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/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 ... | #Tcl | Tcl | proc multiply { arg1 arg2 } {
return [expr {$arg1 * $arg2}]
} |
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... | #Pop11 | Pop11 | define forward_difference(l);
lvars res = [], prev, el;
if l = [] then
return([]);
endif;
front(l) -> prev;
for el in back(l) do
cons(el - prev, res) -> res;
el -> prev;
endfor;
rev(res);
enddefine;
define nth_difference(l, n);
lvars res = l, i;
for i from 1... |
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... | #PowerShell | PowerShell | function Forward-Difference( [UInt64] $n, [Array] $f )
{
$flen = $f.length
if( $flen -gt [Math]::Max( 1, $n ) )
{
0..( $flen - $n - 1 ) | ForEach-Object {
$l=0;
for( $k = 0; $k -le $n; $k++ )
{
$j = 1
for( $i = 1; $i -le $k; $i++ )
{
$j *= ( ( $n - $k + $i ) / $i )
}
$l += $j * ( ... |
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.
| #Toka | Toka | needs values
value n
123 to n
2 import printf
" %08d" n printf |
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.
| #Ursala | Ursala | #import flo
x = 7.125
#show+
t = <printf/'%09.3f' x> |
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 ... | #Racket | Racket | #lang racket
(define (adder-and a b)
(if (= 2 (+ a b)) 1 0)) ; Defining the basic and function
(define (adder-not a)
(if (zero? a) 1 0)) ; Defining the basic not function
(define (adder-or a b)
(if (> (+ a b) 0) 1 0)) ; Defining the basic or function
(define (adder-xor a b)
(adder-or
(ad... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave |
function r = fivenum(x)
r = quantile(x,[0:4]/4);
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 i... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[FiveNum]
FiveNum[x_List] := Quantile[x, Range[0, 1, 1/4]]
FiveNum[RandomVariate[NormalDistribution[], 10000]] |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #AppleScript | AppleScript | use framework "Foundation" -- ( sort )
--------------- RAREST LETTER IN EACH COLUMN -------------
on run
concat(map(composeList({¬
head, ¬
minimumBy(comparing(|length|)), ¬
group, ¬
sort}), ¬
transpose(map(chars, ¬
|words|("ABCD CABD ACDB DACB BCDA ACBD " & ¬
... |
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... | #Befunge | Befunge | ":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v
v2++6**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5<
>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v
^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6
>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8
^<# #"#"##"#"##!` +76:+1g00,+55,+*< |
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.23 | C# | using System;
using System.Drawing;
public class Program
{
static PointF FindIntersection(PointF s1, PointF e1, PointF s2, PointF e2) {
float a1 = e1.Y - s1.Y;
float b1 = s1.X - e1.X;
float c1 = a1 * s1.X + b1 * s1.Y;
float a2 = e2.Y - s2.Y;
float b2 = s2.X - e2.X;
... |
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.23 | C# | using System;
namespace FindIntersection {
class Vector3D {
private double x, y, z;
public Vector3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Vector3D operator +(Vector3D lhs, Vector3D rhs) {
... |
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)
... | #ActionScript | ActionScript | for (var i:int = 1; i <= 100; i++) {
if (i % 15 == 0)
trace('FizzBuzz');
else if (i % 5 == 0)
trace('Buzz');
else if (i % 3 == 0)
trace('Fizz');
else
trace(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 leas... | #Ceylon | Ceylon |
module rosetta.fiveweekends "1.0.0" {
import ceylon.time "1.2.2";
}
|
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... | #Clojure | Clojure | (import java.util.GregorianCalendar
java.text.DateFormatSymbols)
(->> (for [year (range 1900 2101)
month [0 2 4 6 7 9 11] ;; 31 day months
:let [cal (GregorianCalendar. year month 1)
day (.get cal GregorianCalendar/DAY_OF_WEEK)]
:when (= day GregorianCalendar/FRIDAY)]
(println month "-" year))
... |
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 ... | #Julia | Julia | const num = "0123456789abcdef"
hasallin(n, nums, b) = (s = string(n, base=b); all(x -> occursin(x, s), nums))
function squaresearch(base)
basenumerals = [c for c in num[1:base]]
highest = parse(Int, "10" * num[3:base], base=base)
for n in Int(trunc(sqrt(highest))):highest
if hasallin(n * n, basenu... |
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 ... | #Kotlin | Kotlin | import java.math.BigInteger
import java.time.Duration
import java.util.ArrayList
import java.util.HashSet
import kotlin.math.sqrt
const val ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"
var base: Byte = 0
var bmo: Byte = 0
var blim: Byte = 0
var ic: Byte = 0
var st0: Long = 0
var bllim:... |
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... | #D | D | void main() {
import std.stdio, std.math, std.typetuple, std.functional;
alias dir = TypeTuple!(sin, cos, x => x ^^ 3);
alias inv = TypeTuple!(asin, acos, cbrt);
// foreach (f, g; staticZip!(dir, inv))
foreach (immutable i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
} |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Dart | Dart | import 'dart:math' as Math;
cube(x) => x*x*x;
cuberoot(x) => Math.pow(x, 1/3);
compose(f,g) => ((x)=>f(g(x)));
main(){
var functions = [Math.sin, Math.exp, cube];
var inverses = [Math.asin, Math.log, cuberoot];
for (int i = 0; i < 3; i++){
print(compose(functions[i], inverses[i])(0.5));
}
} |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #JAMES_II.2FRule-based_Cellular_Automata | JAMES II/Rule-based Cellular Automata | @caversion 1;
dimensions 2;
state EMPTY, TREE, BURNING;
// an empty cell grows a tree with a chance of p = 5 %
rule{EMPTY} [0.05] : -> TREE;
// a burning cell turns to a burned cell
rule{BURNING}: -> EMPTY;
// a tree starts burning if there is at least one neighbor burning
rule{TREE} : BURNING{1,} -> BURNING;... |
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 "... | #Ruby | Ruby | # Build environments
envs = (1..12).map do |n|
Object.new.instance_eval {@n = n; @cnt = 0; self}
end
# Until all values are 1:
until envs.all? {|e| e.instance_eval{@n} == 1}
envs.each do |e|
e.instance_eval do # Use environment _e_
printf "%4s", @n
if @n > 1
@cnt += 1 ... |
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 "... | #Sidef | Sidef | func calculator({.is_one} ) { 1 }
func calculator(n {.is_even}) { n / 2 }
func calculator(n ) { 3*n + 1 }
func succ(this {_{:value}.is_one}, _) {
return this
}
func succ(this, get_next) {
this{:value} = get_next(this{:value})
this{:count}++
return this
}
var enviornments = (1..12 -> ma... |
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
| #Ela | Ela | xs = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
flat = flat' []
where flat' n [] = n
flat' n (x::xs)
| x is List = flat' (flat' n xs) x
| else = x :: flat' n xs
flat xs |
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 ... | #Raku | Raku | sub MAIN ($square = 4) {
say "{$square}? Seriously?" and exit if $square < 1 or $square > 26;
my %bits = map { $_ => %( map { $_ => 0 }, ('A' .. *)[^ $square] ) },
(1 .. *)[^ $square];
scramble %bits;
my $target = build %bits;
scramble %bits until build(%bits) ne $target;
display($target... |
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 ... | #REXX | REXX | /*REXX program computes powers of two whose leading decimal digits are "12" (in base 10)*/
parse arg L n b . /*obtain optional arguments from the CL*/
if L=='' | L=="," then L= 12 /*Not specified? Then use the default.*/
if n=='' | n=="," then n= 1 ... |
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... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(de multiplier (N1 N2)
(curry (N1 N2) (X)
(*/ N1 N2 X `(* 1.0 1.0)) ) )
(let (X 2.0 Xi 0.5 Y 4.0 Yi 0.25 Z (+ X Y) Zi (*/ 1.0 1.0 Z))
(mapc
'((Num Inv)
(prinl (format ((multiplier Inv Num) 0.5) *Scl)) )
(list X Y Z)
(list Xi Yi Zi) ) ) |
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... | #Python | Python | IDLE 2.6.1
>>> # Number literals
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
>>> # Numbers from calculation
>>> z = x + y
>>> zi = 1.0 / (x + y)
>>> # The multiplier function is similar to 'compose' but with numbers
>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)
>>> # Numbers as members of collections
>>> numlis... |
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... | #REBOL | REBOL | rebol [
Title: "Flow Control"
URL: http://rosettacode.org/wiki/Flow_Control_Structures
]
; return -- Return early from function (normally, functions return
; result of last evaluation).
hatefive: func [
"Prints value unless it's the number 5."
value "Value to print."
][
if value = 5 [return "I hate five!"]
pr... |
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... | #Relation | Relation | call routineName /*no arguments passed to routine.*/
call routineName 50 /*one argument (fifty) passed. */
call routineName 50,60 /*two arguments passed. */
call routineName 50, 60 /*(same as above) */
call routineName 5... |
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... | #FreeBASIC | FreeBASIC | ' version 19-09-2015
' compile with: fbc -s console
Sub pascal_triangle(n As UInteger)
Dim As UInteger a = 1, b, i, j, switch = n + 1
Dim As String frmt, frmt_1, frmt_2
' last number of the last line
i = (n * (n + 1)) \ 2
frmt_2 = String(Len(Str(i)) + 1, "#")
' first number of the last lin... |
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 ... | #Phix | Phix | constant inf = 1e300*1e300
function Path(integer u, integer v, sequence next)
if next[u,v]=null then
return ""
end if
sequence path = {sprintf("%d",u)}
while u!=v do
u = next[u,v]
path = append(path,sprintf("%d",u))
end while
return join(path,"->")
end function
procedure... |
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 ... | #TI-89_BASIC | TI-89 BASIC | multiply(a, b)
Func
Return a * b
EndFunc |
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... | #PureBasic | PureBasic | Procedure forward_difference(List a())
If ListSize(a()) <= 1
ClearList(a()): ProcedureReturn
EndIf
Protected NewList b()
CopyList(a(), b())
LastElement(a()): DeleteElement(a())
SelectElement(b(), 1)
ForEach a()
a() - b(): NextElement(b())
Next
EndProcedure
Procedure nth_difference(List a(), 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.
| #Vala | Vala | void main() {
double r = 7.125;
print(" %9.3f\n", -r);
print(" %9.3f\n",r);
print(" %-9.3f\n",r);
print(" %09.3f\n",-r);
print(" %09.3f\n",r);
print(" %-09.3f\n",r);
} |
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.
| #VBA | VBA | Option Explicit
Sub Main()
Debug.Print fFormat(13, 2, 1230.3333)
Debug.Print fFormat(2, 13, 1230.3333)
Debug.Print fFormat(10, 5, 0.3333)
Debug.Print fFormat(13, 2, 1230)
End Sub
Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String
'NbInt : Lenght of integral part
'NbDec : Lenght of ... |
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 ... | #Raku | Raku | sub xor ($a, $b) { (($a and not $b) or (not $a and $b)) ?? 1 !! 0 }
sub half-adder ($a, $b) {
return xor($a, $b), ($a and $b);
}
sub full-adder ($a, $b, $c0) {
my ($ha0_s, $ha0_c) = half-adder($c0, $a);
my ($ha1_s, $ha1_c) = half-adder($ha0_s, $b);
return $ha1_s, ($ha0_c or $ha1_c);
}
sub four-bit... |
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... | #Modula-2 | Modula-2 | MODULE Fivenum;
FROM FormatString IMPORT FormatString;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteLongReal(v : LONGREAL);
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
RealToStr(v, buf);
WriteString(buf)
END WriteLongReal;
PROCEDURE WriteArray(arr : ARRAY OF LON... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Arturo | Arturo | perms: [
"ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC"
"BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD"
"BADC" "BDAC" "CBDA" "DBCA" "DCAB"
]
allPerms: map permutate split "ABCD" => join
print first difference allPerms perms |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #C | C |
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};
int m, y, w;
if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1;
days[1] -= (y % 4) || (!(y % 100) && (y % 400));
w = y * 365 + 97 * (y - 1) / 40... |
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.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
/** Calculate determinant of matrix:
[a b]
[c d]
*/
inline double Det(double a, double b, double c, double d)
{
return a*d - b*c;
}
/// Calculate intersection of two lines.
///\return true if found, false if not found or error
bool Line... |
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.2B.2B | C++ | #include <iostream>
#include <sstream>
class Vector3D {
public:
Vector3D(double x, double y, double z) {
this->x = x;
this->y = y;
this->z = z;
}
double dot(const Vector3D& rhs) const {
return x * rhs.x + y * rhs.y + z * rhs.z;
}
Vector3D operator-(const Vector3D& rhs) const {
return Vector3D(x - r... |
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)
... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Fizzbuzz is
begin
for I in 1..100 loop
if I mod 15 = 0 then
Put_Line("FizzBuzz");
elsif I mod 5 = 0 then
Put_Line("Buzz");
elsif I mod 3 = 0 then
Put_Line("Fizz");
else
Put_Line(Integer'Image(I));
end if;... |
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... | #COBOL | COBOL |
program-id. five-we.
data division.
working-storage section.
1 wk binary.
2 int-date pic 9(8).
2 dow pic 9(4).
2 friday pic 9(4) value 5.
2 mo-sub pic 9(4).
2 months-with-5 pic 9(4) value 0.
2 years-no-5 pic 9(4) value 0.
2 5-we-flag ... |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[FirstSquare]
FirstSquare[b_Integer] := Module[{n, alldigits, digs, start},
digs = Range[0, b - 1];
digs[[{2, 1}]] //= Reverse;
start = Floor[Sqrt[FromDigits[digs, b]]];
n = start;
alldigits = Range[0, b - 1];
While[! ContainsAll[IntegerDigits[n^2, b], alldigits], n++];
{b, n, start, BaseForm[n, b... |
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 ... | #Nim | Nim | import algorithm, math, strformat
const Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
func toBaseN(num, base: Natural): string =
doAssert(base in 2..Alphabet.len, &"base must be in 2..{Alphabet.len}")
var num = num
while true:
result.add(Alphabet[num mod base])
num = num div base
if num == 0... |
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... | #Delphi | Delphi |
program First_class_functions;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
type
TFunctionTuple = record
forward, backward: TFunc<Double, Double>;
procedure Assign(forward, backward: TFunc<Double, Double>);
end;
TFunctionTuples = array of TFunctionTuple;
var
cube, croot, fsin, f... |
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... | #Java | Java | import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Fire {
private static final char BURNING = 'w'; //w looks like fire, right?
private static final char TREE = 'T';
private static final char EMPTY = '.';
private static final double F = 0.2;
private static final double P = 0... |
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 "... | #Tcl | Tcl | package require Tcl 8.5
for {set i 1} {$i <= 12} {incr i} {
dict set hailenv hail$i [dict create num $i steps 0]
}
while 1 {
set loopagain false
foreach k [dict keys $hailenv] {
dict with hailenv $k {
puts -nonewline [format %4d $num]
if {$num == 1} {
continue
} elseif {$num & 1} {
set... |
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 "... | #Wren | Wren | import "/fmt" for Fmt
var environment = Fn.new {
class E {
construct new(value, count) {
_value = value
_count = count
}
value { _value }
count { _count }
hailstone() {
Fmt.write("$4d", _value)
if (_value == 1) return
... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Elixir | Elixir |
defmodule RC do
def flatten([]), do: []
def flatten([h|t]), do: flatten(h) ++ flatten(t)
def flatten(h), do: [h]
end
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
# Our own implementation
IO.inspect RC.flatten(list)
# Library function
IO.inspect List.flatten(list)
|
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 ... | #Red | Red |
Red []
random/seed now/time/precise ;; start random generator
kRows: kCols: 3 ;; define board size, 3x3 upto 9x9 possible
;; create series of 3 empty blocks:
loop kRows [ append/only board: [] copy [] ] ;; ( this is actu... |
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 ... | #Ruby | Ruby | def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then... |
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... | #R | R | multiplier <- function(n1,n2) { (function(m){n1*n2*m}) }
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
num = c(x,y,z)
inv = c(xi,yi,zi)
multiplier(num,inv)(0.5)
Output
[1] 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 m... | #Racket | Racket |
#lang racket
(define x 2.0)
(define xi 0.5)
(define y 4.0)
(define yi 0.25)
(define z (+ x y))
(define zi (/ 1.0 (+ x y)))
(define ((multiplier x y) z) (* x y z))
(define numbers (list x y z))
(define inverses (list xi yi zi))
(for/list ([n numbers] [i inverses])
((multiplier n i) 0.5))
;; -> '(0.5 0.... |
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... | #REXX | REXX | call routineName /*no arguments passed to routine.*/
call routineName 50 /*one argument (fifty) passed. */
call routineName 50,60 /*two arguments passed. */
call routineName 50, 60 /*(same as above) */
call routineName 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... | #Ring | Ring |
i = 1
while true
see i + nl
if i = 10 see "Break!" exit ok
i = i + 1
end
|
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Gambas | Gambas | Public Sub Main()
Dim siCount, siNo, siCounter As Short
Dim siLine As Short = 1
Dim siInput As Short[] = [5, 14]
For siCount = 0 To siInput.Max
Print "Floyd's triangle to " & siInput[siCount] & " lines"
Do
Inc siNo
Inc siCounter
Print Format(siNo, "####");
If siLine = siCounter Then
Pri... |
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 ... | #PHP | PHP | <?php
$graph = array();
for ($i = 0; $i < 10; ++$i) {
$graph[] = array();
for ($j = 0; $j < 10; ++$j)
$graph[$i][] = $i == $j ? 0 : 9999999;
}
for ($i = 1; $i < 10; ++$i) {
$graph[0][$i] = $graph[$i][0] = rand(1, 9);
}
for ($k = 0; $k < 10; ++$k) {
for ($i = 0; $i < 10; ++$i) {
for (... |
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 ... | #Toka | Toka | [ ( ab-c ) * ] is 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 ... | #Transd | Transd | multiply: (lambda a Double() b Double() (* a b)) |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Python | Python | >>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
>>> # or, dif = lambda s: [x-y for x,y in zip(s[1:],s)]
>>> difn = lambda s, n: difn(dif(s), n-1) if n else s
>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 0)
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 1)
[-43, 11, -29, -7, 10, 23, -50, 5... |
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.
| #VBScript | VBScript |
a = 1234.5678
' Round to three decimal places. Groups by default. Output = "1,234.568".
WScript.Echo FormatNumber(a, 3)
' Truncate to three decimal places. Output = "1234.567".
WScript.Echo Left(a, InStr(a, ".") + 3)
' Round to a whole number. Grouping disabled. Output = "1235".
WScript.Echo FormatNumber(a, 0, ... |
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.
| #Vedit_macro_language | Vedit macro language | #1 = 7125
Num_Ins(#1, FILL+COUNT, 9) Char(-3) Ins_Char('.') |
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 ... | #REXX | REXX | /*REXX program displays (all) the sums of a full 4─bit adder (with carry). */
call hdr1; call hdr2 /*note the order of headers & trailers.*/
/* [↓] traipse thru all possibilities.*/
do j=0 for 16
... |
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... | #Nim | Nim | import algorithm
type FiveNum = array[5, float]
template isOdd(n: SomeInteger): bool = (n and 1) != 0
func median(x: openArray[float]; startIndex, endIndex: Natural): float =
let size = endIndex - startIndex + 1
assert(size > 0, "array slice cannot be empty")
let m = startIndex + size div 2
result = if si... |
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... | #Perl | Perl | use POSIX qw(ceil floor);
sub fivenum {
my(@array) = @_;
my $n = scalar @array;
die "No values were entered into fivenum!" if $n == 0;
my @x = sort {$a <=> $b} @array;
my $n4 = floor(($n+3)/2)/2;
my @d = (1, $n4, ($n +1)/2, $n+1-$n4, $n);
my @sum_array;
for my $e (0..4) {
my $floor = flo... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #AutoHotkey | AutoHotkey | IncompleteList := "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
CompleteList := Perm( "ABCD" )
Missing := ""
Loop, Parse, CompleteList, `n, `r
If !InStr( IncompleteList , A_LoopField )
Missing .= "`n" A_LoopField
MsgBox Missing Permutati... |
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... | #C.23 | C# | using System;
namespace LastSundayOfEachMonth
{
class Program
{
static void Main()
{
Console.Write("Year to calculate: ");
string strYear = Console.ReadLine();
int year = Convert.ToInt32(strYear);
DateTime date;
for (int i = 1; i ... |
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) .
| #Clojure | Clojure | ;; Point is [x y] tuple
(defn compute-line [pt1 pt2]
(let [[x1 y1] pt1
[x2 y2] pt2
m (/ (- y2 y1) (- x2 x1))]
{:slope m
:offset (- y1 (* m x1))}))
(defn intercept [line1 line2]
(let [x (/ (- (:offset line1) (:offset line2))
(- (:slope line2) (:slope line1)))]
{:x x
... |
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) .
| #Common_Lisp | Common Lisp |
;; Point is [x y] tuple
(defun point-of-intersection (x1 y1 x2 y2 x3 y3 x4 y4)
"Find the point of intersection of the lines defined by the points (x1 y1) (x2 y2) and (x3 y3) (x4 y4)"
(let* ((dx1 (- x2 x1))
(dx2 (- x4 x3))
(dy1 (- y2 y1))
(dy2 (- y4 y3))
(den (- (* dy1 dx2) (* dy2... |
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 ... | #D | D | import std.stdio;
struct Vector3D {
private real x;
private real y;
private real z;
this(real x, real y, real z) {
this.x = x;
this.y = y;
this.z = z;
}
auto opBinary(string op)(Vector3D rhs) const {
static if (op == "+" || op == "-") {
mixin("re... |
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)
... | #ALGOL_68 | ALGOL 68 | main:(
FOR i TO 100 DO
printf(($gl$,
IF i %* 15 = 0 THEN
"FizzBuzz"
ELIF i %* 3 = 0 THEN
"Fizz"
ELIF i %* 5 = 0 THEN
"Buzz"
ELSE
i
FI
))
OD
) |
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... | #CoffeeScript | CoffeeScript |
startsOnFriday = (month, year) ->
# 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
new Date(year, month, 1).getDay() == 5
has31Days = (month, year) ->
new Date(year, month, 31).getDate() == 31
checkMonths = (year) ->
month = undefined
count = 0
month = 0
while month < 12
if startsOnFri... |
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 ... | #Pascal | Pascal | program project1;
//Find the smallest number n to base b, so that n*n includes all
//digits of base b
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
uses
sysutils;
const
charSet : array[0..36] of char ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
type
tNumtoBase = record
ntb_dgt : array[0..31-4] of byte;
... |
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... | #Dyalect | Dyalect | func apply(fun, x) { y => fun(x, y) }
func sum(x, y) { x + y }
let sum2 = apply(sum, 2) |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | negate:
- 0
set :A [ @++ $ @negate @-- ]
set :B [ @-- $ @++ @negate ]
test n:
for i range 0 -- len A:
if /= n call compose @B! i @A! i n:
return false
true
test to-num !prompt "Enter a number: "
if:
!print "f^-1(f(x)) = x"
else:
!print "Something went wrong."
|
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... | #JavaScript | JavaScript | "use strict"
const _ = require('lodash');
const WIDTH_ARGUMENT_POSITION = 2;
const HEIGHT_ARGUMENT_POSITION = 3;
const TREE_PROBABILITY = 0.5;
const NEW_TREE_PROBABILITY = 0.01;
const BURN_PROBABILITY = 0.0001;
const CONSOLE_RED = '\x1b[31m';
const CONSOLE_GREEN = '\x1b[... |
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 "... | #zkl | zkl | class Env{
var n,cnt=0;
fcn init(_n){n=_n; returnClass(self.f)}
fcn f{
if(n!=1){
cnt += 1;
if(n.isEven) n=n/2; else n=n*3+1;
}
n
}
} |
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
| #Elm | Elm |
import Graphics.Element exposing (show)
type Tree a
= Leaf a
| Node (List (Tree a))
flatten : Tree a -> List a
flatten tree =
case tree of
Leaf a -> [a]
Node list -> List.concatMap flatten list
-- [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
tree : Tree Int
tree = Node
[ Node [Leaf 1]
, Le... |
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 ... | #REXX | REXX | /*REXX program presents a "flipping bit" puzzle. The user can solve via it via C.L. */
parse arg N u seed . /*get optional arguments from the C.L. */
if N=='' | N=="," then N=3 /*Size given? Then use default of 3.*/
if u=='' | u=="," then u=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 ... | #Rust | Rust | fn power_of_two(l: isize, n: isize) -> isize {
let mut test: isize = 0;
let log: f64 = 2.0_f64.ln() / 10.0_f64.ln();
let mut factor: isize = 1;
let mut looop = l;
let mut nn = n;
while looop > 10 {
factor *= 10;
looop /= 10;
}
while nn > 0 {
test = test + 1;
... |
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 ... | #Scala | Scala | object FirstPowerOfTwo {
def p(l: Int, n: Int): Int = {
var n2 = n
var test = 0
val log = math.log(2) / math.log(10)
var factor = 1
var loop = l
while (loop > 10) {
factor *= 10
loop /= 10
}
while (n2 > 0) {
test += 1
val value = (factor * math.pow(10, test * lo... |
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... | #Raku | Raku | sub multiplied ($g, $f) { return { $g * $f * $^x } }
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 @numbers = $x, $y, $z;
my @inverses = $xi, $yi, $zi;
for flat @numbers Z @inverses { say multiplied($^g, $^f)(.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 m... | #REXX | REXX | /*REXX program to use a first-class function to use numbers analogously. */
nums= 2.0 4.0 6.0 /*various numbers, can have fractions.*/
invs= 1/2.0 1/4.0 1/6.0 /*inverses of the above (real) numbers.*/
m= 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... | #Ruby | Ruby | begin
# some code that may raise an exception
rescue ExceptionClassA => a
# handle code
rescue ExceptionClassB, ExceptionClassC => b_or_c
# handle ...
rescue
# handle all other exceptions
else
# when no exception occurred, execute this code
ensure
# execute this code always
end |
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... | #SAS | SAS | /* GOTO: as in other languages
STOP: to stop current data step */
data _null_;
n=1;
p=1;
L1:
put n p;
n=n+1;
if n<=p then goto L1;
p=p+1;
n=1;
if p>10 then stop;
goto L1;
run;
/* LINK: equivalent of GOSUB in BASIC
RETURN: after a LINK, or to return to the beginning of data step */
data _null_;
input ... |
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... | #Go | Go | package main
import "fmt"
func main() {
floyd(5)
floyd(14)
}
func floyd(n int) {
fmt.Printf("Floyd %d:\n", n)
lowerLeftCorner := n*(n-1)/2 + 1
lastInColumn := lowerLeftCorner
lastInRow := 1
for i, row := 1, 1; row <= n; i++ {
w := len(fmt.Sprint(lastInColumn))
if i < la... |
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 ... | #Prolog | Prolog | :- use_module(library(clpfd)).
path(List, To, From, [From], W) :-
select([To,From,W],List,_).
path(List, To, From, [Link|R], W) :-
select([To,Link,W1],List,Rest),
W #= W1 + W2,
path(Rest, Link, From, R, W2).
find_path(Din, From, To, [From|Pout], Wout) :-
between(1, 4, From),
between(1, 4, To... |
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 ... | #TXR | TXR | @(define multiply (a b out))
@(bind out @(* a b))
@(end)
@(multiply 3 4 result) |
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 ... | #uBasic.2F4tH_2 | uBasic/4tH | PRINT FUNC (_Multiply (2,3))
END
_Multiply PARAM (2)
RETURN (a@ * b@) |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Quackery | Quackery | [ times
[ [] swap behead
swap witheach
[ tuck dip [ - join ] ]
drop ] ] is f-diff ( [ n --> [ )
' [ 90 47 58 29 22 32 55 5 55 73 ]
dup size times
[ dup i^
dup echo say ": "
f-diff echo cr ]
drop |
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... | #R | R | forwarddif <- function(a, n) {
if ( n == 1 )
a[2:length(a)] - a[1:length(a)-1]
else {
r <- forwarddif(a, 1)
forwarddif(r, n-1)
}
}
fdiff <- function(a, n) {
r <- a
for(i in 1:n) {
r <- r[2:length(r)] - r[1:length(r)-1]
}
r
}
v <- c(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)
print(forward... |
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.
| #Visual_Basic | Visual Basic |
Debug.Print Format$(7.125, "00000.000")
|
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.
| #Wren | Wren | import "/fmt" for Fmt
var n = 7.125
System.print(Fmt.rjust(9, n, "0")) |
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 ... | #Ring | Ring |
###---------------------------
# Program: 4 Bit Adder - Ring
# Author: Bert Mariani
# Date: 2018-02-28
#
# Bit Adder: Input A B Cin
# Output S Cout
#
# A ^ B => axb XOR gate
# axb ^ C => Sout XOR gate
# axb & C => d AND gate
#
# A & B => anb ... |
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... | #Phix | Phix | with javascript_semantics
function median(sequence tbl, integer lo, hi)
integer l = hi-lo+1
integer m = lo+floor(l/2)
if remainder(l,2)=1 then
return tbl[m]
end if
return (tbl[m-1]+tbl[m])/2
end function
function fivenum(sequence tbl)
tbl = sort(deep_copy(tbl))
integer l = length(t... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #AWK | AWK | {
split($1,a,"");
for (i=1;i<=4;++i) {
t[i,a[i]]++;
}
}
END {
for (k in t) {
split(k,a,SUBSEP)
for (l in t) {
split(l, b, SUBSEP)
if (a[1] == b[1] && t[k] < t[l]) {
s[a[1]] = a[2]
break
}
}
}
print s[1]s[2]s[3]s[4]
} |
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... | #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class lastSunday
{
public:
l... |
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) .
| #D | D | import std.stdio;
struct Point {
real x, y;
void toString(scope void delegate(const(char)[]) sink) const {
import std.format;
sink("{");
sink.formattedWrite!"%f"(x);
sink(", ");
sink.formattedWrite!"%f"(y);
sink("}");
}
}
struct Line {
Point s, e;
}
... |
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 ... | #F.23 | F# | open System
type Vector(x : double, y : double, z : double) =
member this.x = x
member this.y = y
member this.z = z
static member (-) (lhs : Vector, rhs : Vector) =
Vector(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
static member (*) (lhs : Vector, rhs : double) =
Vector(lhs.x * r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.