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/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 ... | #RATFOR | RATFOR | #
# Floyd-Warshall algorithm.
#
# See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
#
#
# A C programmer might take note that the most rapid stride in an
# array is on the *leftmost* index, rather than the *rightmost* as in
# C.
#
# (In other words, Fortran has "column-m... |
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 ... | #VBScript | VBScript | function multiply( multiplicand, multiplier )
multiply = multiplicand * multiplier
end function |
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 ... | #Visual_Basic | Visual Basic |
Function multiply(a As Integer, b As Integer) As Integer
multiply = a * b
End Function
|
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Scala | Scala | def fdiff(xs: List[Int]) = (xs.tail, xs).zipped.map(_ - _)
def fdiffn(i: Int, xs: List[Int]): List[Int] = if (i == 1) fdiff(xs) else fdiffn(i - 1, fdiff(xs)) |
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... | #Scheme | Scheme | (define (forward-diff lst)
(if (or (null? lst) (null? (cdr lst)))
'()
(cons (- (cadr lst) (car lst))
(forward-diff (cdr lst)))))
(define (nth-forward-diff n xs)
(if (= n 0)
xs
(nth-forward-diff (- n 1)
(forward-diff xs)))) |
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 ... | #Scala | Scala | object FourBitAdder {
type Nibble=(Boolean, Boolean, Boolean, Boolean)
def xor(a:Boolean, b:Boolean)=(!a)&&b || a&&(!b)
def halfAdder(a:Boolean, b:Boolean)={
val s=xor(a,b)
val c=a && b
(s, c)
}
def fullAdder(a:Boolean, b:Boolean, cIn:Boolean)={
val (s1, c1)=halfAdder(a, cIn... |
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... | #Relation | Relation |
program fivenum(X)
rename X^ x
order x 1
dup
project x min, x median, x max, x count
set q1 = x_count / 4
set q1min = floor(q1)
set q1weight = q1 - q1min
set q3 = x_count * 3 / 4
set q3min = floor(q3)
set q3weight = q3 - q3min
swap
dup
select rownumber = q1min + 1 or rownumber = q1min + 2
extend w = q1weight * (rownu... |
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... | #REXX | REXX | /*REXX program computes the five─number summary (LO─value, p25, medium, p75, HI─value).*/
parse arg x
if x='' then x= 15 6 42 41 7 36 49 40 39 47 43 /*Not specified? Then use the defaults*/
say 'input numbers: ' space(x) /*display the original list of numbers.*/
call 5num ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace MissingPermutation
{
class Program
{
static void Main()
{
string[] given = new string[] { "ABCD", "CABD", "ACDB", "DACB",
"BCDA", "ACBD", "ADCB", "CDAB",
... |
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... | #D | D | void lastSundays(in uint year) {
import std.stdio, std.datetime;
foreach (immutable month; 1 .. 13) {
auto date = Date(year, month, 1);
date.day(date.daysInMonth);
date.roll!"days"(-(date.dayOfWeek + 7) % 7);
date.writeln;
}
}
void main() {
lastSundays(2013);
} |
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #Frink | Frink | lineIntersection[x1, y1, x2, y2, x3, y3, x4, y4] :=
{
det = (x1 - x2)(y3 - y4) - (y1 - y2)(x3 - x4)
if det == 0
return undef
t1 = (x1 y2 - y1 x2)
t2 = (x3 y4 - y3 x4)
px = (t1 (x3 - x4) - t2 (x1 - x2)) / det
py = (t1 (y3 - y4) - t2 (y1 - y2)) / det
return [px, py]
}
println[lineIntersecti... |
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) .
| #Go | Go |
package main
import (
"fmt"
"errors"
)
type Point struct {
x float64
y float64
}
type Line struct {
slope float64
yint float64
}
func CreateLine (a, b Point) Line {
slope := (b.y-a.y) / (b.x-a.x)
yint := a.y - slope*a.x
return Line{slope, yint}
}
func EvalX (l Line, x float64) float64 {
return l.... |
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 ... | #Haskell | Haskell | import Control.Applicative (liftA2)
import Text.Printf (printf)
data V3 a = V3 a a a
deriving Show
instance Functor V3 where
fmap f (V3 a b c) = V3 (f a) (f b) (f c)
instance Applicative V3 where
pure a = V3 a a a
V3 a b c <*> V3 d e f = V3 (a d) (b e) (c f)
instance Num a => Num (V3 a) where
... |
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)
... | #APL | APL | ⎕IO←0
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]
|
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... | #ERRE | ERRE |
PROGRAM FIVE_WEEKENDS
DIM M$[12]
PROCEDURE MODULO(X,Y->MD)
IF Y=0 THEN
MD=X
ELSE
MD=X-Y*INT(X/Y)
END IF
END PROCEDURE
PROCEDURE WD(M,D,Y->RES%)
IF M=1 OR M=2 THEN
M+=12
Y-=1
END IF
MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES)
RES%=RES+1.0
END PROCEDUR... |
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... | #Euphoria | Euphoria |
--Five Weekend task from Rosetta Code wiki
--User:Lnettnay
include std/datetime.e
atom numbermonths = 0
sequence longmonths = {1, 3, 5, 7, 8, 10, 12}
sequence yearsmonths = {}
atom none = 0
datetime dt
for year = 1900 to 2100 do
atom flag = 0
for month = 1 to length(longmonths) do
dt = new(year, longmonths... |
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 ... | #REXX | REXX | /*REXX program finds/displays the first perfect square with N unique digits in base N.*/
numeric digits 40 /*ensure enough decimal digits for a #.*/
parse arg LO HI . /*obtain optional argument from the CL.*/
if LO=='' then do; LO=2; HI=16; en... |
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... | #F.23 | F# | open System
let cube x = x ** 3.0
let croot x = x ** (1.0/3.0)
let funclist = [Math.Sin; Math.Cos; cube]
let funclisti = [Math.Asin; Math.Acos; croot]
let composed = List.map2 (<<) funclist funclisti
let main() = for f in composed do printfn "%f" (f 0.5)
main() |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Factor | Factor | USING: assocs combinators kernel math.functions prettyprint sequences ;
IN: rosettacode.first-class-functions
CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] }
CONSTANT: B { [ asin ] [ acos ] [ 1/3 ^ ] }
: compose-all ( seq1 seq2 -- seq ) [ compose ] 2map ;
: test-fcf ( -- )
0.5 A B compose-all
[ call( x -- y ) ] ... |
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... | #Nim | Nim | import random, os, sequtils, strutils
randomize()
type State {.pure.} = enum Empty, Tree, Fire
const
Disp: array[State, string] = [" ", "\e[32m/\\\e[m", "\e[07;31m/\\\e[m"]
TreeProb = 0.01
BurnProb = 0.001
proc chance(prob: float): bool {.inline.} = rand(1.0) < prob
# Set the size
var w, h: int
if para... |
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
| #Factor | Factor | USE: sequences.deep
( scratchpad ) { { 1 } 2 { { 3 4 } 5 } { { { } } } { { { 6 } } } 7 8 { } } 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 ... | #Wren | Wren | import "random" for Random
import "/ioutil" for Input
import "/str" for Str
var rand = Random.new()
var target = List.filled(3, null)
var board = List.filled(3, null)
for (i in 0..2) {
target[i] = List.filled(3, 0)
board[i] = List.filled(3, 0)
for (j in 0..2) target[i][j] = rand.int(2)
}
var flipRow =... |
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... | #Wren | Wren | import "/fmt" for Fmt
var multiplier = Fn.new { |n1, n2| Fn.new { |m| n1 * n2 * m } }
var orderedCollection = Fn.new {
var x = 2.0
var xi = 0.5
var y = 4.0
var yi = 0.25
var z = x + y
var zi = 1.0 / ( x + y )
return [[x, y, z], [xi, yi, zi]]
}
var oc = orderedCollection.call()
for (... |
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... | #zkl | zkl | var x=2.0, y=4.0, z=(x+y), c=T(x,y,z).apply(fcn(n){ T(n,1.0/n) });
//-->L(L(2,0.5),L(4,0.25),L(6,0.166667)) |
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... | #Yabasic | Yabasic |
gosub subrutina
label bucle
print "Bucle infinito"
goto bucle
end
label subrutina
print "En subrutina"
wait 10
return
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... | #Z80_Assembly | Z80 Assembly | PrintString:
ld a,(hl) ;HL is our pointer to the string we want to print
cp 0 ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read.
ret z ;return if accumulator = zero
call PrintChar ;prints accumulator's ascii code to screen - on Amstrad CPC f... |
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... | #JavaScript | JavaScript | (function () {
'use strict';
// FLOYD's TRIANGLE -------------------------------------------------------
// floyd :: Int -> [[Int]]
function floyd(n) {
return snd(mapAccumL(function (start, row) {
return [start + row + 1, enumFromTo(start, start + row)];
}, 1, enumFromTo(... |
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 ... | #REXX | REXX | /*REXX program uses Floyd─Warshall algorithm to find shortest distance between vertices.*/
v= 4 /*███ {1} ███*/ /*number of vertices in weighted graph.*/
@.= 99999999 /*███ 4 / \ -2 ███*/ /*the default distance (edge weight). */
@.1.3= -2 /*███ / 3 \ ███*/ ... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function |
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 ... | #Wart | Wart | def (multiply a b)
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array integer: forwardDifference (in array integer: data) is func
result
var array integer: diffResult is 0 times 0;
local
var integer: index is 0;
begin
for index range 1 to pred(length(data)) do
diffResult &:= -data[index] + data[succ(index)];
end for... |
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... | #SequenceL | SequenceL |
forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]);
forwardDifferenceHelper(x(1), n, result(2)) :=
let
difference := tail(x) - x[1 ... size(x) - 1];
in
result when n = 0 or size(x) = 1 else
forwardDifferenceHelper(difference, n - 1, result ++ [difference]);
|
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 ... | #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 60)) ;; for logical bits
;; Returns a list of bits: '(sum carry)
(define (half-adder a b)
(list (bitwise-xor a b) (bitwise-and a b)))
;; Returns a list of bits: '(sum carry)
(define (full-adder a b c-in)
(let* ((h1 (half-adder c-in a))
(... |
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... | #Ring | Ring |
rem1 = 0
rem2 = 0
rem3 = 0
rem4 = 0
rem5 = 0
fn1 = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]
fn2 = [36, 40, 7, 39, 41, 15]
fn3 = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,
0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,
0.63905160, 0.61501527, -0.98983780, -1.00447874, -... |
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... | #Ruby | Ruby | def fivenum(array)
sorted_arr = array.sort
n = array.size
n4 = (((n + 3).to_f / 2.to_f) / 2.to_f).floor
d = Array.[](1, n4, ((n.to_f + 1) / 2).to_i, n + 1 - n4, n)
sum_array = []
(0..4).each do |e| # each loops have local scope, for loops don't
index_floor = (d[e] - 1).floor
index_ceil = (d[e] - 1)... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #C.2B.2B | C++ | #include <algorithm>
#include <vector>
#include <set>
#include <iterator>
#include <iostream>
#include <string>
static const std::string GivenPermutations[] = {
"ABCD","CABD","ACDB","DACB",
"BCDA","ACBD","ADCB","CDAB",
"DABC","BCAD","CADB","CDBA",
"CBAD","ABDC","ADBC","BDCA",
"DCBA","BACD","BADC","BDAC",
... |
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... | #Delphi | Delphi |
program Find_the_last_Sunday_of_each_month;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.DateUtils;
// ADayOfWeek -> sunday is the first day and is 1
function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>;
var
month: word;
daysOffset: Integer;
date: TDatetime;
begin
if (ADa... |
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) .
| #Groovy | Groovy | class Intersection {
private static class Point {
double x, y
Point(double x, double y) {
this.x = x
this.y = y
}
@Override
String toString() {
return "($x, $y)"
}
}
private static class 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 ... | #J | J | mp=: +/ .* NB. matrix product
p=: mp&{: %~ -~&{. mp {:@] NB. solve
intersectLinePlane=: [ +/@:* 1 , p NB. substitute |
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 ... | #Java | Java | public class LinePlaneIntersection {
private static class Vector3D {
private double x, y, z;
Vector3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector3D plus(Vector3D v) {
return new Vector3D(x + v.x, y +... |
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)
... | #AppleScript | AppleScript | property outputText: ""
repeat with i from 1 to 100
if i mod 15 = 0 then
set outputText to outputText & "FizzBuzz"
else if i mod 3 = 0 then
set outputText to outputText & "Fizz"
else if i mod 5 = 0 then
set outputText to outputText & "Buzz"
else
set outputText to outputText & i
end if
set ou... |
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... | #F.23 | F# | open System
[<EntryPoint>]
let main argv =
let (yearFrom, yearTo) = (1900, 2100)
let monthsWith5We year =
[1; 3; 5; 7; 8; 10; 12] |>
List.filter (fun month -> DateTime(year, month, 1).DayOfWeek = DayOfWeek.Friday)
let ym5we =
[yearFrom .. yearTo]
|> List.map (fun 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 ... | #Ring | Ring |
basePlus = []
decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
see "working..." + nl
for base = 2 to 10
for n = 1 to 40000
basePlus = []
nrPow = pow(n,2)
str = decimaltobase(nrPow,base)
ln = len(str)
for m = 1 to ln... |
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 ... | #Ruby | Ruby | DIGITS = "1023456789abcdefghijklmnopqrstuvwxyz"
2.upto(16) do |n|
start = Integer.sqrt( DIGITS[0,n].to_i(n) )
res = start.step.detect{|i| (i*i).digits(n).uniq.size == n }
puts "Base %2d:%10s² = %-14s" % [n, res.to_s(n), (res*res).to_s(n)]
end
|
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Fantom | Fantom |
class FirstClassFns
{
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
{
return |Obj x -> Obj| { fn2 (fn1 (x)) }
}
public static Void main ()
{
cube := |Float a -> Float| { a * a * a }
cbrt := |Float a -> Float| { a.pow(1/3f) }
|Float->Float|[] fns := [Float#sin.func, Fl... |
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... | #Forth | Forth | : compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
r> compile,
postpone ;
;
: cube fdup fdup f* f* ;
: cuberoot 1e 3e f/ f** ;
: table create does> swap cells + @ ;
table fn ' fsin , ' fcos , ' cube ,
table inverse ' fasin , ' facos , ' cuberoot ,
: main
3 0 do
i fn i invers... |
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... | #OCaml | OCaml | open Curses
let ignite_prob = 0.02
let sprout_prob = 0.01
type cell = Empty | Burning | Tree
let get w x y =
try w.(x).(y)
with Invalid_argument _ -> Empty
let neighborhood_burning w x y =
try
for _x = pred x to succ x do
for _y = pred y to succ y do
if get w _x _y = Burning then raise E... |
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
| #Fantom | Fantom |
class Main
{
// uses recursion to flatten a list
static List myflatten (List items)
{
List result := [,]
items.each |item|
{
if (item is List)
result.addAll (myflatten(item))
else
result.add (item)
}
return result
}
public static Void main ()
{
List s... |
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... | #zkl | zkl | continue; continue(n); // continue nth nested loop
break; break(n); // break out of nth nested loop
try{ ... }catch(exception){ ... } [else{ ... }]
onExit(fcn); // run fcn when enclosing function exits |
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... | #jq | jq | # floyd(n) creates an n-row floyd's triangle
def floyd(n):
def lpad(len): tostring | (((len - length) * " ") + .);
# Construct an array of widths.
# Assuming N is the last integer on the last row (i.e. (n+1)*n/2),
# the last row has n entries from (1+N-n) through N:
def widths:
((n+1)*n/2) as $N
| ... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Julia | Julia | function floydtriangle(rows)
r = collect(1:div(rows *(rows + 1), 2))
for i in 1:rows
for j in 1:i
print(rpad(lpad(popfirst!(r), j > 8 ? 3 : 2), j > 8 ? 4 : 3))
end
println()
end
end
floydtriangle(5); println(); floydtriangle(14)
|
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Ruby | Ruby | def floyd_warshall(n, edge)
dist = Array.new(n){|i| Array.new(n){|j| i==j ? 0 : Float::INFINITY}}
nxt = Array.new(n){Array.new(n)}
edge.each do |u,v,w|
dist[u-1][v-1] = w
nxt[u-1][v-1] = v-1
end
n.times do |k|
n.times do |i|
n.times do |j|
if dist[i][j] > dist[i][k] + dist[k][j]
... |
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 ... | #WebAssembly | WebAssembly | (func $multipy (param $a i32) (param $b i32) (result i32)
local.get $a
local.get $b
i32.mul
)
|
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 ... | #Wren | Wren | var multiply = Fn.new { |a, b| a * b }
System.print(multiply.call(3, 7))
System.print(multiply.call("abc", 3))
System.print(multiply.call([1], 5))
System.print(multiply.call(true, false)) |
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... | #Sidef | Sidef | func dif(arr) {
gather {
for i (0 ..^ arr.end) {
take(arr[i+1] - arr[i])
}
}
}
func difn(n, arr) {
{ arr = dif(arr) } * n
arr
}
say dif([1, 23, 45, 678]) # => [22, 22, 633]
say difn(2, [1, 23, 45, 678]) # => [0, 611] |
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 ... | #Sed | Sed |
#!/bin/sed -f
# (C) 2005,2014 by Mariusz Woloszyn :)
# https://en.wikipedia.org/wiki/Adder_(electronics)
##############################
# PURE SED BINARY FULL ADDER #
##############################
# Input two lines, sanitize input
N
s/ //g
/^[01 ]\+\n[01 ]\+$/! {
i\
ERROR: WRONG INPUT DATA
d
q
}
s/[ ]//... |
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... | #Rust | Rust |
#[derive(Debug)]
struct FiveNum {
minimum: f64,
lower_quartile: f64,
median: f64,
upper_quartile: f64,
maximum: f64,
}
fn median(samples: &[f64]) -> f64 {
// input is already sorted
let n = samples.len();
let m = n / 2;
if n % 2 == 0 {
(samples[m] + samples[m - 1]) / 2.0
... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #SAS | SAS | /* build a dataset */
data test;
do i=1 to 10000;
x=rannor(12345);
output;
end;
keep x;
run;
/* compute the five numbers */
proc means data=test min p25 median p75 max;
var x;
run; |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Clojure | Clojure |
(use 'clojure.math.combinatorics)
(use 'clojure.set)
(def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" )))
(def s1 (apply hash-set (permutations "ABCD")))
(def missing (difference s1 given))
|
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... | #Elixir | Elixir | defmodule RC do
def lastSunday(year) do
Enum.map(1..12, fn month ->
lastday = :calendar.last_day_of_the_month(year, month)
daynum = :calendar.day_of_the_week(year, month, lastday)
sunday = lastday - rem(daynum, 7)
{year, month, sunday}
end)
end
end
y = String.to_integer(hd(System... |
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... | #Emacs_Lisp | Emacs Lisp | (require 'calendar)
(defun last-sunday (year)
"Print the last Sunday in each month of year"
(mapcar (lambda (month)
(let*
((days (number-sequence 1 (calendar-last-day-of-month month year)))
(mdy (mapcar (lambda (x) (list month x year)) days))
(weekdays (mapcar #'calendar-day-of-week mdy))
... |
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) .
| #Haskell | Haskell | type Line = (Point, Point)
type Point = (Float, Float)
intersection :: Line -> Line -> Either String Point
intersection ab pq =
case determinant of
0 -> Left "(Parallel lines – no intersection)"
_ ->
let [abD, pqD] = (\(a, b) -> diff ([fst, snd] <*> [a, b])) <$> [ab, pq]
[ix, iy] =
... |
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 ... | #jq | jq | # add as many as you please
def addVector:
transpose | add;
# . - y
def minusVector(y):
[.[0] - y[0], .[1] - y[1], .[2] - y[2]];
# scalar multiplication: . * s
def multVector(s):
map(. * s);
def dot(y):
.[0] * y[0] + .[1] * y[1] + .[2] * y[2];
def intersectPoint($rayVector; $rayPoint; $planeNormal; $p... |
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 ... | #Julia | Julia | function lineplanecollision(planenorm::Vector, planepnt::Vector, raydir::Vector, raypnt::Vector)
ndotu = dot(planenorm, raydir)
if ndotu ≈ 0 error("no intersection or line is within plane") end
w = raypnt - planepnt
si = -dot(planenorm, w) / ndotu
ψ = w .+ si .* raydir .+ planepnt
return ψ
e... |
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)
... | #Applesoft_BASIC | Applesoft BASIC | fizzbuzz():
for x in [1..100]
if x%5==0 and x%3==0
return "FizzBuzz"
else
if x%3==0
return "Fizz"
else
if x%5==0
return "Buzz"
else
return x
main():
fizzbuzz() -> io |
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... | #Factor | Factor | USING: calendar calendar.format formatting io kernel math
sequences ;
: timestamps>my ( months -- )
[ { MONTH bl YYYY nl } formatted 2drop ] each ;
: month-range ( start-year #months -- seq )
[ <year> ] [ <iota> ] bi* [ months time+ ] with map ;
: find-five-weekend-months ( months -- months' )
[ [ frid... |
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 ... | #Sidef | Sidef | func first_square(b) {
var start = [1, 0, (2..^b)...].flip.map_kv{|k,v| v * b**k }.sum.isqrt
start..Inf -> first_by {|k|
k.sqr.digits(b).freq.len == b
}.sqr
}
for b in (2..16) {
var s = first_square(b)
printf("Base %2d: %10s² == %s\n", b, s.isqrt.base(b), s.base(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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "crt/math.bi" '' include math functions in C runtime library
' Declare function pointer type
' This implicitly assumes default StdCall calling convention on Windows
Type Class2Func As Function(As Double) As Double
' A couple of functions with the above prototype
Function functionA(v ... |
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... | #Ol | Ol |
(import (lib gl))
(import (otus random!))
(define WIDTH 170)
(define HEIGHT 96)
; probabilities
(define p 20)
(define f 1000)
(gl:set-window-title "Drossel and Schwabl 'forest-fire'")
(import (OpenGL version-1-0))
(glShadeModel GL_SMOOTH)
(glClearColor 0.11 0.11 0.11 1)
(glOrtho 0 WIDTH 0 HEIGHT 0 1)... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Forth | Forth | include FMS-SI.f
include FMS-SILib.f
: flatten {: list1 list2 -- :}
list1 size: 0 ?do i list1 at:
dup is-a object-list2
if list2 recurse else list2 add: then loop ;
object-list2 list
o{ o{ 1 } 2 o{ o{ 3 4 } 5 } o{ o{ o{ } } } o{ o{ o{ 6 } } } 7 8 o{ } }
list flatten
list p... |
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... | #Kotlin | Kotlin | fun main(args: Array<String>) = args.forEach { Triangle(it.toInt()) }
internal class Triangle(n: Int) {
init {
println("$n rows:")
var printMe = 1
var printed = 0
var row = 1
while (row <= n) {
val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).to... |
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 ... | #Rust | Rust | pub type Edge = (usize, usize);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Graph<T> {
size: usize,
edges: Vec<Option<T>>,
}
impl<T> Graph<T> {
pub fn new(size: usize) -> Self {
Self {
size,
edges: std::iter::repeat_with(|| None).take(size * size).collect(),
... |
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 ... | #X86_Assembly | X86 Assembly | .text
.globl multiply
.type multiply,@function
multiply:
movl 4(%esp), %eax
mull 8(%esp)
ret |
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 ... | #XBS | XBS | func multiply(a,b){
send 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... | #Slate | Slate | s@(Sequence traits) forwardDifference
[
s allButFirst with: s allButLast collect: #- `er
].
s@(Sequence traits) forwardDifference
"Without creating two intermediate throwaway Sequences."
[
result ::= s allButFirst.
result doWithIndex: [| :nextValue :index | result at: index infect: [| :oldValue | oldValue - (s ... |
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... | #Smalltalk | Smalltalk | Array extend [
difference [
^self allButFirst with: self allButLast collect: [ :a :b | a - b ]
]
nthOrderDifference: n [
^(1 to: n) inject: self into: [ :old :unused | old difference ]
]
]
s := #(90 47 58 29 22 32 55 5 55 73)
1 to: s size - 1 do: [ :i |
(s nthOrderDifference: i) ... |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Sidef | Sidef | func bxor(a, b) {
(~a & b) | (a & ~b)
}
func half_adder(a, b) {
return (bxor(a, b), a & b)
}
func full_adder(a, b, c) {
var (s1, c1) = half_adder(a, c)
var (s2, c2) = half_adder(s1, b)
return (s2, c1 | c2)
}
func four_bit_adder(a, b) {
var (s0, c0) = full_adder(a[0], b[0], 0)
var (s1, c1) = full_add... |
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... | #Scala | Scala | import java.util
object Fivenum extends App {
val xl = Array(
Array(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0),
Array(36.0, 40.0, 7.0, 39.0, 41.0, 15.0),
Array(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,
-0.03035726, 1.46675970, -0.74621349, -0.7... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #CoffeeScript | CoffeeScript |
missing_permutation = (arr) ->
# Find the missing permutation in an array of N! - 1 permutations.
# We won't validate every precondition, but we do have some basic
# guards.
if arr.length == 0
throw Error "Need more data"
if arr.length == 1
return [arr[0][1] + arr[0][0]]
# Now we know that f... |
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... | #Erlang | Erlang |
-module(last_sundays).
-export([in_year/1]).
% calculate all the last sundays in a particular year
in_year(Year) ->
[lastday(Year, Month, 7) || Month <- lists:seq(1, 12)].
% calculate the date of the last occurrence of a particular weekday
lastday(Year, Month, WeekDay) ->
Ldm = calendar:last_day_of_the_... |
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) .
| #J | J | det=: -/ .* NB. calculate determinant
findIntersection=: (det ,."1 [: |: -/"2) %&det -/"2 |
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) .
| #Java | Java | public class Intersection {
private static class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("{%f, %f}", x, y);
}
}
private stati... |
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 ... | #Kotlin | Kotlin | // version 1.1.51
class Vector3D(val x: Double, val y: Double, val z: Double) {
operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)
operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)
operator fun times(s: Double) = Vector3D(s * x, s * y, s * z)
infix fun dot... |
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)
... | #Arbre | Arbre | fizzbuzz():
for x in [1..100]
if x%5==0 and x%3==0
return "FizzBuzz"
else
if x%3==0
return "Fizz"
else
if x%5==0
return "Buzz"
else
return x
main():
fizzbuzz() -> io |
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... | #Fortran | Fortran | program Five_weekends
implicit none
integer :: m, year, nfives = 0, not5 = 0
logical :: no5weekend
type month
integer :: n
character(3) :: name
end type month
type(month) :: month31(7)
month31(1) = month(13, "Jan")
month31(2) = month(3, "Mar")
month31(3) = month(5, "May")
month31(4... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Program
Dim base, bm1 As Byte, hs As New HashSet(Of Byte), st0 As DateTime
Const chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"
' converts base10 to string, using current base
Function toStr(ByVal b As BigInteger) As String
... |
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... | #GAP | GAP | # Function composition
Composition := function(f, g)
local h;
h := function(x)
return f(g(x));
end;
return h;
end;
# Apply each function in list u, to argument x
ApplyList := function(u, x)
local i, n, v;
n := Size(u);
v := [ ];
for i in [1 .. n] do
v[i] := u[i](x);
od;
return v;
end;
# ... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Go | Go | package main
import "math"
import "fmt"
// user-defined function, per task. Other math functions used are built-in.
func cube(x float64) float64 { return math.Pow(x, 3) }
// ffType and compose function taken from Function composition task
type ffType func(float64) float64
func compose(f, g ffType) ffType {
... |
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... | #PARI.2FGP | PARI/GP | step(M,p,f)={
my(m=matsize(M)[1],n=matsize(M)[2]);
matrix(m,n,i,j,
if(M[i,j]=="*",
" "
,
if(M[i,j]=="t",
my(nbr="t");
for(x=max(1,i-1),min(m,i+1),
for(y=max(1,j-1),min(n,j+1),
if(M[x,y]=="*",nbr="*";break(2))
)
);
if(random(1.)<f,"*",nbr)
,
if(random(1.)<p,"t"," ")
... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Fortran | Fortran |
! input : [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
! flatten : [1, 2, 3, 4, 5, 6, 7, 8 ]
module flat
implicit none
type n
integer :: a
type(n), dimension(:), pointer :: p => null()
logical :: empty = .false.
end type
con... |
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... | #Lasso | Lasso | define floyds_triangle(n::integer) => {
local(out = array(array(1)),comp = array, num = 1)
while(#out->size < #n) => {
local(new = array)
loop(#out->last->size + 1) => {
#num++
#new->insert(#num)
}
#out->insert(#new)
}
local(pad = #out->last->last->asString->size)
with line in #out do => {
local(li... |
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... | #Liberty_BASIC | Liberty BASIC | input "Number of rows needed:- "; rowsNeeded
dim colWidth(rowsNeeded) ' 5 rows implies 5 columns
for col=1 to rowsNeeded
colWidth(col) = len(str$(col + rowsNeeded*(rowsNeeded-1)/2))
next
currentNumber =1
for row=1 to rowsNeeded
for col=1 to row
print right$( " "+str$( currentNumber), colW... |
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 ... | #Scheme | Scheme | ;;; Floyd-Warshall algorithm.
;;;
;;; See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
;;;
(import (scheme base))
(import (scheme cxr))
(import (scheme write))
;;;
;;; A square array will be represented by a cons-pair:
;;;
;;; (vector-of-length n-squared . n)
;;;
;... |
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 ... | #XLISP | XLISP | (defun multiply (x y)
(* x y)) |
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 ... | #Xojo | Xojo | Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #SQL | SQL | WITH RECURSIVE
T0 (N, ITEM, LIST, NEW_LIST) AS
(
SELECT 1,
NULL,
'90,47,58,29,22,32,55,5,55,73' || ',',
NULL
UNION ALL
SELECT CASE
WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''
THEN N + 1
ELSE N
END,
... |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Swift | Swift | typealias FourBit = (Int, Int, Int, Int)
func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) {
return (a ^ b, a & b)
}
func fullAdder(_ a: Int, _ b: Int, carry: Int) -> (Int, Int) {
let (s0, c0) = halfAdder(a, b)
let (s1, c1) = halfAdder(s0, carry)
return (s1, c0 | c1)
}
func fourBitAdder(_ a: FourBit, _ b... |
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... | #Sidef | Sidef | func fourths(e) {
var t = ((e>>1) / 2)
[0, t, e/2, e - t, e]
}
func fivenum(nums) {
var x = nums.sort
var d = fourths(x.end)
([x[d.map{.floor}]] ~Z+ [x[d.map{.ceil}]]) »/» 2
}
var nums = [
[15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43],
[36, 40, 7, 39, 41, 15], [
0.14082834, 0.0974879... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Common_Lisp | Common Lisp | (defparameter *permutations*
'("ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
"CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"))
(defun missing-perm (perms)
(let* ((letters (loop for i across (car perms) collecting i))
(l (/ (1+ (length 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... | #Excel | Excel | lastSundayOfEachMonth
=LAMBDA(y,
LAMBDA(monthEnd,
1 + monthEnd - WEEKDAY(monthEnd)
)(
EDATE(
DATEVALUE(y & "-01-31"),
SEQUENCE(12, 1, 0, 1)
)
)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.