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/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
|
#ALGOL-M
|
ALGOL-M
|
BEGIN
INTEGER FUNCTION DIVBY(N, D);
INTEGER N;
INTEGER D;
BEGIN
DIVBY := 1 - (N - D * (N / D));
END;
INTEGER I;
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
IF DIVBY(I, 15) = 1 THEN
WRITE("FizzBuzz")
ELSE IF DIVBY(I, 5) = 1 THEN
WRITE("Buzz")
ELSE IF DIVBY(I, 3) = 1 THEN
WRITE("Fizz")
ELSE
WRITE(I);
END;
END
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Common_Lisp
|
Common Lisp
|
;; Given a date, get the day of the week. Adapted from
;; http://lispcookbook.github.io/cl-cookbook/dates_and_times.html
(defun day-of-week (day month year)
(nth-value
6
(decode-universal-time
(encode-universal-time 0 0 0 day month year 0)
0)))
(defparameter *long-months* '(1 3 5 7 8 10 12))
(defun sundayp (day month year)
(= (day-of-week day month year) 6))
(defun ends-on-sunday-p (month year)
(sundayp 31 month year))
;; We use the "long month that ends on Sunday" rule.
(defun has-five-weekends-p (month year)
(and (member month *long-months*)
(ends-on-sunday-p month year)))
;; For the extra credit problem.
(defun has-at-least-one-five-weekend-month-p (year)
(let ((flag nil))
(loop for month in *long-months* do
(if (has-five-weekends-p month year)
(setf flag t)))
flag))
(defun solve-it ()
(let ((good-months '())
(bad-years 0))
(loop for year from 1900 to 2100 do
;; First form in the PROGN is for the extra credit.
(progn (unless (has-at-least-one-five-weekend-month-p year)
(incf bad-years))
(loop for month in *long-months* do
(when (has-five-weekends-p month year)
(push (list month year) good-months)))))
(let ((len (length good-months)))
(format t "~A months have five weekends.~%" len)
(format t "First 5 months: ~A~%" (subseq good-months (- len 5) len))
(format t "Last 5 months: ~A~%" (subseq good-months 0 5))
(format t "Years without a five-weekend month: ~A~%" bad-years))))
|
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
|
First perfect square in base n with n unique digits
|
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use ntheory qw/fromdigits todigitstring/;
use utf8;
binmode('STDOUT', 'utf8');
sub first_square {
my $n = shift;
my $sr = substr('1023456789abcdef',0,$n);
my $r = int fromdigits($sr, $n) ** .5;
my @digits = reverse split '', $sr;
TRY: while (1) {
my $sq = $r * $r;
my $cnt = 0;
my $s = todigitstring($sq, $n);
my $i = scalar @digits;
for (@digits) {
$r++ and redo TRY if (-1 == index($s, $_)) || ($i-- + $cnt < $n);
last if $cnt++ == $n;
}
return sprintf "Base %2d: %10s² == %s", $n, todigitstring($r, $n),
todigitstring($sq, $n);
}
}
say "First perfect square with N unique digits in base N: ";
say first_square($_) for 2..16;
|
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
|
#E
|
E
|
def sin(x) { return x.sin() }
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
def acos(x) { return x.acos() }
def cube(x) { return x ** 3 }
def curt(x) { return x ** (1/3) }
def forward := [sin, cos, cube]
def reverse := [asin, acos, curt]
|
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.
|
#Julia
|
Julia
|
using Printf
@enum State empty tree fire
function evolution(nepoch::Int=100, init::Matrix{State}=fill(tree, 30, 50))
# Single evolution
function evolve!(forest::Matrix{State}; f::Float64=0.12, p::Float64=0.5)
dir = [-1 -1; -1 0; -1 1; 0 -1; 0 1; 1 -1; 1 0; 1 1]
# A tree will burn if at least one neighbor is burning
for i in 1:size(forest, 1), j in 1:size(forest, 2)
for k in 1:size(dir, 1)
if checkbounds(Bool, forest, i + dir[k, 1], j + dir[k, 2]) &&
get(forest, i + dir[k, 1], j + dir[k, 2]) == fire
forest[i, j] = fire
break
end
end
end
for i in LinearIndices(forest)
# A burning cell turns into an empty cell
if forest[i] == fire forest[i] = empty end
# A tree ignites with probability f even if no neighbor is burning
if forest[i] == tree && rand() < f forest[i] = fire end
# An empty space fills with a tree with probability p
if forest[i] == empty && rand() < p forest[i] = tree end
end
end
# Print functions
function printforest(f::Matrix{State})
for i in 1:size(f, 1)
for j in 1:size(f, 2)
print(f[i, j] == empty ? ' ' : f[i, j] == tree ? '🌲' : '🔥')
end
println()
end
end
function printstats(f::Matrix{State})
tot = length(f)
nt = count(x -> x in (tree, fire), f)
nb = count(x -> x == fire, f)
@printf("\n%6i cell(s), %6i tree(s), %6i currently burning (%6.2f%%, %6.2f%%)\n",
tot, nt, nb, nt / tot * 100, nb / nt * 100)
end
# Main
printforest(init)
printstats(init)
for i in 1:nepoch
# println("\33[2J")
evolve!(init)
# printforest(init)
# printstats(init)
# sleep(1)
end
printforest(init)
printstats(init)
end
evolution()
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun flatten (mylist)
(cond
((null mylist) nil)
((atom mylist) (list mylist))
(t
(append (flatten (car mylist)) (flatten (cdr mylist))))))
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Ring
|
Ring
|
load "guilib.ring"
load "stdlib.ring"
size = 3
flip = newlist(size,size)
board = newlist(size,size)
colflip = list(size)
rowflip = list(size)
new qapp
{
win1 = new qwidget() {
setwindowtitle("Flipping bits game")
setgeometry(465,115,800,600)
label1 = new qlabel(win1) {
setgeometry(285,60,120,40)
settext("Target")
}
label2 = new qlabel(win1) {
setgeometry(285,220,120,40)
settext("Board")
}
for n = 1 to size
for m = 1 to size
flip[n][m] = new qpushbutton(win1) {
setgeometry(200+n*40,60+m*40,40,40)
settext(string(random(1)))
}
next
next
for n = 1 to size
for m = 1 to size
board[n][m] = new qpushbutton(win1) {
setgeometry(200+n*40,260+m*40,40,40)
setclickevent("draw(" + n + "," + m +")")
}
next
next
for n = 1 to size
colflip[n]= new qpushbutton(win1) {
setgeometry(200+n*40,260,40,40)
settext("Go")
setclickevent("coldraw(" + n + ")")
}
next
for n = 1 to size
rowflip[n]= new qpushbutton(win1) {
setgeometry(200,260+n*40,40,40)
settext("Go")
setclickevent("rowdraw(" + n + ")")
}
next
scramblebutton = new qpushbutton(win1) {
setgeometry(240,460,120,40)
settext("Scramble Board")
setclickevent("scramble(flip)")
}
scramblebegin(flip)
show()
}
exec()
}
func coldraw(n)
for row = 1 to size
board[n][row] {temp = text()}
if temp = "0"
board[n][row].settext("1")
else
board[n][row].settext("0")
ok
next
func rowdraw(n)
for col = 1 to size
board[col][n] {temp = text()}
if temp = "0"
board[col][n].settext("1")
else
board[col][n].settext("0")
ok
next
func scramble(flip)
for col = 1 to size
for row = 1 to size
flip[col][row]{temp = text()}
board[col][row].settext(temp)
next
next
for mix = 1 to size*10
colorrow = random(1) + 1
colrow = random(size-1) + 1
if colorrow = 1
rc = "coldraw"
else
rc = "rowdraw"
ok
go = rc + "(" + colrow + ")"
eval(go)
next
func scramblebegin(flip)
for col = 1 to size
for row = 1 to size
flip[col][row]{temp = text()}
board[col][row].settext(temp)
next
next
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Ruby
|
Ruby
|
class FlipBoard
def initialize(size)
raise ArgumentError.new("Invalid board size: #{size}") if size < 2
@size = size
@board = Array.new(size**2, 0)
randomize_board
loop do
@target = generate_target
break unless solved?
end
# these are used for validating user input
@columns = [*'a'...('a'.ord+@size).chr]
@rows = (1..@size).map(&:to_s)
end
############################################################
def play
moves = 0
puts "your target:", target
until solved?
puts "", "move #{moves}:", self
print "Row/column to flip: "
ans = $stdin.gets.strip
if @columns.include? ans
flip_column @columns.index(ans)
moves += 1
elsif @rows.include? ans
flip_row @rows.index(ans)
moves += 1
else
puts "invalid input: " + ans
end
end
puts "", "you solved the game in #{moves} moves", self
end
# the target formation as a string
def target
format_array @target
end
# the current formation as a string
def to_s
format_array @board
end
############################################################
private
def solved?
@board == @target
end
# flip a random number of bits on the board
def randomize_board
(@size + rand(@size)).times do
flip_bit rand(@size), rand(@size)
end
end
# generate a random number of flip_row/flip_column calls
def generate_target
orig_board = @board.clone
(@size + rand(@size)).times do
rand(2).zero? ? flip_row( rand(@size) ) : flip_column( rand(@size) )
end
target, @board = @board, orig_board
target
end
def flip_row(row)
@size.times {|col| flip_bit(row, col)}
end
def flip_column(col)
@size.times {|row| flip_bit(row, col)}
end
def flip_bit(row, col)
@board[@size * row + col] ^= 1
end
def format_array(ary)
str = " " + @columns.join(" ") + "\n"
@size.times do |row|
str << "%2s " % @rows[row] + ary[@size*row, @size].join(" ") + "\n"
end
str
end
end
######################################################################
begin
FlipBoard.new(ARGV.shift.to_i).play
rescue => e
puts e.message
end
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#Sidef
|
Sidef
|
func farey_approximations(r, callback) {
var (a1 = r.int, b1 = 1)
var (a2 = a1+1, b2 = 1)
loop {
var a3 = a1+a2
var b3 = b1+b2
if (a3 < r*b3) {
(a1, b1) = (a3, b3)
}
else {
(a2, b2) = (a3, b3)
}
callback(a3 / b3)
}
}
func p(L, nth) {
define ln2 = log(2)
define ln5 = log(5)
define ln10 = log(10)
var t = L.len-1
func isok(n) {
floor(exp(ln2*(n - floor((n*ln2)/ln10) + t) + ln5*(t - floor((n*ln2)/ln10)))) == L
}
var deltas = gather {
farey_approximations(ln2/ln10, {|r|
take(r.de) if (r.de.len == L.len)
break if (r.de.len > L.len)
})
}.sort.uniq
var c = 0
var k = (1..Inf -> first(isok))
loop {
return k if (++c == nth)
k += (deltas.first {|d| isok(k+d) } \\ die "error: #{k}")
}
}
var tests = [
[12, 1],
[12, 2],
[123, 45],
[123, 12345],
[123, 678910],
# extra
[1234, 10000],
[12345, 10000],
]
for a,b in (tests) {
say "p(#{a}, #{b}) = #{p(a,b)}"
}
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Ruby
|
Ruby
|
multiplier = proc {|n1, n2| proc {|m| n1 * n2 * m}}
numlist = [x=2, y=4, x+y]
invlist = [0.5, 0.25, 1.0/(x+y)]
p numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]}
# => [0.5, 0.5, 0.5]
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Rust
|
Rust
|
#![feature(conservative_impl_trait)]
fn main() {
let (x, xi) = (2.0, 0.5);
let (y, yi) = (4.0, 0.25);
let z = x + y;
let zi = 1.0/z;
let numlist = [x,y,z];
let invlist = [xi,yi,zi];
let result = numlist.iter()
.zip(&invlist)
.map(|(x,y)| multiplier(*x,*y)(0.5))
.collect::<Vec<_>>();
println!("{:?}", result);
}
fn multiplier(x: f64, y: f64) -> impl Fn(f64) -> f64 {
move |m| x*y*m
}
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Scala
|
Scala
|
import Goto._
import scala.util.continuations._
object Goto {
case class Label(k: Label => Unit)
private case class GotoThunk(label: Label) extends Throwable
def label: Label @suspendable =
shift((k: Label => Unit) => executeFrom(Label(k)))
def goto(l: Label): Nothing =
throw new GotoThunk(l)
private def executeFrom(label: Label): Unit = {
val nextLabel = try {
label.k(label)
None
} catch {
case g: GotoThunk => Some(g.label)
}
if (nextLabel.isDefined) executeFrom(nextLabel.get)
}
}
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Sidef
|
Sidef
|
say "Hello"
goto :world
say "Never printed"
@:world
say "World"
|
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.
|
#Groovy
|
Groovy
|
class Floyd {
static void main(String[] args) {
printTriangle(5)
printTriangle(14)
}
private static void printTriangle(int n) {
println(n + " rows:")
int printMe = 1
int numsPrinted = 0
for (int rowNum = 1; rowNum <= n; printMe++) {
int cols = (int) Math.ceil(Math.log10(n * (n - 1) / 2 + numsPrinted + 2))
printf("%" + cols + "d ", printMe)
if (++numsPrinted == rowNum) {
println()
rowNum++
numsPrinted = 0
}
}
}
}
|
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
|
Floyd-Warshall algorithm
|
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#Python
|
Python
|
from math import inf
from itertools import product
def floyd_warshall(n, edge):
rn = range(n)
dist = [[inf] * n for i in rn]
nxt = [[0] * n for i in rn]
for i in rn:
dist[i][i] = 0
for u, v, w in edge:
dist[u-1][v-1] = w
nxt[u-1][v-1] = v-1
for k, i, j in product(rn, repeat=3):
sum_ik_kj = dist[i][k] + dist[k][j]
if dist[i][j] > sum_ik_kj:
dist[i][j] = sum_ik_kj
nxt[i][j] = nxt[i][k]
print("pair dist path")
for i, j in product(rn, repeat=2):
if i != j:
path = [i]
while path[-1] != j:
path.append(nxt[path[-1]][j])
print("%d → %d %4d %s"
% (i + 1, j + 1, dist[i][j],
' → '.join(str(p + 1) for p in path)))
if __name__ == '__main__':
floyd_warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]])
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#UNIX_Shell
|
UNIX Shell
|
multiply() {
# There is never anything between the parentheses after the function name
# Arguments are obtained using the positional parameters $1, and $2
# The return is given as a parameter to the return command
return `expr "$1" \* "$2"` # The backslash is required to suppress interpolation
}
# Call the function
multiply 3 4 # The function is invoked in statement context
echo $? # The dollarhook special variable gives the return value
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#Racket
|
Racket
|
#lang racket
(define (forward-difference list)
(for/list ([x (cdr list)] [y list]) (- x y)))
(define (nth-forward-difference n list)
(for/fold ([list list]) ([n n]) (forward-difference list)))
(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#Raku
|
Raku
|
sub dif(@array [$, *@tail]) { @tail Z- @array }
sub difn($array, $n) { ($array, &dif ... *)[$n] }
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#XPL0
|
XPL0
|
int C;
[Format(5, 3); \5 places before decimal point and 3 after
RlOut(8, 7.125); \output real number to internal buffer
loop [C:= ChIn(8); \read character from internal buffer
if C = ^ then C:= ^0; \change leading space characters to zeros
if C = $1A then quit; \exit loop on end-of-file (EOF = end of chars)
ChOut(0, C); \display digit character on terminal
];
]
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#XSLT
|
XSLT
|
<xsl:value-of select="format-number(7.125, '00000000.#############')" />
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#Ruby
|
Ruby
|
# returns pair [sum, carry]
def four_bit_adder(a, b)
a_bits = binary_string_to_bits(a,4)
b_bits = binary_string_to_bits(b,4)
s0, c0 = full_adder(a_bits[0], b_bits[0], 0)
s1, c1 = full_adder(a_bits[1], b_bits[1], c0)
s2, c2 = full_adder(a_bits[2], b_bits[2], c1)
s3, c3 = full_adder(a_bits[3], b_bits[3], c2)
[bits_to_binary_string([s0, s1, s2, s3]), c3.to_s]
end
# returns pair [sum, carry]
def full_adder(a, b, c0)
s, c = half_adder(c0, a)
s, c1 = half_adder(s, b)
[s, _or(c,c1)]
end
# returns pair [sum, carry]
def half_adder(a, b)
[xor(a, b), _and(a,b)]
end
def xor(a, b)
_or(_and(a, _not(b)), _and(_not(a), b))
end
# "and", "or" and "not" are Ruby keywords
def _and(a, b) a & b end
def _or(a, b) a | b end
def _not(a) ~a & 1 end
def int_to_binary_string(n, length)
"%0#{length}b" % n
end
def binary_string_to_bits(s, length)
("%#{length}s" % s).reverse.chars.map(&:to_i)
end
def bits_to_binary_string(bits)
bits.map(&:to_s).reverse.join
end
puts " A B A B C S sum"
0.upto(15) do |a|
0.upto(15) do |b|
bin_a = int_to_binary_string(a, 4)
bin_b = int_to_binary_string(b, 4)
sum, carry = four_bit_adder(bin_a, bin_b)
puts "%2d + %2d = %s + %s = %s %s = %2d" %
[a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)]
end
end
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#PicoLisp
|
PicoLisp
|
(de median (Lst)
(let N (length Lst)
(if (bit? 1 N)
(get Lst (/ (inc N) 2))
(setq Lst (nth Lst (/ N 2)))
(/ (+ (car Lst) (cadr Lst)) 2) ) ) )
(de fivenum (Lst) # destructive
(let
(Len (length Lst)
M (/ Len 2)
S (sort Lst) )
(list
(format (car S) *Scl)
(format
(median (head (+ M (% Len 2)) S))
*Scl )
(format (median S) *Scl)
(format (median (tail M S)) *Scl)
(format (last S) *Scl) ) ) )
(scl 2)
(println (fivenum (36.0 40.0 7.0 39.0 41.0 15.0)))
(scl 8)
(println
(fivenum
(0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594
0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772
0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469
0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 ) ) )
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#Python
|
Python
|
from __future__ import division
import math
import sys
def fivenum(array):
n = len(array)
if n == 0:
print("you entered an empty array.")
sys.exit()
x = sorted(array)
n4 = math.floor((n+3.0)/2.0)/2.0
d = [1, n4, (n+1)/2, n+1-n4, n]
sum_array = []
for e in range(5):
floor = int(math.floor(d[e] - 1))
ceil = int(math.ceil(d[e] - 1))
sum_array.append(0.5 * (x[floor] + x[ceil]))
return sum_array
x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,
-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,
1.04312009, -0.10305385, 0.75775634, 0.32566578]
y = fivenum(x)
print(y)
|
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)
|
#BBC_BASIC
|
BBC BASIC
|
DIM perms$(22), miss&(4)
perms$() = "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", \
\ "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", \
\ "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
FOR i% = 0 TO DIM(perms$(),1)
FOR j% = 1 TO DIM(miss&(),1)
miss&(j%-1) EOR= ASCMID$(perms$(i%),j%)
NEXT
NEXT
PRINT $$^miss&(0) " is missing"
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
|
#Clojure
|
Clojure
|
(ns last-sundays.core
(:require [clj-time.core :as time]
[clj-time.periodic :refer [periodic-seq]]
[clj-time.format :as fmt])
(:import (org.joda.time DateTime DateTimeConstants))
(:gen-class))
(defn sunday? [t]
(= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))
(defn sundays [year]
(take-while #(= (time/year %) year)
(filter sunday? (periodic-seq (time/date-time year 1 1) (time/days 1)))))
(defn last-sundays-of-months [year]
(->> (sundays year)
(group-by time/month)
(vals)
(map (comp first #(sort-by time/day > %)))
(map #(fmt/unparse (fmt/formatters :year-month-day) %))
(interpose "\n")
(apply str)))
(defn -main [& args]
(println (last-sundays-of-months (Integer. (first args)))))
|
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) .
|
#F.23
|
F#
|
(*
Find the point of intersection of 2 lines.
Nigel Galloway May 20th., 2017
*)
type Line={a:float;b:float;c:float} member N.toS=sprintf "%.2fx + %.2fy = %.2f" N.a N.b N.c
let intersect (n:Line) g = match (n.a*g.b-g.a*n.b) with
|0.0 ->printfn "%s does not intersect %s" n.toS g.toS
|ng ->printfn "%s intersects %s at x=%.2f y=%.2f" n.toS g.toS ((g.b*n.c-n.b*g.c)/ng) ((n.a*g.c-g.a*n.c)/ng)
let fn (i,g) (e,l) = {a=g-l;b=e-i;c=(e-i)*g+(g-l)*i}
intersect (fn (4.0,0.0) (6.0,10.0)) (fn (0.0,3.0) (10.0,7.0))
intersect {a=3.18;b=4.23;c=7.13} {a=6.36;b=8.46;c=9.75}
|
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].
|
#Factor
|
Factor
|
USING: io locals math.vectors prettyprint ;
:: intersection-point ( rdir rpt pnorm ppt -- loc )
rpt rdir pnorm rpt ppt v- v. v*n rdir pnorm v. v/n v- ;
"The ray intersects the plane at " write
{ 0 -1 -1 } { 0 0 10 } { 0 0 1 } { 0 0 5 } intersection-point .
|
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
|
Find the intersection of a line with a plane
|
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
|
#FreeBASIC
|
FreeBASIC
|
' version 11-07-2018
' compile with: fbc -s console
Type vector3d
Dim As Double x, y ,z
Declare Constructor ()
Declare Constructor (ByVal x As Double, ByVal y As Double, ByVal z As Double)
End Type
Constructor vector3d()
This.x = 0
This.y = 0
This.z = 0
End Constructor
Constructor vector3d(ByVal x As Double, ByVal y As Double, ByVal z As Double)
This.x = x
This.y = y
This.z = z
End Constructor
Operator + (lhs As vector3d, rhs As vector3d) As vector3d
Return Type(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
End Operator
Operator - (lhs As vector3d, rhs As vector3d) As vector3d
Return Type(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
End Operator
Operator * (lhs As vector3d, d As Double) As vector3d
Return Type(lhs.x * d, lhs.y * d, lhs.z * d)
End Operator
Function dot(lhs As vector3d, rhs As vector3d) As Double
Return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
End Function
Function tostring(vec As vector3d) As String
Return "(" + Str(vec.x) + ", " + Str(vec.y) + ", " + Str(vec.z) + ")"
End Function
Function intersectpoint(rayvector As vector3d, raypoint As vector3d, _
planenormal As vector3d, planepoint As vector3d) As vector3d
Dim As vector3d diff = raypoint - planepoint
Dim As Double prod1 = dot(diff, planenormal)
Dim As double prod2 = dot(rayvector, planenormal)
Return raypoint - rayvector * (prod1 / prod2)
End Function
' ------=< MAIN >=------
Dim As vector3d rv = Type(0, -1, -1)
Dim As vector3d rp = Type(0, 0, 10)
Dim As vector3d pn = Type(0, 0, 1)
Dim As vector3d pp = Type(0, 0, 5)
Dim As vector3d ip = intersectpoint(rv, rp, pn, pp)
print
Print "line intersects the plane at "; tostring(ip)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
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
|
#ALGOL_W
|
ALGOL W
|
begin
i_w := 1; % set integers to print in minimum space %
for i := 1 until 100 do begin
if i rem 15 = 0 then write( "FizzBuzz" )
else if i rem 5 = 0 then write( "Buzz" )
else if i rem 3 = 0 then write( "Fizz" )
else write( i )
end for_i
end.
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#D
|
D
|
import std.stdio, std.datetime, std.algorithm, std.range;
Date[] m5w(in Date start, in Date end) pure /*nothrow*/ {
typeof(return) res;
// adjust to 1st day
for (Date when = Date(start.year, start.month, 1);
when < end;
when.add!"months"(1))
// Such month must have 3+4*7 days and start at friday
// for 5 FULL weekends.
if (when.daysInMonth == 31 &&
when.dayOfWeek == DayOfWeek.fri)
res ~= when;
return res;
}
bool noM5wByYear(in int year) pure {
return m5w(Date(year, 1, 1), Date(year, 12, 31)).empty;
}
void main() {
immutable m = m5w(Date(1900, 1, 1), Date(2100, 12, 31));
writeln("There are ", m.length,
" months of which the first and last five are:");
foreach (d; m[0 .. 5] ~ m[$ - 5 .. $])
writeln(d.toSimpleString()[0 .. $ - 3]);
immutable n = iota(1900, 2101).filter!noM5wByYear().walkLength();
writefln("\nThere are %d years in the range that do not have " ~
"months with five weekends.", n);
}
|
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
|
First perfect square in base n with n unique digits
|
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#Phix
|
Phix
|
-- demo\rosetta\PandigitalSquares.exw
without javascript_semantics -- (mpz_set_str() currently only supports bases 2, 8, 10, and 16 under pwa/p2js)
include mpfr.e
atom t0 = time()
constant chars = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz|",
use_hll_code = true
function str_conv(sequence s, integer mode=+1)
-- mode of +1: eg {1,2,3} -> "123", mode of -1 the reverse.
-- note this doesn't really care what base s/res are in.
{sequence res,integer dcheck} = iff(mode=+1?{"",9}:{{},'9'})
for i=1 to length(s) do
integer d = s[i]
d += mode*iff(d>dcheck?'a'-10:'0')
res &= d
end for
return res
end function
procedure do_one(integer base)
-- tabulates one base
integer bm1 = base-1,
dr = iff(and_bits(base,1) ? floor(base/2) : 0),
id = 0,
rc = 0,
sdri
atom st = time()
sequence sdr = repeat(0,bm1)
for i=0 to bm1-1 do
sdri = mod(i*i,bm1)
rc += (sdri==dr)
sdr[i+1] = iff(sdri=0 ? bm1 : sdri)
end for
if dr>0 then
id = base
for i=1 to dr do
sdri = sdr[i+1]
if sdri>=dr
and id>sdri then
id = sdri
end if
end for
id -= dr
end if
string sq = chars[1..base]
if id>0 then sq = sq[1..id]&chars[id+1]&sq[id+1..$] end if
sq[1..2] = "10"
mpz sqz = mpz_init(),
rtz = mpz_init(),
dnz = mpz_init(),
tmp = mpz_init()
mpz_set_str(sqz,sq,base)
mpz_sqrt(rtz,sqz)
mpz_add_ui(rtz,rtz,1) -- rtz = sqrt(sqz)+1
mpz_mul_si(dnz,rtz,2)
mpz_add_si(dnz,dnz,1) -- dnz = rtz*2+1
mpz_mul(sqz,rtz,rtz) -- sqz = rtz * rtz
integer d = 1,
inc = 1
if base>3 and rc>0 then
while mpz_fdiv_ui(sqz,bm1)!=dr do
-- align sqz to dr
mpz_add_ui(rtz,rtz,1) -- rtz += 1
mpz_add(sqz,sqz,dnz) -- sqz += dnz
mpz_add_ui(dnz,dnz,2) -- dnz += 2
end while
inc = floor(bm1/rc)
if inc>1 then
mpz_mul_si(tmp,rtz,inc-2)
mpz_sub_ui(tmp,tmp,1)
mpz_add(dnz,dnz,tmp) -- dnz += rtz*(inc-2)-1
end if
d = inc * inc
mpz_add(dnz,dnz,dnz)
mpz_add_ui(dnz,dnz,d) -- dnz += dnz + d
end if
d *= 2
atom mask, fullmask = power(2,base)-1 -- ie 0b111..
integer icount = 0
mpz_set_si(tmp,d)
sequence sqi = str_conv(mpz_get_str(sqz,base), mode:=-1),
dni = str_conv(mpz_get_str(dnz,base), mode:=-1),
dti = str_conv(mpz_get_str(tmp,base), mode:=-1)
while true do
if use_hll_code then
mask = 0
for i=1 to length(sqi) do
mask = or_bits(mask,power(2,sqi[i]))
end for
else
?9/0 -- see below, inline part 1
end if
if mask=fullmask then exit end if
integer carry = 0, sidx, si
if use_hll_code then
for sidx=-1 to -length(dni) by -1 do
si = sqi[sidx]+dni[sidx]+carry
carry = si>=base
sqi[sidx] = si-carry*base
end for
sidx += length(sqi)+1
while carry and sidx do
si = sqi[sidx]+carry
carry = si>=base
sqi[sidx] = si-carry*base
sidx -= 1
end while
else
?9/0 --see below, inline part 2
end if
if carry then
sqi = carry&sqi
end if
carry = 0
for sidx=-1 to -length(dti) by -1 do
si = dni[sidx]+dti[sidx]+carry
carry = floor(si/base)
dni[sidx] = remainder(si,base)
end for
sidx += length(dni)+1
while carry and sidx do
si = dni[sidx]+carry
carry = si>=base
dni[sidx] = si-carry*base
sidx -= 1
end while
if carry then
dni = carry&dni
end if
icount += 1
end while
mpz_set_si(tmp,icount)
mpz_mul_si(tmp,tmp,inc)
mpz_add(rtz,rtz,tmp) -- rtz += icount * inc
sq = str_conv(sqi, mode:=+1)
string rt = mpz_get_str(rtz,base),
idstr = iff(id?sprintf("%d",id):" "),
ethis = elapsed_short(time()-st),
etotal = elapsed_short(time()-t0)
printf(1,"%3d %3d %s %18s -> %-28s %10d %8s %8s\n",
{base, inc, idstr, rt, sq, icount, ethis, etotal})
{sqz,rtz,dnz,tmp} = mpz_free({sqz,rtz,dnz,tmp})
end procedure
puts(1,"base inc id root -> square" &
" test count time total\n")
for base=2 to 19 do
--for base=2 to 25 do
--for base=2 to 28 do
do_one(base)
end for
printf(1,"completed in %s\n", {elapsed(time()-t0)})
|
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
|
#EchoLisp
|
EchoLisp
|
;; adapted from Racket
;; (compose f g h ... ) is a built-in defined as :
;; (define (compose f g) (λ (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (// 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
(for ([f funlist] [i ifunlist])
(writeln ((compose i f) 0.5)))
→
0.5
0.4999999999999999
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.
|
#Lua
|
Lua
|
-- ForestFire automaton implementation
-- Rules: at each step:
-- 1) a burning tree disappears
-- 2) a non-burning tree starts burning if any of its neighbours is
-- 3) an empty spot may generate a tree with prob P
-- 4) a non-burning tree may ignite with prob F
local socket = require 'socket' -- needed for socket.sleep
local curses = require 'curses'
local p_spawn, p_ignite = 0.005, 0.0002
local naptime = 0.03 -- seconds
local forest_x, forest_y = 60, 30
local forest = (function (x, y)
local wrl = {}
for i = 1, y do
wrl[i] = {}
for j = 1, x do
local rand = math.random()
wrl[i][j] = (rand < 0.5) and 1 or 0
end
end
return wrl
end)(forest_x, forest_y)
math.randomseed(os.time())
forest.step = function (self)
for i = 1, #self do
for j = 1, #self[i] do
if self[i][j] == 0 then
if math.random() < p_spawn then self[i][j] = 1 end
elseif self[i][j] == 1 then
if self:ignite(i, j) or math.random() < p_ignite then self[i][j] = 2 end
elseif self[i][j] == 2 then self[i][j] = 0
else error("Error: forest[" .. i .. "][" .. j .. "] is " .. self[i][j] .. "!")
end
end
end
end
forest.draw = function (self)
for i = 1, #self do
for j = 1, #self[i] do
if self[i][j] == 0 then win:mvaddch(i,j," ")
elseif self[i][j] == 1 then
win:attron(curses.color_pair(1))
win:mvaddch(i,j,"Y")
win:attroff(curses.color_pair(1))
elseif self[i][j] == 2 then
win:attron(curses.color_pair(2))
win:mvaddch(i,j,"#")
win:attroff(curses.color_pair(2))
else error("self[" .. i .. "][" .. j .. "] is " .. self[i][j] .. "!")
end
end
end
end
forest.ignite = function (self, i, j)
for k = i - 1, i + 1 do
if k < 1 or k > #self then goto continue1 end
for l = j - 1, j + 1 do
if l < 1 or
l > #self[i] or
math.abs((k - i) + (l - j)) ~= 1
then
goto continue2
end
if self[k][l] == 2 then return true end
::continue2::
end
::continue1::
end
return false
end
local it = 1
curses.initscr()
curses.start_color()
curses.echo(false)
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
win = curses.newwin(forest_y + 2, forest_x, 0, 0)
win:clear()
win:mvaddstr(forest_y + 1, 0, "p_spawn = " .. p_spawn .. ", p_ignite = " .. p_ignite)
repeat
forest:draw()
win:move(forest_y, 0)
win:clrtoeol()
win:addstr("Iteration: " .. it .. ", nap = " .. naptime*1000 .. "ms")
win:refresh()
forest:step()
it = it + 1
socket.sleep(naptime)
until false
|
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
|
#Erlang
|
Erlang
|
flatten([]) -> [];
flatten([H|T]) -> flatten(H) ++ flatten(T);
flatten(H) -> [H].
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Rust
|
Rust
|
// For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
/// A simple struct for a board
struct Board {
/// The cells of the board
cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Functions for the Board struct
impl Board {
/// Generate a new, empty board, of size >= 1
///
/// Returns a Board in the "off" state, where all cells are 0.
/// If a size of 0 is given, a Board of size 1 will be created instead.
/// A mutable board is required for using Board::fliprow and Board::flipcol functions.
///
/// ```
/// let mut board: Board = Board::new(3);
/// ```
fn new(size: usize) -> Board {
// Ensure we make a board with a non-zero size
if size > 0 {
Board {
cells: vec![false; size * size],
size,
}
} else {
Board::new(1)
}
}
/// Flip the specified row
///
/// Returns true if the row is within the size, false otherwise.
///
/// ```
/// let mut board: Board = Board::new(3);
/// board.fliprow(1);
/// ```
fn fliprow(&mut self, row: usize) -> bool {
// Check constraints
if row > self.size {
return false;
}
// Starting position in the vector
let start = row * self.size;
// Loop through the vector row
for i in start..start + self.size {
self.cells[i] = !self.cells[i];
}
true
}
/// Flip the specified column
///
/// Returns true if the column is within the size, false otherwise.
///
/// ```
/// let mut board: Board = Board::new(3);
/// board.flipcol(0);
/// ```
fn flipcol(&mut self, col: usize) -> bool {
// Check constraints
if col > self.size {
return false;
}
// Loop through the vector column
for i in 0..self.size {
self.cells[col + i * self.size] = !self.cells[col + i * self.size];
}
true
}
/// Generate a random board
///
/// Returns a Board in a random state.
/// If a size of 0 is given, a Board of size 1 will be created instead.
///
/// ```
/// let target: Board = Board::random(3);
/// ```
fn random<R: Rng>(rng: &mut R, size: usize) -> Board {
// Ensure we make a board with a non-zero size
if size == 0 {
return Board::random(rng, 1);
}
// Make a vector of the board size with random bits
let cells = (0..size * size)
.map(|_| rng.gen::<bool>())
.collect::<Vec<_>>();
// Return the random board
Board { cells, size }
}
}
impl PartialEq for Board {
fn eq(&self, rhs: &Board) -> bool {
self.cells == rhs.cells
}
}
// Implement the Display format, used with `print!("{}", &board);`
impl fmt::Display for Board {
// Example output:
// 0 1 2
// 0 0 1 0
// 1 1 0 0
// 2 0 1 1
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Get the string width of the size of the board
let width = (self.size - 1).to_string().len();
// Write the initial spaces (upper left)
write!(f, "{space: >0$}", width, space = " ")?;
// Write the column numbers
for i in 0..self.size {
write!(f, " {offset:>0$}", width, offset = i)?;
}
// Newline for rows
writeln!(f)?;
// Loop through the rows
for row in 0..self.size {
// Write the row number
write!(f, "{row:>0$}", width, row = row)?;
// Loop through the columns
for col in 0..self.size {
// Get the value of the cell as 1 or 0
let p = self.cells[row * self.size + col] as usize;
// Write the column value
write!(f, " {col:>0$}", width, col = p)?;
}
// Newline for next row
writeln!(f)?;
}
// Return Formatter result
Ok(())
}
}
fn main() {
let mut rng = rand::thread_rng();
// The board size
let size: usize = 3;
// The target board
let target: Board = Board::random(&mut rng, size);
// The user board
let mut board: Board = Board::new(size);
// How many moves taken
let mut moves: u32 = 0;
// Loop until win or quit
'mainloop: loop {
// User input
let mut input: String;
// Write the boards
println!("Target:\n{}\nBoard:\n{}", &target, &board);
// User input loop
'userinput: loop {
// Prompt
print!("\nFlip? [q|[r|c]#] ");
// Flush stdout to write the previous print, if we can't then exit
match std::io::stdout().flush() {
Ok(_) => {}
Err(e) => {
println!("Error: cannot flush stdout: {}", e);
break 'mainloop;
}
};
// Reset input for each loop
input = String::new();
// Read user input
match std::io::stdin().read_line(&mut input) {
Ok(_) => {
input = input.trim().to_string();
// Get the first character
let rc: char = match input.chars().next() {
Some(c) => c,
None => {
println!("Error: No input");
continue 'userinput;
}
};
// Make sure input is r, c, or q
if rc != 'r' && rc != 'c' && rc != 'q' {
println!("Error: '{}': Must use 'r'ow or 'c'olumn or 'q'uit", rc);
continue 'userinput;
}
// If input is q, exit game
if rc == 'q' {
println!("Thanks for playing!");
break 'mainloop;
}
// If input is r or c, get the number after
let n: usize = match input[1..].to_string().parse() {
Ok(x) => {
// If we're within bounds, return the parsed number
if x < size {
x
} else {
println!(
"Error: Must specify a row or column within size({})",
size
);
continue 'userinput;
}
}
Err(_) => {
println!(
"Error: '{}': Unable to parse row or column number",
input[1..].to_string()
);
continue 'userinput;
}
};
// Flip the row or column specified
match rc {
'r' => board.fliprow(n),
'c' => board.flipcol(n),
_ => {
// We want to panic here because should NEVER
// have anything other than 'r' or 'c' here
panic!("How did you end up here?");
}
};
// Increment moves
moves += 1;
println!("Moves taken: {}", moves);
break 'userinput;
}
Err(e) => {
println!("Error reading input: {}", e);
break 'mainloop;
}
}
} // 'userinput
if board == target {
println!("You win!");
break;
}
} // 'mainloop
}
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#Swift
|
Swift
|
let ld10 = log(2.0) / log(10.0)
func p(L: Int, n: Int) -> Int {
var l = L
var digits = 1
while l >= 10 {
digits *= 10
l /= 10
}
var count = 0
var i = 0
while count < n {
let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1)
let e = exp(log(10.0) * rhs)
if Int(e * Double(digits)) == L {
count += 1
}
i += 1
}
return i - 1
}
let cases = [
(12, 1),
(12, 2),
(123, 45),
(123, 12345),
(123, 678910)
]
for (l, n) in cases {
print("p(\(l), \(n)) = \(p(L: l, n: n))")
}
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Function Func(ByVal l As Integer, ByVal n As Integer) As Long
Dim res As Long = 0, f As Long = 1
Dim lf As Double = Math.Log10(2)
Dim i As Integer = l
While i > 10
f *= 10
i /= 10
End While
While n > 0
res += 1
If CInt((f * Math.Pow(10, res * lf Mod 1))) = l Then
n -= 1
End If
End While
Return res
End Function
Sub Main()
Dim values = {Tuple.Create(12, 1), Tuple.Create(12, 2), Tuple.Create(123, 45), Tuple.Create(123, 12345), Tuple.Create(123, 678910), Tuple.Create(99, 1)}
For Each pair In values
Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", pair.Item1, pair.Item2, Func(pair.Item1, pair.Item2))
Next
End Sub
End Module
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Scala
|
Scala
|
scala> val x = 2.0
x: Double = 2.0
scala> val xi = 0.5
xi: Double = 0.5
scala> val y = 4.0
y: Double = 4.0
scala> val yi = 0.25
yi: Double = 0.25
scala> val z = x + y
z: Double = 6.0
scala> val zi = 1.0 / ( x + y )
zi: Double = 0.16666666666666666
scala> val numbers = List(x, y, z)
numbers: List[Double] = List(2.0, 4.0, 6.0)
scala> val inverses = List(xi, yi, zi)
inverses: List[Double] = List(0.5, 0.25, 0.16666666666666666)
scala> def multiplier = (n1: Double, n2: Double) => (m: Double) => n1 * n2 * m
multiplier: (Double, Double) => (Double) => Double
scala> def comp = numbers zip inverses map multiplier.tupled
comp: List[(Double) => Double]
scala> comp.foreach(f=>println(f(0.5)))
0.5
0.5
0.5
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Scheme
|
Scheme
|
(define x 2.0)
(define xi 0.5)
(define y 4.0)
(define yi 0.25)
(define z (+ x y))
(define zi (/ (+ x y)))
(define number (list x y z))
(define inverse (list xi yi zi))
(define (multiplier n1 n2) (lambda (m) (* n1 n2 m)))
(define m 0.5)
(define (go n1 n2)
(for-each (lambda (n1 n2)
(display ((multiplier n1 n2) m))
(newline))
n1 n2))
(go number inverse)
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#SSEM
|
SSEM
|
00101000000000000000000000000000 20 to CI
...
01010000000000000000000000000000 20. 10
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Stata
|
Stata
|
mata
function pythagorean_triple(n) {
for (a=1; a<=n; a++) {
for (b=a; b<=n-a; b++) {
c=n-a-b
if (c>b & c*c==a*a+b*b) {
printf("%f %f %f\n",a,b,c)
goto END
}
}
}
END:
}
pythagorean_triple(1980)
165 900 915
|
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.
|
#Haskell
|
Haskell
|
--------------------- FLOYDS TRIANGLE --------------------
floydTriangle :: [[Int]]
floydTriangle =
( zipWith
(fmap (.) enumFromTo <*> (\a b -> pred (a + b)))
<$> scanl (+) 1
<*> id
)
[1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ (putStrLn . formatFT) [5, 14]
------------------------- DISPLAY ------------------------
formatFT :: Int -> String
formatFT n = unlines $ unwords . zipWith alignR ws <$> t
where
t = take n floydTriangle
ws = length . show <$> last t
alignR :: Int -> Int -> String
alignR n =
( (<>)
=<< flip replicate ' '
. (-) n
. length
)
. show
|
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
|
Floyd-Warshall algorithm
|
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#Racket
|
Racket
|
#lang typed/racket
(require math/array)
;; in : initialized dist and next matrices
;; out : dist and next matrices
;; O(n^3)
(define-type Next-T (Option Index))
(define-type Dist-T Real)
(define-type Dists (Array Dist-T))
(define-type Nexts (Array Next-T))
(define-type Settable-Dists (Settable-Array Dist-T))
(define-type Settable-Nexts (Settable-Array Next-T))
(: floyd-with-path (-> Index Dists Nexts (Values Dists Nexts)))
(: init-edges (-> Index (Values Settable-Dists Settable-Nexts)))
(define (floyd-with-path n dist-in next-in)
(define dist : Settable-Dists (array->mutable-array dist-in))
(define next : Settable-Nexts (array->mutable-array next-in))
(for* ((k n) (i n) (j n))
(when (negative? (array-ref dist (vector j j)))
(raise 'negative-cycle))
(define i.k (vector i k))
(define i.j (vector i j))
(define d (+ (array-ref dist i.k) (array-ref dist (vector k j))))
(when (< d (array-ref dist i.j))
(array-set! dist i.j d)
(array-set! next i.j (array-ref next i.k))))
(values dist next))
;; utilities
;; init random edges costs, matrix 66% filled
(define (init-edges n)
(define dist : Settable-Dists (array->mutable-array (make-array (vector n n) 0)))
(define next : Settable-Nexts (array->mutable-array (make-array (vector n n) #f)))
(for* ((i n) (j n) #:unless (= i j))
(define i.j (vector i j))
(array-set! dist i.j +Inf.0)
(unless (< (random) 0.3)
(array-set! dist i.j (add1 (random 100)))
(array-set! next i.j j)))
(values dist next))
;; show path from u to v
(: path (-> Nexts Index Index (Listof Index)))
(define (path next u v)
(let loop : (Listof Index) ((u : Index u) (rv : (Listof Index) null))
(if (= u v)
(reverse (cons u rv))
(let ((nxt (array-ref next (vector u v))))
(if nxt (loop nxt (cons u rv)) null)))))
;; show computed distance
(: mdist (-> Dists Index Index Dist-T))
(define (mdist dist u v)
(array-ref dist (vector u v)))
(module+ main
(define n 8)
(define-values (dist next) (init-edges n))
(define-values (dist+ next+) (floyd-with-path n dist next))
(displayln "original dist")
dist
(displayln "new dist and next")
dist+
next+
;; note, these path and dist calls are not as carefully crafted as
;; the echolisp ones (in fact they're verbatim copied)
(displayln "paths and distances")
(path next+ 1 3)
(mdist dist+ 1 0)
(mdist dist+ 0 3)
(mdist dist+ 1 3)
(path next+ 7 6)
(path next+ 6 7))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Ursa
|
Ursa
|
# multiply is a built-in in ursa, so the function is called mult instead
def mult (int a, int b)
return (* a b)
end
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Ursala
|
Ursala
|
multiply = math..mul
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#REXX
|
REXX
|
/*REXX program computes the forward difference of a list of numbers. */
numeric digits 100 /*ensure enough accuracy (decimal digs)*/
parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */
if e=='' then e=90 47 58 29 22 32 55 5 55 73 /*Not specified? Then use the default.*/
#=words(e) /*# is the number of elements in list.*/
/* [↓] assign list numbers to @ array.*/
do i=1 for #; @.i=word(e, i)/1; end /*i*/ /*process each number one at a time. */
/* [↓] process the optional order. */
if N=='' then parse value 0 # # with bot top N /*define the default order range. */
else parse var N bot 1 top /*Not specified? Then use only 1 order*/
say right(# 'numbers:', 44) e /*display the header title and ··· */
say left('', 44)copies('─', length(e)+2) /* " " " fence. */
/* [↓] where da rubber meets da road. */
do o=bot to top; do r=1 for #; [email protected]; end /*r*/; $=
do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k; end /*k*/
end /*j*/
do i=o+1 to #; $=$ !.i/1; end /*i*/
if $=='' then $=' [null]'
say right(o, 7)th(o)'─order forward difference vector =' $
end /*o*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#zkl
|
zkl
|
"%09.3f".fmt(7.125) //-->"00007.125"
"%09.3e".fmt(7.125) //-->"7.125e+00"
"%09.3g".fmt(7.125) //-->"000007.12"
"%09d".fmt(7.125) //-->"000000007"
"%09,d".fmt(78901.125)//-->"00078,901"
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET n=7.125
20 LET width=9
30 GO SUB 1000
40 PRINT AT 10,10;n$
50 STOP
1000 REM Formatted fixed-length
1010 LET n$=STR$ n
1020 FOR i=1 TO width-LEN n$
1030 LET n$="0"+n$
1040 NEXT i
1050 RETURN
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#Rust
|
Rust
|
// half adder with XOR and AND
// SUM = A XOR B
// CARRY = A.B
fn half_adder(a: usize, b: usize) -> (usize, usize) {
return (a ^ b, a & b);
}
// full adder as a combination of half adders
// SUM = A XOR B XOR C
// CARRY = A.B + B.C + C.A
fn full_adder(a: usize, b: usize, c_in: usize) -> (usize, usize) {
let (s0, c0) = half_adder(a, b);
let (s1, c1) = half_adder(s0, c_in);
return (s1, c0 | c1);
}
// A = (A3, A2, A1, A0)
// B = (B3, B2, B1, B0)
// S = (S3, S2, S1, S0)
fn four_bit_adder (
a: (usize, usize, usize, usize),
b: (usize, usize, usize, usize)
)
->
// 4 bit output, carry is ignored
(usize, usize, usize, usize)
{
// lets have a.0 refer to the rightmost element
let a = a.reverse();
let b = b.reverse();
// i would prefer a loop but that would abstract
// the "connections of the constructive blocks"
let (sum, carry) = half_adder(a.0, b.0);
let out0 = sum;
let (sum, carry) = full_adder(a.1, b.1, carry);
let out1 = sum;
let (sum, carry) = full_adder(a.2, b.2, carry);
let out2 = sum;
let (sum, _) = full_adder(a.3, b.3, carry);
let out3 = sum;
return (out3, out2, out1, out0);
}
fn main() {
let a: (usize, usize, usize, usize) = (0, 1, 1, 0);
let b: (usize, usize, usize, usize) = (0, 1, 1, 0);
assert_eq!(four_bit_adder(a, b), (1, 1, 0, 0));
// 0110 + 0110 = 1100
// 6 + 6 = 12
}
// misc. traits to make our life easier
trait Reverse<A, B, C, D> {
fn reverse(self) -> (D, C, B, A);
}
// reverse a generic tuple of arity 4
impl<A, B, C, D> Reverse<A, B, C, D> for (A, B, C, D) {
fn reverse(self) -> (D, C, B, A){
return (self.3, self.2, self.1, self.0)
}
}
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#R
|
R
|
x <- c(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578)
fivenum(x)
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#Racket
|
Racket
|
#lang racket/base
(require math/private/statistics/quickselect)
;; racket's quantile uses "Method 1" of https://en.wikipedia.org/wiki/Quartile
;; Tukey (fivenum) uses "Method 2", so we will need a specialist median
(define (fivenum! data-v)
(define (tukey-median start end)
(define-values (n/2 parity) (quotient/remainder (- end start) 2))
(define mid (+ start n/2))
(if (zero? parity)
(/ (+ (data-kth-value! (+ mid (sub1 parity))) (data-kth-value! mid)) 2)
(data-kth-value! mid)))
(define n-data (let ((l (vector-length data-v)))
(if (zero? l)
(raise-argument-error 'data-v "nonempty (Vectorof Real)" data-v)
l)))
(define (data-kth-value! n) (kth-value! data-v n <))
(define subset-size (let-values (((n/2 parity) (quotient/remainder n-data 2))) (+ n/2 parity)))
(vector (data-kth-value! 0)
(tukey-median 0 subset-size)
(tukey-median 0 n-data)
(tukey-median (- n-data subset-size) n-data)
(data-kth-value! (sub1 n-data))))
(define (fivenum data-seq)
(fivenum! (if (and (vector? data-seq) (not (immutable? data-seq)))
data-seq
(for/vector ((datum data-seq)) datum))))
(module+ test
(require rackunit
racket/vector)
(check-equal? #(14 14 14 14 14) (fivenum #(14)) "Minimal case")
(check-equal? #(8 11 14 17 20) (fivenum #(8 14 20)) "3-value case")
(check-equal? #(8 11 15 18 20) (fivenum #(8 14 16 20)) "4-value case")
(define x1-seq #(36 40 7 39 41 15))
(define x1-v (vector-copy x1-seq))
(check-equal? x1-seq x1-v "before fivenum! sequence and vector were not `equal?`")
(check-equal? #(7 15 #e37.5 40 41) (fivenum! x1-v) "Test against Go results x1")
(check-not-equal? x1-seq x1-v "fivenum! did not mutate mutable input vectors")
(check-equal? #(6 #e25.5 40 #e42.5 49) (fivenum #(15 6 42 41 7 36 49 40 39 47 43)) "Test against Go results x2")
(check-equal? #(-1.95059594 -0.676741205 0.23324706 0.746070945 1.73131507)
(fivenum (vector 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555
-0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527
-0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385
0.75775634 0.32566578))
"Test against Go results x3"))
|
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)
|
#Burlesque
|
Burlesque
|
ln"ABCD"r@\/\\
|
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
|
#COBOL
|
COBOL
|
program-id. last-sun.
data division.
working-storage section.
1 wk-date.
2 yr pic 9999.
2 mo pic 99 value 1.
2 da pic 99 value 1.
1 rd-date redefines wk-date pic 9(8).
1 binary.
2 int-date pic 9(8).
2 dow pic 9(4).
2 sunday pic 9(4) value 7.
procedure division.
display "Enter a calendar year (1601 thru 9999): "
with no advancing
accept yr
if yr >= 1601 and <= 9999
continue
else
display "Invalid year"
stop run
end-if
perform 12 times
move 1 to da
add 1 to mo
if mo > 12 *> to avoid y10k in 9999
move 12 to mo
move 31 to da
end-if
compute int-date = function
integer-of-date (rd-date)
if mo =12 and da = 31 *> to avoid y10k in 9999
continue
else
subtract 1 from int-date
end-if
compute rd-date = function
date-of-integer (int-date)
compute dow = function mod
((int-date - 1) 7) + 1
compute dow = function mod ((dow - sunday) 7)
subtract dow from da
display yr "-" mo "-" da
add 1 to mo
end-perform
stop run
.
end program last-sun.
|
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) .
|
#Factor
|
Factor
|
USING: arrays combinators.extras kernel math
math.matrices.laplace math.vectors prettyprint sequences ;
: det ( pt pt -- x ) 2array determinant ;
: numerator ( x y pt pt quot -- z )
bi@ swapd [ 2array ] 2bi@ det ; inline
: intersection ( pt pt pt pt -- pt )
[ [ det ] 2bi@ ]
[ [ v- ] 2bi@ ] 4bi
[ [ first ] numerator ]
[ [ second ] numerator ]
[ det 2nip ] 4tri
dup zero? [ 3drop { 0/0. 0/0. } ]
[ tuck [ / ] 2bi@ 2array ] if ;
{ 4 0 } { 6 10 } { 0 3 } { 10 7 } intersection .
{ 4 0 } { 6 10 } { 0 3 } { 10 7+1/10 } intersection .
{ 0 0 } { 1 1 } { 1 2 } { 4 5 } intersection .
|
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) .
|
#Fortran
|
Fortran
|
program intersect_two_lines
implicit none
type point
real::x,y
end type point
integer, parameter :: n = 4
type(point) :: p(n)
p(1)%x = 4; p(1)%y = 0; p(2)%x = 6; p(2)%y = 10 ! fist line
p(3)%x = 0; p(3)%y = 3; p(4)%x = 10; p(4)%y = 7 ! second line
call intersect(p, n)
contains
subroutine intersect(p,m)
integer, intent(in) :: m
type(point), intent(in) :: p(m)
integer :: i
real :: a(2), b(2) ! y = a*x + b, for each line
real :: x, y ! intersect point
real :: dx,dy ! working variables
do i = 1, 2
dx = p(2*i-1)%x - p(2*i)%x
dy = p(2*i-1)%y - p(2*i)%y
if( dx == 0.) then ! in case this line is of the form y = b
a(i) = 0.
b(i) = p(2*i-1)%y
else
a(i)= dy / dx
b(i) = p(2*i-1)%y - a(i)*p(2*i-1)%x
endif
enddo
if( a(1) - a(2) == 0. ) then
write(*,*)"lines are not intersecting"
return
endif
x = ( b(2) - b(1) ) / ( a(1) - a(2) )
y = a(1) * x + b(1)
write(*,*)x,y
end subroutine intersect
end program intersect_two_lines
|
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].
|
#Go
|
Go
|
package main
import "fmt"
type Vector3D struct{ x, y, z float64 }
func (v *Vector3D) Add(w *Vector3D) *Vector3D {
return &Vector3D{v.x + w.x, v.y + w.y, v.z + w.z}
}
func (v *Vector3D) Sub(w *Vector3D) *Vector3D {
return &Vector3D{v.x - w.x, v.y - w.y, v.z - w.z}
}
func (v *Vector3D) Mul(s float64) *Vector3D {
return &Vector3D{s * v.x, s * v.y, s * v.z}
}
func (v *Vector3D) Dot(w *Vector3D) float64 {
return v.x*w.x + v.y*w.y + v.z*w.z
}
func (v *Vector3D) String() string {
return fmt.Sprintf("(%v, %v, %v)", v.x, v.y, v.z)
}
func intersectPoint(rayVector, rayPoint, planeNormal, planePoint *Vector3D) *Vector3D {
diff := rayPoint.Sub(planePoint)
prod1 := diff.Dot(planeNormal)
prod2 := rayVector.Dot(planeNormal)
prod3 := prod1 / prod2
return rayPoint.Sub(rayVector.Mul(prod3))
}
func main() {
rv := &Vector3D{0.0, -1.0, -1.0}
rp := &Vector3D{0.0, 0.0, 10.0}
pn := &Vector3D{0.0, 0.0, 1.0}
pp := &Vector3D{0.0, 0.0, 5.0}
ip := intersectPoint(rv, rp, pn, pp)
fmt.Println("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
|
#AntLang
|
AntLang
|
n:{1+ x}map range[100]
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n
echo map s
|
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
|
#Dart
|
Dart
|
main() {
var total = 0;
var empty = <int>[];
for (var year = 1900; year < 2101; year++) {
var months =
[1, 3, 5, 7, 8, 10, 12].where((m) => DateTime(year, m, 1).weekday == 5);
print('$year\t$months');
total += months.length;
if (months.isEmpty) empty.add(year);
}
print('Total: $total');
print('Year with none: $empty');
}
|
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
|
#Delphi
|
Delphi
|
program FiveWeekends;
{$APPTYPE CONSOLE}
uses SysUtils, DateUtils;
var
lMonth, lYear: Integer;
lDate: TDateTime;
lFiveWeekendCount: Integer;
lYearsWithout: Integer;
lFiveWeekendFound: Boolean;
begin
for lYear := 1900 to 2100 do
begin
lFiveWeekendFound := False;
for lMonth := 1 to 12 do
begin
lDate := EncodeDate(lYear, lMonth, 1);
if (DaysInMonth(lDate) = 31) and (DayOfTheWeek(lDate) = DayFriday) then
begin
Writeln(FormatDateTime('mmm yyyy', lDate));
Inc(lFiveWeekendCount);
lFiveWeekendFound := True;
end;
end;
if not lFiveWeekendFound then
Inc(lYearsWithout);
end;
Writeln;
Writeln(Format('Months with 5 weekends: %d', [lFiveWeekendCount]));
Writeln(Format('Years with no 5 weekend months: %d', [lYearsWithout]));
end.
|
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
|
First perfect square in base n with n unique digits
|
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#Python
|
Python
|
'''Perfect squares using every digit in a given base.'''
from itertools import count, dropwhile, repeat
from math import ceil, sqrt
from time import time
# allDigitSquare :: Int -> Int -> Int
def allDigitSquare(base, above):
'''The lowest perfect square which
requires all digits in the given base.
'''
bools = list(repeat(True, base))
return next(
dropwhile(
missingDigitsAtBase(base, bools),
count(
max(
above,
ceil(sqrt(int(
'10' + '0123456789abcdef'[2:base],
base
)))
)
)
)
)
# missingDigitsAtBase :: Int -> [Bool] -> Int -> Bool
def missingDigitsAtBase(base, bools):
'''Fusion of representing the square of integer N at a
given base with checking whether all digits of
that base contribute to N^2.
Clears the bool at a digit position to False when used.
True if any positions remain uncleared (unused).
'''
def go(x):
xs = bools.copy()
while x:
xs[x % base] = False
x //= base
return any(xs)
return lambda n: go(n * n)
# digit :: Int -> Char
def digit(n):
'''Digit character for given integer.'''
return '0123456789abcdef'[n]
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Smallest perfect squares using all digits in bases 2-16'''
start = time()
print(main.__doc__ + ':\n\nBase Root Square')
q = 0
for b in enumFromTo(2)(16):
q = allDigitSquare(b, q)
print(
str(b).rjust(2, ' ') + ' -> ' +
showIntAtBase(b)(digit)(q)('').rjust(8, ' ') +
' -> ' +
showIntAtBase(b)(digit)(q * q)('')
)
print(
'\nc. ' + str(ceil(time() - start)) + ' seconds.'
)
# ----------------------- GENERIC ------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# showIntAtBase :: Int -> (Int -> String) -> Int ->
# String -> String
def showIntAtBase(base):
'''String representation of an integer in a given base,
using a supplied function for the string representation
of digits.
'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
# MAIN ---
if __name__ == '__main__':
main()
|
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
|
#Ela
|
Ela
|
open number //sin,cos,asin,acos
open list //zipWith
cube x = x ** 3
croot x = x ** (1/3)
funclist = [sin, cos, cube]
funclisti = [asin, acos, croot]
zipWith (\f inversef -> (inversef << f) 0.5) funclist funclisti
|
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
|
#Elena
|
Elena
|
import system'routines;
import system'math;
import extensions'routines;
import extensions'math;
extension op
{
compose(f,g)
= f(g(self));
}
public program()
{
var fs := new object[]{ mssgconst sin<mathOp>[1], mssgconst cos<mathOp>[1], (x => power(x, 3.0r)) };
var gs := new object[]{ mssgconst arcsin<mathOp>[1], mssgconst arccos<mathOp>[1], (x => power(x, 1.0r / 3)) };
fs.zipBy(gs, (f,g => 0.5r.compose(f,g)))
.forEach:printingLn
}
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
evolve[nbhd_List, k_] := 0 /; nbhd[[2, 2]] == 2 (*burning->empty*)
evolve[nbhd_List, k_] := 2 /; nbhd[[2, 2]] == 1 && Max@nbhd == 2 (*near_burning&nonempty->burning*)
evolve[nbhd_List, k_] := RandomChoice[{f, 1 - f} -> {2, nbhd[[2, 2]]}] /; nbhd[[2, 2]] == 1 && Max@nbhd < 2 (*spontaneously combusting tree*)
evolve[nbhd_List, k_] := RandomChoice[{p, 1 - p} -> {1, nbhd[[2, 2]]}] /; nbhd[[2, 2]] == 0 (*random tree growth*)
r = 100; c = 100; p = 10^-2; f = 10^-4;
init = RandomInteger[BernoulliDistribution[0.05], {r, c}];
MatrixPlot[CellularAutomaton[{evolve, {}, {1, 1}}, {init, 0}, {{{300}}}], ColorRules -> {0 -> White, 1 -> Green, 2 -> Red}, Frame -> False]
|
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
|
#Euphoria
|
Euphoria
|
sequence a = {{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
function flatten( object s )
sequence res = {}
if sequence( s ) then
for i = 1 to length( s ) do
sequence c = flatten( s[ i ] )
if length( c ) > 0 then
res &= c
end if
end for
else
if length( s ) > 0 then
res = { s }
end if
end if
return res
end function
? a
? flatten(a)
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Scala
|
Scala
|
import java.awt.{BorderLayout, Color, Dimension, Font, Graphics, Graphics2D, Rectangle, RenderingHints}
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing.{JFrame, JPanel}
object FlippingBitsGame extends App {
class FlippingBitsGame extends JPanel {
private val maxLevel: Int = 7
private val box: Rectangle = new Rectangle(120, 90, 400, 400)
private var n: Int = maxLevel
private var grid: Array[Array[Boolean]] = _
private var target: Array[Array[Boolean]] = _
private var solved: Boolean = true
override def paintComponent(gg: Graphics): Unit = {
def drawGrid(g: Graphics2D): Unit = {
if (solved) g.drawString("Solved! Click here to play again.", 180, 600)
else g.drawString("Click next to a row or a column to flip.", 170, 600)
val size: Int = box.width / n
for {r <- 0 until n
c <- 0 until n} {
g.setColor(if (grid(r)(c)) Color.blue else Color.orange)
g.fillRect(box.x + c * size, box.y + r * size, size, size)
g.setColor(getBackground)
g.drawRect(box.x + c * size, box.y + r * size, size, size)
g.setColor(if (target(r)(c)) Color.blue else Color.orange)
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10)
}
}
super.paintComponent(gg)
val g: Graphics2D = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawGrid(g)
}
private def printGrid(msg: String, g: Array[Array[Boolean]]): Unit = {
println(msg)
for (row <- g) println(row.mkString(", "))
println()
}
private def startNewGame(): Unit = {
val rand = scala.util.Random
if (solved) {
val minLevel: Int = 3
n = if (n == maxLevel) minLevel else n + 1
grid = Array.ofDim[Boolean](n, n)
target = Array.ofDim[Boolean](n, n)
do {
def shuffle(): Unit = for (i <- 0 until n * n)
if (rand.nextBoolean()) flipRow(rand.nextInt(n)) else flipCol(rand.nextInt(n))
shuffle()
for (i <- grid.indices) grid(i).copyToArray(target(i)) //, n)
shuffle()
} while (solved(grid, target))
solved = false
printGrid("The target", target)
printGrid("The board", grid)
}
}
private def solved(a: Array[Array[Boolean]], b: Array[Array[Boolean]]): Boolean =
a.indices.forall(i => a(i) sameElements b(i))
private def flipRow(r: Int): Unit = for (c <- 0 until n) grid(r)(c) ^= true
private def flipCol(c: Int): Unit = for (row <- grid) row(c) ^= true
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
setFont(new Font("SansSerif", Font.PLAIN, 18))
startNewGame()
addMouseListener(new MouseAdapter() {
override def mousePressed(e: MouseEvent): Unit = {
if (solved) startNewGame()
else {
val x: Int = e.getX
val y: Int = e.getY
if (box.contains(x, y)) return
if (x > box.x && x < box.x + box.width) flipCol((x - box.x) / (box.width / n))
else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n))
solved = solved(grid, target)
printGrid(if (solved) "Solved!" else "The board", grid)
}
repaint()
}
})
}
new JFrame("Flipping Bits Game") {
add(new FlippingBitsGame(), BorderLayout.CENTER)
pack()
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
}
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
import "/math" for Math
var ld10 = Math.ln2 / Math.ln10
var p = Fn.new { |L, n|
var i = L
var digits = 1
while (i >= 10) {
digits = digits * 10
i = (i/10).floor
}
var count = 0
i = 0
while (count < n) {
var e = (Math.ln10 * (i * ld10).fraction).exp
if ((e * digits).truncate == L) count = count + 1
i = i + 1
}
return i - 1
}
var start = System.clock
var params = [ [12, 1] , [12, 2], [123, 45], [123, 12345], [123, 678910] ]
for (param in params) {
Fmt.print("p($d, $d) = $,d", param[0], param[1], p.call(param[0], param[1]))
}
System.print("\nTook %(System.clock - start) seconds.")
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Sidef
|
Sidef
|
func multiplier(n1, n2) {
func (n3) {
n1 * n2 * n3
}
}
var x = 2.0
var xi = 0.5
var y = 4.0
var yi = 0.25
var z = (x + y)
var zi = (1 / (x + y))
var numbers = [x, y, z]
var inverses = [xi, yi, zi]
for f,g (numbers ~Z inverses) {
say multiplier(f, g)(0.5)
}
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Slate
|
Slate
|
define: #multiplier -> [| :n1 :n2 | [| :m | n1 * n2 * m]].
define: #x -> 2.
define: #y -> 4.
define: #numlist -> {x. y. x + y}.
define: #numlisti -> (numlist collect: [| :x | 1.0 / x]).
numlist with: numlisti collect: [| :n1 :n2 | (multiplier applyTo: {n1. n2}) applyWith: 0.5].
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Tcl
|
Tcl
|
after 1000 {myroutine x}
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Tiny_BASIC
|
Tiny BASIC
|
REM TinyBASIC has only two control flow structures: goto and gosub
LET N = 0
10 LET N = N + 1
PRINT N
IF N < 10 THEN GOTO 10
LET R = 10
15 IF N < 10000 THEN GOSUB 20
IF N > 10000 THEN GOTO 30
GOTO R + 5 REM goto can be computed
20 LET N = N * 2
PRINT N
RETURN REM gosub returns to where it was called from
REM meaning it can be called from multiple
REM places in the program
30 LET N = 0
40 GOSUB 105-N REM gosub can be computed as well
IF N <= 5 THEN GOTO 40
END
100 PRINT "ZERO"
101 PRINT "1"
102 PRINT "22"
103 PRINT "333"
104 PRINT "4444"
105 PRINT "55555"
LET N = N + 1
RETURN REM one return can serve several gosubs
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(a)
n := integer(a[1]) | 5
w := ((n*(n-1))/2)-n
c := create seq()
every row := 1 to n do {
every col := 1 to row do {
width := *(w+col)+1
every writes(right(@c,width))
}
write()
}
end
|
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
|
Floyd-Warshall algorithm
|
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#Raku
|
Raku
|
sub Floyd-Warshall (Int $n, @edge) {
my @dist = [0, |(Inf xx $n-1)], *.Array.rotate(-1) … !*[*-1];
my @next = [0 xx $n] xx $n;
for @edge -> ($u, $v, $w) {
@dist[$u-1;$v-1] = $w;
@next[$u-1;$v-1] = $v-1;
}
for [X] ^$n xx 3 -> ($k, $i, $j) {
if @dist[$i;$j] > my $sum = @dist[$i;$k] + @dist[$k;$j] {
@dist[$i;$j] = $sum;
@next[$i;$j] = @next[$i;$k];
}
}
say ' Pair Distance Path';
for [X] ^$n xx 2 -> ($i, $j){
next if $i == $j;
my @path = $i;
@path.push: @next[@path[*-1];$j] until @path[*-1] == $j;
printf("%d → %d %4d %s\n", $i+1, $j+1, @dist[$i;$j],
@path.map( *+1 ).join(' → '));
}
}
Floyd-Warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]);
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#V
|
V
|
[multiply *].
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#VBA
|
VBA
|
Function Multiply(lngMcand As Long, lngMplier As Long) As Long
Multiply = lngMcand * lngMplier
End Function
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#Ring
|
Ring
|
# Project : Forward difference
s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
for p = 1 to 9
s = fwddiff(s)
showarray(s)
next
func fwddiff(s)
for j=1 to len(s)-1
s[j] = s[j+1]-s[j]
next
n = len(s)
del(s, n)
return s
func showarray(vect)
see "{"
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n] + ", "
next
svect = left(svect, len(svect) - 2)
see svect
see "}" + nl
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#Ruby
|
Ruby
|
def dif(s)
s.each_cons(2).collect { |x, y| y - x }
end
def difn(s, n)
n.times.inject(s) { |s, | dif(s) }
end
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#Sather
|
Sather
|
-- a "pin" can be connected only to one component
-- that "sets" it to 0 or 1, while it can be "read"
-- ad libitum. (Tristate logic is not taken into account)
-- This class does the proper checking, assuring the "circuit"
-- and the connections are described correctly. Currently can make
-- hard the implementation of a latch
class PIN is
private attr v:INT;
readonly attr name:STR;
private attr connected:BOOL;
create(n:STR):SAME is -- n = conventional name for this "pin"
res ::= new;
res.name := n;
res.connected := false;
return res;
end;
val:INT is
if self.connected.not then
#ERR + "pin " + self.name + " is undefined\n";
return 0; -- could return a random bit to "simulate" undefined
-- behaviour
else
return self.v;
end;
end;
-- connect ...
val(v:INT) is
if self.connected then
#ERR + "pin " + self.name + " is already 'assigned'\n";
else
self.connected := true;
self.v := v.band(1);
end;
end;
-- connect to existing pin
val(v:PIN) is
self.val(v.val);
end;
end;
-- XOR "block"
class XOR is
readonly attr xor :PIN;
create(a, b:PIN):SAME is
res ::= new;
res.xor := #PIN("xor output");
l ::= a.val.bnot.band(1).band(b.val);
r ::= a.val.band(b.val.bnot.band(1));
res.xor.val := r.bor(l);
return res;
end;
end;
-- HALF ADDER "block"
class HALFADDER is
readonly attr s, c:PIN;
create(a, b:PIN):SAME is
res ::= new;
res.s := #PIN("halfadder sum output");
res.c := #PIN("halfadder carry output");
res.s.val := #XOR(a, b).xor.val;
res.c.val := a.val.band(b.val);
return res;
end;
end;
-- FULL ADDER "block"
class FULLADDER is
readonly attr s, c:PIN;
create(a, b, ic:PIN):SAME is
res ::= new;
res.s := #PIN("fulladder sum output");
res.c := #PIN("fulladder carry output");
halfadder1 ::= #HALFADDER(a, b);
halfadder2 ::= #HALFADDER(halfadder1.s, ic);
res.s.val := halfadder2.s;
res.c.val := halfadder2.c.val.bor(halfadder1.c.val);
return res;
end;
end;
-- FOUR BITS ADDER "block"
class FOURBITSADDER is
readonly attr s0, s1, s2, s3, v :PIN;
create(a0, a1, a2, a3, b0, b1, b2, b3:PIN):SAME is
res ::= new;
res.s0 := #PIN("4-bits-adder sum outbut line 0");
res.s1 := #PIN("4-bits-adder sum outbut line 1");
res.s2 := #PIN("4-bits-adder sum outbut line 2");
res.s3 := #PIN("4-bits-adder sum outbut line 3");
res.v := #PIN("4-bits-adder overflow output");
zero ::= #PIN("zero/mass pin");
zero.val := 0;
fa0 ::= #FULLADDER(a0, b0, zero);
fa1 ::= #FULLADDER(a1, b1, fa0.c);
fa2 ::= #FULLADDER(a2, b2, fa1.c);
fa3 ::= #FULLADDER(a3, b3, fa2.c);
res.v.val := fa3.c;
res.s0.val := fa0.s;
res.s1.val := fa1.s;
res.s2.val := fa2.s;
res.s3.val := fa3.s;
return res;
end;
end;
-- testing --
class MAIN is
main is
a0 ::= #PIN("a0 in"); b0 ::= #PIN("b0 in");
a1 ::= #PIN("a1 in"); b1 ::= #PIN("b1 in");
a2 ::= #PIN("a2 in"); b2 ::= #PIN("b2 in");
a3 ::= #PIN("a3 in"); b3 ::= #PIN("b3 in");
ov ::= #PIN("overflow");
a0.val := 1; b0.val := 1;
a1.val := 1; b1.val := 1;
a2.val := 0; b2.val := 0;
a3.val := 0; b3.val := 1;
fba ::= #FOURBITSADDER(a0,a1,a2,a3,b0,b1,b2,b3);
#OUT + #FMT("%d%d%d%d", a3.val, a2.val, a1.val, a0.val) +
" + " +
#FMT("%d%d%d%d", b3.val, b2.val, b1.val, b0.val) +
" = " +
#FMT("%d%d%d%d", fba.s3.val, fba.s2.val, fba.s1.val, fba.s0.val) +
", overflow = " + fba.v.val + "\n";
end;
end;
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#Raku
|
Raku
|
sub fourths ( Int $end ) {
my $end_22 = $end div 2 / 2;
return 0, $end_22, $end/2, $end - $end_22, $end;
}
sub fivenum ( @nums ) {
my @x = @nums.sort(+*)
or die 'Input must have at least one element';
my @d = fourths(@x.end);
return ( @x[@d».floor] Z+ @x[@d».ceiling] ) »/» 2;
}
say .&fivenum for [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43],
[36, 40, 7, 39, 41, 15], [
0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,
0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,
0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,
0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578,
];
|
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)
|
#C
|
C
|
#include <stdio.h>
#define N 4
const char *perms[] = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB",
};
int main()
{
int i, j, n, cnt[N];
char miss[N];
for (n = i = 1; i < N; i++) n *= i; /* n = (N-1)!, # of occurrence */
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) cnt[j] = 0;
/* count how many times each letter occur at position i */
for (j = 0; j < sizeof(perms)/sizeof(const char*); j++)
cnt[perms[j][i] - 'A']++;
/* letter not occurring (N-1)! times is the missing one */
for (j = 0; j < N && cnt[j] == n; j++);
miss[i] = j + 'A';
}
printf("Missing: %.*s\n", N, miss);
return 0;
}
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun last-sundays (year)
(loop for month from 1 to 12
for last-month-p = (= month 12)
for next-month = (if last-month-p 1 (1+ month))
for year-of-next-month = (if last-month-p (1+ year) year)
for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0)
for 1st-day-dow = (nth-value 6 (decode-universal-time 1st-day-next-month 0))
;; 0: monday, 1: tuesday, ... 6: sunday
for diff-to-last-sunday = (1+ 1st-day-dow)
for last-sunday = (- 1st-day-next-month (* diff-to-last-sunday 24 60 60))
do (multiple-value-bind (second minute hour date month year)
(decode-universal-time last-sunday 0)
(declare (ignore second minute hour))
(format t "~D-~2,'0D-~2,'0D~%" year month date))))
(last-sundays 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) .
|
#FreeBASIC
|
FreeBASIC
|
' version 16-08-2017
' compile with: fbc -s console
#Define NaN 0 / 0 ' FreeBASIC returns -1.#IND
Type _point_
As Double x, y
End Type
Function l_l_intersect(s1 As _point_, e1 As _point_, s2 As _point_, e2 As _point_) As _point_
Dim As Double a1 = e1.y - s1.y
Dim As Double b1 = s1.x - e1.x
Dim As Double c1 = a1 * s1.x + b1 * s1.y
Dim As Double a2 = e2.y - s2.y
Dim As Double b2 = s2.x - e2.x
Dim As Double c2 = a2 * s2.x + b2 * s2.y
Dim As Double det = a1 * b2 - a2 * b1
If det = 0 Then
Return Type(NaN, NaN)
Else
Return Type((b2 * c1 - b1 * c2) / det, (a1 * c2 - a2 * c1) / det)
End If
End Function
' ------=< MAIN >=------
Dim As _point_ s1, e1, s2, e2, answer
s1.x = 4.0 : s1.y = 0.0 : e1.x = 6.0 : e1.y = 10.0 ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y = 7.0 ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y
s1.x = 0.0 : s1.y = 0.0 : e1.x = 0.0 : e1.y = 0.0 ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y = 7.0 ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
|
Find the intersection of a line with a plane
|
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
|
#Groovy
|
Groovy
|
class LinePlaneIntersection {
private static class Vector3D {
private double x, y, z
Vector3D(double x, double y, double z) {
this.x = x
this.y = y
this.z = z
}
Vector3D plus(Vector3D v) {
return new Vector3D(x + v.x, y + v.y, z + v.z)
}
Vector3D minus(Vector3D v) {
return new Vector3D(x - v.x, y - v.y, z - v.z)
}
Vector3D multiply(double s) {
return new Vector3D(s * x, s * y, s * z)
}
double dot(Vector3D v) {
return x * v.x + y * v.y + z * v.z
}
@Override
String toString() {
return "($x, $y, $z)"
}
}
private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) {
Vector3D diff = rayPoint - planePoint
double prod1 = diff.dot(planeNormal)
double prod2 = rayVector.dot(planeNormal)
double prod3 = prod1 / prod2
return rayPoint - rayVector * prod3
}
static void main(String[] args) {
Vector3D rv = new Vector3D(0.0, -1.0, -1.0)
Vector3D rp = new Vector3D(0.0, 0.0, 10.0)
Vector3D pn = new Vector3D(0.0, 0.0, 1.0)
Vector3D pp = new Vector3D(0.0, 0.0, 5.0)
Vector3D ip = intersectPoint(rv, rp, pn, pp)
println("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
|
#APEX
|
APEX
|
for(integer i=1; i <= 100; i++){
String output = '';
if(math.mod(i, 3) == 0) output += 'Fizz';
if(math.mod(i, 5) == 0) output += 'Buzz';
if(output != ''){
System.debug(output);
} else {
System.debug(i);
}
}
|
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
|
#Elixir
|
Elixir
|
defmodule Date do
@months { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" }
def five_weekends(year) do
for m <-[1,3,5,7,8,10,12], :calendar.day_of_the_week(year, m, 31) == 7, do: elem(@months, m-1)
end
end
months = Enum.map(1900..2100, fn year -> {year, Date.five_weekends(year)} end)
{none, months5} = Enum.partition(months, fn {_,m} -> Enum.empty?(m) end)
count = Enum.reduce(months5, 0, fn {year, months}, acc ->
IO.puts "#{year} : #{Enum.join(months, ", ")}"
acc + length(months)
end)
IO.puts "Found #{count} month with 5 weekends."
IO.puts "\nFound #{length(none)} years with no month having 5 weekends:"
IO.puts "#{inspect Enum.map(none, fn {y,_}-> y end)}"
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Erlang
|
Erlang
|
#!/usr/bin/env escript
%%
%% Calculate number of months with five weekends between years 1900-2100
%%
main(_) ->
Years = [ [{Y,M} || M <- lists:seq(1,12)] || Y <- lists:seq(1900,2100) ],
{CountedYears, {Has5W, TotM5W}} = lists:mapfoldl(
fun(Months, {Has5W, Tot}) ->
WithFive = [M || M <- Months, has_five(M)],
CountM5W = length(WithFive),
{{Months,CountM5W}, {Has5W++WithFive, Tot+CountM5W}}
end, {[], 0}, Years),
io:format("There are ~p months with five full weekends.~n"
"Showing top and bottom 5:~n",
[TotM5W]),
lists:map(fun({Y,M}) -> io:format("~p-~p~n", [Y,M]) end,
lists:sublist(Has5W,1,5) ++ lists:nthtail(TotM5W-5, Has5W)),
No5W = [Y || {[{Y,_M}|_], 0} <- CountedYears],
io:format("The following ~p years do NOT have any five-weekend months:~n",
[length(No5W)]),
lists:map(fun(Y) -> io:format("~p~n", [Y]) end, No5W).
has_five({Year, Month}) ->
has_five({Year, Month}, calendar:last_day_of_the_month(Year, Month)).
has_five({Year, Month}, Days) when Days =:= 31 ->
calendar:day_of_the_week({Year, Month, 1}) =:= 5;
has_five({_Year, _Month}, _DaysNot31) ->
false.
|
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
|
First perfect square in base n with n unique digits
|
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#Raku
|
Raku
|
#`[
Only search square numbers that have at least N digits;
smaller could not possibly match.
Only bother to use analytics for large N. Finesse takes longer than brute force for small N.
]
unit sub MAIN ($timer = False);
sub first-square (Int $n) {
my @start = flat '1', '0', (2 ..^ $n)».base: $n;
if $n > 10 { # analytics
my $root = digital-root( @start.join, :base($n) );
my @roots = (2..$n).map(*²).map: { digital-root($_.base($n), :base($n) ) };
if $root ∉ @roots {
my $offset = min(@roots.grep: * > $root ) - $root;
@start[1+$offset] = $offset ~ @start[1+$offset];
}
}
my $start = @start.join.parse-base($n).sqrt.ceiling;
my @digits = reverse (^$n)».base: $n;
my $sq;
my $now = now;
my $time = 0;
my $sr;
for $start .. * {
$sq = .²;
my $s = $sq.base($n);
my $f;
$f = 1 and last unless $s.contains: $_ for @digits;
if $timer && $n > 19 && $_ %% 1_000_000 {
$time += now - $now;
say "N $n: {$_}² = $sq <$s> : {(now - $now).round(.001)}s" ~
" : {$time.round(.001)} elapsed";
$now = now;
}
next if $f;
$sr = $_;
last
}
sprintf( "Base %2d: %13s² == %-30s", $n, $sr.base($n), $sq.base($n) ) ~
($timer ?? ($time + now - $now).round(.001) !! '');
}
sub digital-root ($root is copy, :$base = 10) {
$root = $root.comb.map({:36($_)}).sum.base($base) while $root.chars > 1;
$root.parse-base($base);
}
say "First perfect square with N unique digits in base N: ";
say .&first-square for flat
2 .. 12, # required
13 .. 16, # optional
17 .. 19, # stretch
20, # slow
21, # pretty fast
22, # very slow
23, # don't hold your breath
24, # slow but not too terrible
25, # very slow
26, # "
;
|
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
|
#Elixir
|
Elixir
|
defmodule First_class_functions do
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
bs = [&:math.asin/1, &:math.acos/1, fn x -> :math.pow(x, 1/3) end]
Enum.zip(as, bs)
|> Enum.each(fn {a,b} -> IO.puts compose([a,b], val) end)
end
defp compose(funs, x) do
Enum.reduce(funs, x, fn f,acc -> f.(acc) end)
end
end
First_class_functions.task(0.5)
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#Erlang
|
Erlang
|
-module( first_class_functions ).
-export( [task/0] ).
task() ->
As = [fun math:sin/1, fun math:cos/1, fun cube/1],
Bs = [fun math:asin/1, fun math:acos/1, fun square_inverse/1],
[io:fwrite( "Value: 1.5 Result: ~p~n", [functional_composition([A, B], 1.5)]) || {A, B} <- lists:zip(As, Bs)].
functional_composition( Funs, X ) -> lists:foldl( fun(F, Acc) -> F(Acc) end, X, Funs ).
square( X ) -> math:pow( X, 2 ).
square_inverse( X ) -> math:sqrt( X ).
|
http://rosettacode.org/wiki/Forest_fire
|
Forest fire
|
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
A burning cell turns into an empty cell
A tree will burn if at least one neighbor is burning
A tree ignites with probability f even if no neighbor is burning
An empty space fills with a tree with probability p
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function forest_fire(f,p,N,M)
% Forest fire
if nargin<4;
M=200;
end
if nargin<3;
N=200;
end
if nargin<2;
p=.03;
end
if nargin<1;
f=p*.0001;
end
% initialize;
F = (rand(M,N) < p)+1; % tree with probability p
S = ones(3); S(2,2)=0; % surrounding
textmap = ' T#';
colormap([.5,.5,.5;0,1,0;1,0,0]);
while(1)
image(F); pause(.1) % uncomment for graphical output
% disp(textmap(F)); pause; % uncomment for textual output
G = ((F==1).*((rand(M,N)<p)+1)); % grow tree
G = G + (F==2) .* ((filter2(S,F==3)>0) + (rand(M,N)<f) + 2); % burn tree if neighbor is burning or by chance f
G = G + (F==3); % empty after burn
F = G;
end;
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#F.23
|
F#
|
type 'a ll =
| I of 'a // leaf Item
| L of 'a ll list // ' <- confine the syntax colouring confusion
let rec flatten = function
| [] -> []
| (I x)::y -> x :: (flatten y)
| (L x)::y -> List.append (flatten x) (flatten y)
printfn "%A" (flatten [L([I(1)]); I(2); L([L([I(3);I(4)]); I(5)]); L([L([L([])])]); L([L([L([I(6)])])]); I(7); I(8); L([])])
// -> [1; 2; 3; 4; 5; 6; 7; 8]
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Swift
|
Swift
|
import Foundation
struct Board: Equatable, CustomStringConvertible {
let size: Int
private var tiles: [Bool]
init(size: Int) {
self.size = size
tiles = Array(count: size * size, repeatedValue: false)
}
subscript(x: Int, y: Int) -> Bool {
get {
return tiles[y * size + x]
}
set {
tiles[y * size + x] = newValue
}
}
mutating func randomize() {
for i in 0..<tiles.count {
tiles[i] = Bool(random() % 2)
}
}
mutating func flipRow(row: Int) {
for i in 0..<size {
self[row, i] = !self[row, i]
}
}
mutating func flipColumn(column: Int) {
for i in 0..<size {
self[i, column] = !self[i, column]
}
}
var description: String {
var desc = "\n\ta\tb\tc\n"
for i in 0..<size {
desc += "\(i+1):\t"
for j in 0..<size {
desc += "\(Int(self[i, j]))\t"
}
desc += "\n"
}
return desc
}
}
func ==(lhs: Board, rhs: Board) -> Bool {
return lhs.tiles == rhs.tiles
}
class FlippingGame: CustomStringConvertible {
var board: Board
var target: Board
var solved: Bool { return board == target }
init(boardSize: Int) {
target = Board(size: 3)
board = Board(size: 3)
generateTarget()
}
func generateTarget() {
target.randomize()
board = target
let size = board.size
while solved {
for _ in 0..<size + (random() % size + 1) {
if random() % 2 == 0 {
board.flipColumn(random() % size)
}
else {
board.flipRow(random() % size)
}
}
}
}
func getMove() -> Bool {
print(self)
print("Flip what? ", terminator: "")
guard
let move = readLine(stripNewline: true)
where move.characters.count == 1
else { return false }
var moveValid = true
if let row = Int(move) {
board.flipRow(row - 1)
}
else if let column = move.lowercaseString.utf8.first where column < 100 && column > 96 {
board.flipColumn(numericCast(column) - 97)
}
else {
moveValid = false
}
return moveValid
}
var description: String {
var str = ""
print("Target: \n \(target)", toStream: &str)
print("Board: \n \(board)", toStream: &str)
return str
}
}
func playGame(game: FlippingGame) -> String {
game.generateTarget()
var numMoves = 0
while !game.solved {
numMoves++
print("Move #\(numMoves)")
while !game.getMove() {}
}
print("You win!")
print("Number of moves: \(numMoves)")
print("\n\nPlay Again? ", terminator: "")
return readLine(stripNewline: true)!.lowercaseString
}
let game = FlippingGame(boardSize: 3)
repeat { } while playGame(game) == "y"
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#Tcl
|
Tcl
|
package require Tcl 8.6
oo::class create Flip {
variable board target s
constructor {size} {
set s $size
set target [my RandomConfiguration]
set board $target
while {$board eq $target} {
for {set i 0} {$i < $s} {incr i} {
if {rand()<.5} {
my SwapRow $i
}
if {rand()<.5} {
my SwapColumn $i
}
}
}
}
method RandomConfiguration {{p 0.5}} {
for {set row 0} {$row < $s} {incr row} {
set r {}
for {set col 0} {$col < $s} {incr col} {
lappend r [expr {rand() < $p}]
}
lappend result $r
}
return $result
}
method SwapRow {rowId} {
for {set i 0} {$i < $s} {incr i} {
lset board $rowId $i [expr {![lindex $board $rowId $i]}]
}
}
method SwapColumn {columnId} {
for {set i 0} {$i < $s} {incr i} {
lset board $i $columnId [expr {![lindex $board $i $columnId]}]
}
}
method Render {configuration {prefixes {}}} {
join [lmap r $configuration p $prefixes {
format %s%s $p [join [lmap c $r {string index ".X" $c}] ""]
}] "\n"
}
method GetInput {prompt} {
puts -nonewline "${prompt}: "
flush stdout
gets stdin
}
method play {} {
set p0 {}
set p {}
set top [format "%*s " [string length $s] ""]
for {set i 1;set j 97} {$i<=$s} {incr i;incr j} {
append top [format %c $j]
lappend p [format "%*d " [string length $s] $i]
lappend p0 [format "%*s " [string length $s] ""]
}
set moves 0
puts "You are trying to get to:\n[my Render $target $p0]\n"
while true {
puts "Current configuration (#$moves):\n$top\n[my Render $board $p]"
# Test for if we've won
if {$board eq $target} break
# Ask the user for a move
set i [my GetInput "Pick a column (letter) or row (number) to flip"]
# Parse the move and apply it
if {[string is lower -strict $i] && [set c [expr {[scan $i "%c"] - 97}]]<$s} {
my SwapColumn $c
incr moves
} elseif {[string is integer -strict $i] && $i>0 && $i<=$s} {
my SwapRow [expr {$i - 1}]
incr moves
} else {
puts "Error: bad selection"
}
puts ""
}
puts "\nYou win! (You took $moves moves.)"
}
}
Flip create flip 3
flip play
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#Yabasic
|
Yabasic
|
FAC = 0.30102999566398119521373889472449302677
print p(12, 1)
print p(12, 2)
print p(123, 45)
print p(123, 12345)
print p(123, 678910)
end
sub p(L, n)
cont = 0 : j = 0
LS$ = str$(L)
while cont < n
j = j + 1
x = FAC * j
//if x < len(LS$) continue while 'sino da error
y = 10^(x-int(x))
y = y * 10^len(LS$)
digits$ = str$(y)
if left$(digits$, len(LS$)) = LS$ cont = cont + 1
end while
return j
end sub
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#zkl
|
zkl
|
// float*int --> float and int*float --> int
fcn p(L,nth){ // 2^j = <L><digits>
var [const] ln10=(10.0).log(), ld10=(2.0).log() / ln10;
digits := (10).pow(L.numDigits - 1);
foreach i in ([1..]){
z:=ld10*i;
if(L == ( ln10 * (z - z.toInt()) ).exp()*digits and (nth-=1) <= 0)
return(i);
}
}
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc multiplier {a b} {
list apply {{ab m} {expr {$ab*$m}}} [expr {$a*$b}]
}
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Ursala
|
Ursala
|
#import std
#import flo
numbers = <2.,4.,plus(2.,4.)>
inverses = <0.5,0.25,div(1.,plus(2.,4.))>
multiplier = //times+ times
#cast %eL
main = (gang multiplier*p\numbers inverses) 0.5
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Sub bar2()
Dim x = 0
GoTo label
x = 5
label:
Console.WriteLine(x)
End Sub
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Wren
|
Wren
|
var func = Fn.new { |n|
var i = 1
while (true) {
if (i == 1) {
i = i + 1
continue // jumps to next iteration
}
System.print(i)
if (i == n) break // exits while loop
i = i + 1
}
if (n < 3) return // exits function
System.print(n + 1)
}
var fiber = Fiber.new {
Fiber.abort("Demo error") // error occcurred, abort script
}
var a = [2, 3]
for (n in a) {
func.call(n)
if (n > 2) return // end module and hence the script as its a single module script
var error = fiber.try() // catch any error
System.print("Caught error: " + error)
}
|
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.
|
#J
|
J
|
require 'strings'
floyd=: [: rplc&(' 0';' ')"1@":@(* ($ $ +/\@,)) >:/~@:i.
|
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.
|
#Java
|
Java
|
public class Floyd {
public static void main(String[] args){
printTriangle(5);
printTriangle(14);
}
private static void printTriangle(int n){
System.out.println(n + " rows:");
for(int rowNum = 1, printMe = 1, numsPrinted = 0;
rowNum <= n; printMe++){
int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
System.out.printf("%"+cols+"d ", printMe);
if(++numsPrinted == rowNum){
System.out.println();
rowNum++;
numsPrinted = 0;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.