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/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 ... | #Perl | Perl | #!perl
use strict;
use warnings qw(FATAL all);
my $n = shift(@ARGV) || 4;
if( $n < 2 or $n > 26 ) {
die "You can't play a size $n game\n";
}
my $n2 = $n*$n;
my (@rows, @cols);
for my $i ( 0 .. $n-1 ) {
my $row = my $col = "\x00" x $n2;
vec($row, $i * $n + $_, 8) ^= 1 for 0 .. $n-1;
vec($col, $i + $_ * $n, 8) ... |
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 ... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use feature 'state';
use POSIX qw(fmod);
use Perl6::GatherTake;
use constant ln2ln10 => log(2) / log(10);
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub ordinal_digit {
my($d) = $_[0] =~ /(.)$/;
$d eq '1' ? 'st' : $d eq '2' ? 'nd' :... |
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 m... | #Objeck | Objeck | use Collection.Generic;
class FirstClass {
function : Main(args : String[]) ~ Nil {
x := 2.0;
xi := 0.5;
y := 4.0;
yi := 0.25;
z := x + y;
zi := 1.0 / (x + y);
numlist := CompareVector->New()<FloatHolder>;
numlist->AddBack(x); numlist->AddBack(y); numlist->AddBack(z);
numlist... |
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 Struc... | #PHP | PHP | <?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?> |
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 Struc... | #PicoLisp | PicoLisp |
LEAVE
The LEAVE statement terminates execution of a loop.
Execution resumes at the next statement after the loop.
ITERATE
The ITERATE statement causes the next iteration of the loop to
commence. Any statements between ITERATE and the end of the loop
are not executed.
STOP
Terminates execution of ei... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #ERRE | ERRE |
PROGRAM FLOYD
!
! for rosettacode.org
!
BEGIN
N=14
NUM=1
LAST=(N^2-N+2) DIV 2
FOR ROW=1 TO N DO
FOR J=1 TO ROW DO
US$=STRING$(LEN(STR$(LAST-1+J))-1,"#")
WRITE(US$;NUM;)
PRINT(" ";)
NUM+=1
END FOR
PRINT
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Excel | Excel | floydTriangle
=LAMBDA(n,
IF(0 < n,
LET(
ixs, SEQUENCE(
n, n,
0, 1
),
x, MOD(ixs, n),
y, QUOTIENT(ixs, n),
IF(x > y,
"",
x + 1 + QUOTIENT(
y * (1 + y),
... |
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 ... | #Nim | Nim | import sequtils, strformat
type
Weight = tuple[src, dest, value: int]
Weights = seq[Weight]
#---------------------------------------------------------------------------------------------------
proc printResult(dist: seq[seq[float]]; next: seq[seq[int]]) =
echo "pair dist path"
for i in 0..next.... |
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 ... | #SNUSP | SNUSP | +1>++2=@\=>+++3=@\==@\=.=# prints '6'
| | \=itoa=@@@+@+++++#
\=======!\==!/===?\<#
\>+<-/ |
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 ... | #SPARK | SPARK | package Functions is
function Multiply (A, B : Integer) return Integer;
--# pre A * B in Integer; -- See note below
--# return A * B; -- Implies commutativity on Multiply arguments
end Functions; |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #PHP | PHP | <?php
function forwardDiff($anArray, $times = 1) {
if ($times <= 0) { return $anArray; }
for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) {
$accumilation[] = $anArray[$i] - $anArray[$i - 1];
}
if ($times === 1) { return $accumilation; }
return forwardDiff($accumilation, $times... |
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.
| #SQL | SQL | DECLARE @n INT
SELECT @n=123
SELECT SUBSTRING(CONVERT(CHAR(5), 10000+@n),2,4) AS FourDigits
SET @n=5
print "TwoDigits: " + SUBSTRING(CONVERT(CHAR(3), 100+@n),2,2)
--Output: 05 |
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.
| #Standard_ML | Standard ML | print (StringCvt.padLeft #"0" 9 (Real.fmt (StringCvt.FIX (SOME 3)) 7.125) ^ "\n") |
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 ... | #Prolog | Prolog | % binary 4 bit adder chip simulation
b_not(in(hi), out(lo)) :- !. % not(1) = 0
b_not(in(lo), out(hi)). % not(0) = 1
b_and(in(hi,hi), out(hi)) :- !. % and(1,1) = 1
b_and(in(_,_), out(lo)). % and(anything else) = 0
b_or(in(hi,_), out(hi)) :- !. % or(1,any) = 1
b_or(in(_,hi), out(hi)) :... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #JavaScript | JavaScript |
function median(arr) {
let mid = Math.floor(arr.length / 2);
return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid];
}
Array.prototype.fiveNums = function() {
this.sort(function(a, b) { return a - b} );
let mid = Math.floor(this.length / 2),
loQ = (this.length % 2 == 0) ? this.slice(0, ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Aime | Aime | void
paste(record r, index x, text p, integer a)
{
p = insert(p, -1, a);
x.delete(a);
if (~x) {
x.vcall(paste, -1, r, x, p);
} else {
r[p] = 0;
}
x[a] = 0;
}
integer
main(void)
{
record r;
list l;
index x;
l.bill(0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACB... |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #AutoHotkey | AutoHotkey | InputBox, Year, , Enter a year., , 300, 135
Date := Year . "0101"
while SubStr(Date, 1, 4) = Year {
FormatTime, WD, % Date, WDay
if (WD = 1)
MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2)
Date += 1, Days
}
Gui, Font, S10, Courier New
Gui, Add, Text, , % "Last Sundays of " Ye... |
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) .
| #AWK | AWK |
# syntax: GAWK -f FIND_THE_INTERSECTION_OF_TWO_LINES.AWK
# converted from Ring
BEGIN {
intersect(4,0,6,10,0,3,10,7)
exit(0)
}
function intersect(xa,ya,xb,yb,xc,yc,xd,yd, errors,x,y) {
printf("the 1st line passes through (%g,%g) and (%g,%g)\n",xa,ya,xb,yb)
printf("the 2nd line passes through (%g,%g) a... |
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 ... | #Arturo | Arturo | define :vector [x, y, z][]
addv: function [v1 :vector, v2 :vector]->
to :vector @[v1\x+v2\x, v1\y+v2\y, v1\z+v2\z]
subv: function [v1 :vector, v2 :vector]->
to :vector @[v1\x-v2\x, v1\y-v2\y, v1\z-v2\z]
mulv: function [v1 :vector, v2 :vector :floating][
if? is? :vector v2
-> return sum @[v1\x*... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #ABAP | ABAP | DATA: tab TYPE TABLE OF string.
tab = VALUE #(
FOR i = 1 WHILE i <= 100 (
COND string( LET r3 = i MOD 3
r5 = i MOD 5 IN
WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|
WHEN r3 = 0 THEN |FIZZ|
WHEN r5 = 0 THEN |BUZZ|
... |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #C | C | #include <stdio.h>
#include <time.h>
static const char *months[] = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"};
static int long_months[] = {0, 2, 4, 6, 7, 9, 11};
int main() {
int n = 0, y, i, m;
struct tm t = {0};
printf... |
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 ... | #Haskell | Haskell | import Control.Monad (guard)
import Data.List (find, unfoldr)
import Data.Char (intToDigit)
import qualified Data.Set as Set
import Text.Printf (printf)
digits :: Integral a => a -> a -> [a]
digits
b = unfoldr
(((>>) . guard . (0 /=)) <*> (pure . ((,) <$> (`mod` b) <... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Ceylon | Ceylon | module rosetta "1.0.0" {
import ceylon.numeric "1.2.1";
} |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Clojure | Clojure |
(use 'clojure.contrib.math)
(let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))]
inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]]
(map #(% 0.5) (map #(comp %1 %2) fns inv)))
|
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Haskell | Haskell | import Control.Monad (replicateM, unless)
import Data.List (tails, transpose)
import System.Random (randomRIO)
data Cell
= Empty
| Tree
| Fire
deriving (Eq)
instance Show Cell where
show Empty = " "
show Tree = "T"
show Fire = "$"
randomCell :: IO Cell
randomCell = fmap ([Empty, Tree] !!) (randomRIO... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #PicoLisp | PicoLisp | (let Envs
(mapcar
'((N) (list (cons 'N N) (cons 'Cnt 0))) # Build environments
(range 1 12) )
(while (find '((E) (job E (> N 1))) Envs) # Until all values are 1:
(for E Envs
(job E # Use environment 'E'
(prin (align 4 N))
(unless... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Python | Python | environments = [{'cnt':0, 'seq':i+1} for i in range(12)]
code = '''
print('% 4d' % seq, end='')
if seq != 1:
cnt += 1
seq = 3 * seq + 1 if seq & 1 else seq // 2
'''
while any(env['seq'] > 1 for env in environments):
for env in environments:
exec(code, globals(), env)
print()
print('Counts'... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #R | R | code <- quote(
if (n == 1) n else {
count <- count + 1;
n <- if (n %% 2 == 1) 3 * n + 1 else n/2
})
eprint <- function(envs, var="n")
cat(paste(sprintf("%4d", sapply(envs, `[[`, var)), collapse=" "), "\n")
envs <- mapply(function(...) list2env(list(...)), n=1:12, count=... |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | (flatten):
for i in copy:
i
if = :list type dup:
(flatten)
flatten l:
[ (flatten) l ]
!. flatten [ [ 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 ... | #Phix | Phix | integer w, h
string board, target
procedure new_board()
board = ""
h = prompt_number("Enter number of rows(1..9):",{1,9})
w = prompt_number("Enter number of columns(1..26):",{1,26})
string line = ""
for j=1 to w do line &= 'A'+j-1 end for
board = " "&line&"\n"
for i=1 to h do
li... |
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 ... | #PL.2FI | PL/I | (subscriptrange, stringrange, stringsize):
flip: procedure options (main);
declare n fixed binary;
put skip list ('This is the bit-flipping game. What size of board do you want?');
get list (n);
put skip list
('Your task is to change your board so as match the board on the right (the objective)');
... |
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 ... | #Phix | Phix | with javascript_semantics
function p(integer L, n)
atom logof2 = log10(2)
integer places = trunc(log10(L)),
nfound = 0, i = 1
while true do
atom a = i * logof2,
b = trunc(power(10,a-trunc(a)+places))
if L == b then
nfound += 1
if nfound == n t... |
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 m... | #OCaml | OCaml | # let x = 2.0;;
# let y = 4.0;;
# let z = x +. y;;
# let coll = [ x; y; z];;
# let inv_coll = List.map (fun x -> 1.0 /. x) coll;;
# let multiplier n1 n2 = (fun t -> n1 *. n2 *. t);;
(* create a list of new functions *)
# let func_list = List.map2 (fun n inv -> (multiplier n inv)) coll inv_coll;;
# List.ma... |
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 m... | #Oforth | Oforth | : multiplier(n1, n2) #[ n1 n2 * * ] ;
: firstClassNum
| x xi y yi z zi |
2.0 ->x
0.5 ->xi
4.0 ->y
0.25 ->yi
x y + ->z
x y + inv ->zi
[ x, y, z ] [ xi, yi, zi ] zipWith(#multiplier) map(#[ 0.5 swap perform ] ) . ; |
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 Struc... | #PL.2FI | PL/I |
LEAVE
The LEAVE statement terminates execution of a loop.
Execution resumes at the next statement after the loop.
ITERATE
The ITERATE statement causes the next iteration of the loop to
commence. Any statements between ITERATE and the end of the loop
are not executed.
STOP
Terminates execution of ei... |
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 Struc... | #Pop11 | Pop11 | while condition1 do
while condition2 do
if condition3 then
quitloop(2);
endif;
endwhile;
endwhile; |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #F.23 | F# | open System
[<EntryPoint>]
let main argv =
// columns and rows are 0-based, so the input has to be decremented:
let maxRow =
match UInt32.TryParse(argv.[0]) with
| (true, v) when v > 0u -> int (v - 1u)
| (_, _) -> failwith "not a positive integer"
let len (n: int) = int (Math.Fl... |
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 ... | #ObjectIcon | ObjectIcon | #
# Floyd-Warshall algorithm.
#
# See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
#
import io
import ipl.array
import ipl.printf
record fw_results (n, distance, next_vertex)
procedure main ()
local example_graph
local fw
local u, v
example_graph := [[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 ... | #SPL | SPL | multiply(a,b) <= a*b |
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 ... | #SSEM | SSEM | 01000000000000100000000000000000 0. -2 to c
00100000000000000000000000000000 1. 4 to CI
01111111111111111111111111111111 2. -2
00000000000001110000000000000000 3. Stop
11100000000000000000000000000000 4. 7 |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Picat | Picat | go =>
L = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
foreach(I in 1..L.length-1)
println([d=I,diffi(L,I)])
end,
nl,
% All differences (a sublist to save space)
println(alldiffs(L[1..6])),
nl.
% Difference of the list
diff(L) = Diff =>
Diff = [L[I]-L[I-1] : I in 2..L.length].
% The i'th ... |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #PicoLisp | PicoLisp | (de fdiff (Lst)
(mapcar - (cdr Lst) Lst) )
(for (L (90 47 58 29 22 32 55 5 55 73) L (fdiff L))
(println L) ) |
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.
| #Stata | Stata | . display %010.3f (57/8)
000007.125 |
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.
| #Suneido | Suneido | Print(7.125.Pad(9)) |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #PureBasic | PureBasic | ;Because no representation for a solitary bit is present, bits are stored as bytes.
;Output values from the constructive building blocks is done using pointers (i.e. '*').
Procedure.b notGate(x)
ProcedureReturn ~x
EndProcedure
Procedure.b xorGate(x,y)
ProcedureReturn (x & notGate(y)) | (notGate(x) & y)
EndProc... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Julia | Julia | function mediansorted(x::AbstractVector{T}, i::Integer, l::Integer)::T where T
len = l - i + 1
len > zero(len) || throw(ArgumentError("Array slice cannot be empty."))
mid = i + len ÷ 2
return isodd(len) ? x[mid] : (x[mid-1] + x[mid]) / 2
end
function fivenum(x::AbstractVector{T}) where T<:AbstractFloa... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Kotlin | Kotlin | // version 1.2.21
fun median(x: DoubleArray, start: Int, endInclusive: Int): Double {
val size = endInclusive - start + 1
require (size > 0) { "Array slice cannot be empty" }
val m = start + size / 2
return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0
}
fun fivenum(x: DoubleArray): DoubleArr... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #ALGOL_68 | ALGOL 68 | BEGIN # find the missing permutation in a list using the XOR method of the Raku sample #
# the list to find the missing permutation of #
[]STRING list = ( "ABCD", "CABD", "ACDB", "DACB", "BCDA"
, "ACBD", "ADCB", "CDAB", "DABC", "BCAD"
, "CADB", "CDBA", "CBAD", "ABDC", "AD... |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #AWK | AWK |
# syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year]
BEGIN {
split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year
year = (ARGV[1] == "") ? strftime("%Y") : ARGV[1]
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
daynum_array[2] = 29
... |
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) .
| #BASIC | BASIC | 0 A = 1:B = 2: HOME : VTAB 21: HGR : HCOLOR= 3: FOR L = A TO B: READ X1(L),Y1(L),X2(L),Y2(L): HPLOT X1(L),Y1(L) TO X2(L),Y2(L): NEXT : DATA4,0,6,10,0,3,10,7
1 GOSUB 5: IF NAN THEN PRINT "THE LINES DO NOT INTERSECT, THEY ARE EITHER PARALLEL OR CO-INCIDENT."
2 IF NOT NAN THEN PRINT "POINT OF INTERSECTION : "X" "Y... |
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #AutoHotkey | AutoHotkey | /*
; https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection#Algebraic_form
l = line vector
lo = point on the line
n = plane normal vector
Po = point on the plane
if (l . n) = 0 ; line and plane are parallel.
if (Po - lo) . n = 0 ; line is contained in the plane.
(P - Po) . n = 0 ; vector equatio... |
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)
... | #ACL2 | ACL2 | (defun fizzbuzz-r (i)
(declare (xargs :measure (nfix (- 100 i))))
(prog2$
(cond ((= (mod i 15) 0) (cw "FizzBuzz~%"))
((= (mod i 5) 0) (cw "Buzz~%"))
((= (mod i 3) 0) (cw "Fizz~%"))
(t (cw "~x0~%" i)))
(if (zp (- 100 i))
nil
(fizzbuzz-r (1+ i)))))
(defun fizz... |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #C.23 | C# | using System;
namespace _5_Weekends
{
class Program
{
const int FIRST_YEAR = 1900;
const int LAST_YEAR = 2100;
static int[] _31_MONTHS = { 1, 3, 5, 7, 8, 10, 12 };
static void Main(string[] args)
{
int totalNum = 0;
int totalNo5Weekends = 0;
... |
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 ... | #J | J |
pandigital=: [ = [: # [: ~. #.inv NB. BASE pandigital Y
|
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 ... | #Java | Java | import java.math.BigInteger;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Program {
static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|";
stat... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #CoffeeScript | CoffeeScript | # Functions as values of a variable
cube = (x) -> Math.pow x, 3
cuberoot = (x) -> Math.pow x, 1 / 3
# Higher order function
compose = (f, g) -> (x) -> f g(x)
# Storing functions in a array
fun = [Math.sin, Math.cos, cube]
inv = [Math.asin, Math.acos, cuberoot]
# Applying the composition to 0.5
console.log compose... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Icon_and_Unicon | Icon and Unicon | link graphics,printf
$define EDGE 0
$define EMPTY 1
$define TREE 2
$define FIRE 3
global Colours,Width,Height,ProbTree,ProbFire,ProbInitialTree,Forest,oldForest
procedure main() # forest fire
Height := 400 # Window height
Width := 400 # Window width
ProbInitial... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Racket | Racket |
#lang racket
(define namespaces
(for/list ([i (in-range 1 13)])
(define ns (make-base-namespace))
(eval `(begin (define N ,i) (define count 0)) ns)
ns))
(define (get-var-values name)
(map (curry namespace-variable-value name #t #f) namespaces))
(define code
'(when (> N 1)
(set! N (if (eve... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Raku | Raku | my $calculator = sub ($n is rw) {
return ($n == 1) ?? 1 !! $n %% 2 ?? $n div 2 !! $n * 3 + 1
};
sub next (%this, &get_next) {
return %this if %this.<value> == 1;
%this.<value>.=&get_next;
%this.<count>++;
return %this;
};
my @hailstones = map { %(value => $_, count => 0) }, 1 .. 12;
while not ... |
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
| #E | E | def flatten(nested) {
def flat := [].diverge()
def recur(x) {
switch (x) {
match list :List { for elem in list { recur(elem) } }
match other { flat.push(other) }
}
}
recur(nested)
return flat.snapshot()
} |
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 ... | #Python | Python | """
Given a %i by %i sqare array of zeroes or ones in an initial
configuration, and a target configuration of zeroes and ones
The task is to transform one to the other in as few moves as
possible by inverting whole numbered rows or whole lettered
columns at once.
In an inversion any 1 becomes 0 and any 0 becomes 1 fo... |
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 ... | #Python | Python | from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
... |
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 m... | #Oz | Oz | declare
[X Y Z] = [2.0 4.0 Z=X+Y]
[XI YI ZI] = [0.5 0.25 1.0/(X+Y)]
fun {Multiplier A B}
fun {$ M}
A * B * M
end
end
in
for
N in [X Y Z]
I in [XI YI ZI]
do
{Show {{Multiplier N I} 0.5}}
end |
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 m... | #PARI.2FGP | PARI/GP | multiplier(n1,n2)={
x -> n1 * n2 * x
};
test()={
my(x = 2.0, xi = 0.5, y = 4.0, yi = 0.25, z = x + y, zi = 1.0 / ( x + y ));
print(multiplier(x,xi)(0.5));
print(multiplier(y,yi)(0.5));
print(multiplier(z,zi)(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 Struc... | #PureBasic | PureBasic | If OpenConsole()
top:
i = i + 1
PrintN("Hello world.")
If i < 10
Goto top
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
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 Struc... | #Python | Python | # Search for an odd factor of a using brute force:
for i in range(n):
if (n%2) == 0:
continue
if (n%i) == 0:
result = i
break
else:
result = None
print "No odd factors found" |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Factor | Factor | USING: io kernel math math.functions math.ranges prettyprint
sequences ;
IN: rosetta-code.floyds-triangle
: floyd. ( n -- )
[ dup 1 - * 2 / 1 + dup 1 ] [ [1,b] ] bi
[
[
2dup [ log10 1 + >integer ] bi@ -
[ " " write ] times dup pprint bl [ 1 + ] bi@
] times nl [ drop dup... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Forth | Forth | : lastn ( rows -- n ) dup 1- * 2/ ;
: width ( n -- n ) s>f flog ftrunc f>s 2 + ;
: triangle ( rows -- )
dup lastn 0 rot ( last 0 rows )
0 do
over cr
i 1+ 0 do
1+ swap 1+ swap
2dup width u.r
loop
drop
loop
2drop ;
|
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 ... | #OCaml | OCaml | (*
Floyd-Warshall algorithm.
See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
*)
module Square_array =
(* Square arrays with 1-based indexing. *)
struct
type 'a t =
{
n : int;
r : 'a Array.t
}
let make n fill =
... |
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 ... | #Standard_ML | Standard ML | val multiply = op * |
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 ... | #Stata | Stata | prog def multiply, return
args a b
return sca product=`a'*`b'
end
multiply 77 13
di r(product) |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #PL.2FI | PL/I |
/* Forward differences. */ /* 23 April 2010 */
differences: procedure options (main);
declare a(10) fixed(10) static initial
(7, 3, 9, 250, 300, 4, 68, 72, 154, 601);
declare (i, j, m, n, t, u) fixed binary;
m = hbound(a,1);
get (n); if n > m then signal error;
put skip edit (a) (F(7));
do i... |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Plain_English | Plain English | To add a fraction to some fraction things:
Allocate memory for a fraction thing.
Put the fraction into the fraction thing's fraction.
Append the fraction thing to the fraction things.
To create some fraction things:
Add 90-1/2 to the fraction things.
Add 47/1 to the fraction things.
Add 58/1 to the fraction things.
A... |
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.
| #Tcl | Tcl | set number 7.342
format "%08.3f" $number |
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.
| #TI-89_BASIC | TI-89 BASIC | right("00000" & format(7.12511, "f3"), 9) |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Python | Python | def xor(a, b): return (a and not b) or (b and not a)
def ha(a, b): return xor(a, b), a and b # sum, carry
def fa(a, b, ci):
s0, c0 = ha(ci, a)
s1, c1 = ha(s0, b)
return s1, c0 or c1 # sum, carry
def fa4(a, b):
width = 4
ci = [None] * width
co = [None] * width
s = [None] * widt... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Lua | Lua | function slice(tbl, low, high)
local copy = {}
for i=low or 1, high or #tbl do
copy[#copy+1] = tbl[i]
end
return copy
end
-- assumes that tbl is sorted
function median(tbl)
m = math.floor(#tbl / 2) + 1
if #tbl % 2 == 1 then
return tbl[m]
end
return (tbl[m-1] + tbl[m... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #APL | APL | missing ← ((⊂↓⍳¨⌊/) +⌿∘(⊢∘.=∪∘∊)) ⌷ ∪∘∊ |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
set /p yr= Enter year:
echo.
call:monthdays %yr% list
set mm=1
for %%i in (!list!) do (
call:calcdow !yr! !mm! %%i dow
set/a lsu=%%i-dow
set mf=0!mm!
echo !yr!-!mf:~-2!-!lsu!
set /a mm+=1
)
pause
exit /b
:monthdays yr &list
setlocal
call:isleap %1 ly
for /L %%i... |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #BBC_BASIC | BBC BASIC |
INSTALL @lib$+"DATELIB"
INPUT "What year to calculate (YYYY)? " Year%
PRINT '"Last Sundays in ";Year%;" are on:"
FOR Month%=1 TO 12
PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%))
NEXT
END
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double lineSlope(point a,point b){
if(a.x-b.x == 0.0)
return NAN;
else
return (a.y-b.y)/(a.x-b.x);
}
point extractPoint(char* str){
int i,j,start,end,length;
char* holder;
point c;
for(i=0;str[i]!=00;i++){
... |
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 ... | #C | C |
#include<stdio.h>
typedef struct{
double x,y,z;
}vector;
vector addVectors(vector a,vector b){
return (vector){a.x+b.x,a.y+b.y,a.z+b.z};
}
vector subVectors(vector a,vector b){
return (vector){a.x-b.x,a.y-b.y,a.z-b.z};
}
double dotProduct(vector a,vector b){
return a.x*b.x + a.y*b.y + a.z*b.z;
}
vector ... |
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)
... | #Action.21 | Action! | PROC Main()
BYTE i,d3,d5
d3=1 d5=1
FOR i=1 TO 100
DO
IF d3=0 AND d5=0 THEN
Print("FizzBuzz")
ELSEIF d3=0 THEN
Print("Fizz")
ELSEIF d5=0 THEN
Print("Buzz")
ELSE
PrintB(i)
FI
Put(32)
d3==+1 d5==+1
IF d3=3 THEN d3=0 FI
IF d5=5 THEN d5=0 FI
OD
RETURN |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #C.2B.2B | C++ | #include <vector>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace boost::gregorian ;
void print( const date &d ) {
std::cout << d.year( ) << "-" << d.month( ) << "\n" ;
}
int main( ) {
greg_month longmonths[ ] = {Jan, Mar , May , ... |
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 ... | #JavaScript | JavaScript | (() => {
'use strict';
// allDigitSquare :: Int -> Int
const allDigitSquare = base => {
const bools = replicate(base, false);
return untilSucc(
allDigitsUsedAtBase(base, bools),
ceil(sqrt(parseInt(
'10' + '0123456789abcdef'.slice(2, base),
... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Common_Lisp | Common Lisp | (defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
(loop with value = 0.5
for func in (list #'sin #'cos #'cube )
for inverse in (list #'asin #'acos #'cube-root)
for composed = (compose inverse func)
do (format t ... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #J | J | NB. states: 0 empty, 1 tree, _1 fire
dims =:10 10
tessellate=: 0,0,~0,.0,.~ 3 3 >./@,;._3 ]
mask=: tessellate dims$1
chance=: 1 :'(> ? bind (dims$0)) bind (mask*m)'
start=: 0.5 chance
grow =: 0.01 chance
fire =: 0.001 chance
spread=: [: tessellate 0&>
step=: grow [`]@.(|@])"0 >.&0 * _1 ^ fire +. sprea... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #REXX | REXX | /*REXX pgm illustrates N 1st─class environments (using numbers from a hailstone seq).*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 12 /*Was N defined? No, then use default.*/
@.= ... |
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
| #EchoLisp | EchoLisp |
(define (fflatten l)
(cond
[(null? l) null]
[(not (list? l)) (list l)]
[else (append (fflatten (first l)) (fflatten (rest l)))]))
;;
(define L' [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])
(fflatten L) ;; use custom function
→ (1 2 3 4 5 6 7 8)
(flatten L) ;; use built-in
→ (1 2 3 4 5 6 7 8)
;; Remarks
;; null is... |
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 ... | #QB64 | QB64 |
RANDOMIZE TIMER
DIM SHARED cellsPerSide, legalMoves$, startB$, currentB$, targetB$, moveCount
restart
DO
displayStatus
IF currentB$ = targetB$ THEN 'game done!
PRINT " Congratulations, done in"; moveCount; " moves."
PRINT "": PRINT " Press y for yes, if you want to start over > ";
ye... |
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 ... | #Racket | Racket | #lang racket
(define (flip-row! pzzl r)
(define N (integer-sqrt (bytes-length pzzl)))
(for* ((c (in-range N)))
(define idx (+ c (* N r)))
(bytes-set! pzzl idx (- 1 (bytes-ref pzzl idx)))))
(define (flip-col! pzzl c)
(define N (integer-sqrt (bytes-length pzzl)))
(for* ((r (in-range N)))
(define idx... |
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 ... | #Racket | Racket | #lang racket
(define (fract-part f)
(- f (truncate f)))
(define ln10 (log 10))
(define ln2/ln10 (/ (log 2) ln10))
(define (inexact-p-test L)
(let ((digit-shift (let loop ((L (quotient L 10)) (shift 1))
(if (zero? L) shift (loop (quotient L 10) (* 10 shift))))))
(λ (p) (= L (truncate (... |
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 ... | #Raku | Raku | use Lingua::EN::Numbers;
constant $ln2ln10 = log(2) / log(10);
my @startswith12 = ^∞ .grep: { ( 10 ** ($_ * $ln2ln10 % 1) ).substr(0,3) eq '1.2' };
my @startswith123 = lazy gather loop {
state $pre = '1.23';
state $count = 0;
state $this = 0;
given $this {
when 196 {
$this ... |
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 m... | #Perl | Perl | sub multiplier {
my ( $n1, $n2 ) = @_;
sub {
$n1 * $n2 * $_[0];
};
}
my $x = 2.0;
my $xi = 0.5;
my $y = 4.0;
my $yi = 0.25;
my $z = $x + $y;
my $zi = 1.0 / ( $x + $y );
my %zip;
@zip{ $x, $y, $z } = ( $xi, $yi, $zi );
while ( my ( $number, $inverse ) = each %zip ) {
print multiplier( $n... |
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 m... | #Phix | Phix | with javascript_semantics
sequence mtable = {}
function multiplier(atom n1, atom n2)
mtable = append(mtable,{n1,n2})
return length(mtable)
end function
function call_multiplier(integer f, atom m)
atom {n1,n2} = mtable[f]
return n1*n2*m
end function
constant x = 2,
xi = 0.5,
y = 4,
... |
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 Struc... | #Racket | Racket |
#lang racket
;; some silly boilerplate to mimic the assembly code better
(define r0 0)
(define (cmp r1 r2) (set! r0 (sgn (- r1 r2))))
(define (je true-label false-label) (if (zero? r0) (true-label) (false-label)))
(define (goto label) (label))
(define (gcd %eax %ecx)
(define %edx 0)
(define (main) (goto loop)... |
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 Struc... | #Raku | Raku | TOWN: goto TOWN; |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 22:55:08
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a 1223334444
!gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f
! 1
! 2 3
! 4 5 6
! 7 8 9 10
! 11 12 13 14 15
!
!
! 1
! 2 3
! 4 5 6
! 7 ... |
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 ... | #Perl | Perl | sub FloydWarshall{
my $edges = shift;
my (@dist, @seq);
my $num_vert = 0;
# insert given dists into dist matrix
map {
$dist[$_->[0] - 1][$_->[1] - 1] = $_->[2];
$num_vert = $_->[0] if $num_vert < $_->[0];
$num_vert = $_->[1] if $num_vert < $_->[1];
} @$edges;
my @vert... |
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 ... | #Swift | Swift | func multiply(a: Double, b: Double) -> Double {
return a * b
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.