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/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #J | J | isLeap=: 0 -/@:= 4 100 400 |/ ] |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Java | Java | import java.util.GregorianCalendar;
import java.text.MessageFormat;
public class Leapyear{
public static void main(String[] argv){
int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
GregorianCalendar cal = new GregorianCalendar();
for(int year : yrs){
... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "FRFLLFRF" ] is F ( $ --> $ )
[ $ "L" ] is L ( $ --> $ )
[ $ "R" ] is R ( $ --> $ )
$ "FLLFLLF"
... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Racket | Racket | #lang racket
(require metapict)
; rot: rotate d degrees around point p, where c is a point or curve
(def (rot d p c)
(rotated-aboutd d p c))
(define (koch a b n)
(match n
[0 (draw (curve a -- b))]
[_ (def 1/3ab (med 1/3 a b))
(def 2/3ab (med 2/3 a b))
(draw (koch a 1/3ab ... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Ruby | Ruby | def s_of_n_creator(n)
sample = []
i = 0
Proc.new do |item|
i += 1
if i <= n
sample << item
elsif rand(i) < n
sample[rand(n)] = item
end
sample
end
end
frequency = Array.new(10,0)
100_000.times do
s_of_n = s_of_n_creator(3)
sample = nil
(0..9).each {|digit| sample = s_of_n... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Rust | Rust | use rand::{Rng,weak_rng};
struct SofN<R: Rng+Sized, T> {
rng: R,
sample: Vec<T>,
i: usize,
n: usize,
}
impl<R: Rng, T> SofN<R, T> {
fn new(rng: R, n: usize) -> Self {
SofN{rng, sample: Vec::new(), i: 0, n}
}
fn add(&mut self, item: T) {
self.i += 1;
if self.i <=... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #EasyLang | EasyLang | len f[] 100 * 100
func show . .
for y range 100
for x range 100
if f[y * 100 + x] = 1
move x y
rect 1 1
.
.
.
.
func run x y dir . .
dx[] = [ 0 1 0 -1 ]
dy[] = [ -1 0 1 0 ]
while x >= 0 and x < 100 and y >= 0 and y < 100
v = f[y * 100 + x]
f[y * 100 + x] = 1 - v
... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Pike | Pike | array kronecker(array matrix1, array matrix2) {
array final_list = ({});
array sub_list = ({});
int count = sizeof(matrix2);
foreach(matrix1, array elem1) {
int counter = 0;
int check = 0;
while (check < count) {
foreach(elem1, int num1) {
foreach(matrix2[counter], int num2) {
sub_list = Array... |
http://rosettacode.org/wiki/Kronecker_product_based_fractals | Kronecker product based fractals | This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the matrix (filled with 0/1) we ... | #Wren | Wren | import "/matrix" for Matrix
var kroneckerPower = Fn.new { |m, n|
var pow = m.copy()
for (i in 1...n) pow = pow.kronecker(m)
return pow
}
var printMatrix = Fn.new { |text, m|
System.print("%(text) fractal :\n")
for (i in 0...m.numRows) {
for (j in 0...m.numCols) {
System.write... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Groovy | Groovy | def ymd = { it.format('yyyy-MM-dd') }
def lastFridays = lastWeekDays.curry(Day.Fri)
lastFridays(args[0] as int).each { println (ymd(it)) } |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Scala | Scala | object LastLetterFirstLetterNaive extends App {
def solve(names: Set[String]) = {
def extend(solutions: List[List[String]]): List[List[String]] = {
val more = solutions.flatMap{solution =>
val lastLetter = solution.head takeRight 1
(names -- solution).filter(_.take(1) equalsIgnoreCase lastLe... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Oforth | Oforth | : largestInt map(#asString) sortWith(#[ 2dup + -rot swap + > ]) sum asInteger ; |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #PARI.2FGP | PARI/GP | large(v)=eval(concat(apply(n->Str(n),vecsort(v,(x,y)->eval(Str(y,x,"-",x,y))))));
large([1, 34, 3, 98, 9, 76, 45, 4])
large([54, 546, 548, 60]) |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Kotlin | Kotlin | fun main(args: Array<String>) {
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
println(lcm(15, 9))
}
|
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #LabVIEW | LabVIEW | define gcd(a,b) => {
while(#b != 0) => {
local(t = #b)
#b = #a % #b
#a = #t
}
return #a
}
define lcm(m,n) => {
#m == 0 || #n == 0 ? return 0
local(r = (#m * #n) / decimal(gcd(#m, #n)))
return integer(#r)->abs
}
lcm(-6, 14)
lcm(2, 0)
lcm(12, 18)
lcm(12, 22)
lcm(7, 31) |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #Limbo | Limbo | implement Levenshtein;
include "sys.m"; sys: Sys;
print: import sys;
include "draw.m";
Levenshtein: module {
init: fn(nil: ref Draw->Context, args: list of string);
# Export distance so that this module can be used as either a
# standalone program or as a library:
distance: fn(s, t: string): int;
};
init(n... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #J | J | ltrfreq=: 3 : 0
letters=. u: 65 + i.26 NB. upper case letters
<: #/.~ letters (, -. -.~) toupper fread y
) |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Stata | Stata | mata
function rand_bsd(u) {
m = 65536
u1 = floor(u/m)
u2 = mod(u,m)
a1 = 16838
a2 = 20077
b = 12345
u = mod((a1*u2+a2*u1)*m+a2*u2+b,2147483648)
return(u)
}
function rand_ms(u) {
u = mod(214013*u+2531011,2147483648)
return(floor(u/65536))
}
function rand_seq(f,seed,n) {
a = J(n,1,.)
for (i=1; i<=n; i++) ... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Swift | Swift | import Cocoa
class LinearCongruntialGenerator {
var state = 0 //seed of 0 by default
let a, c, m, shift: Int
//we will use microsoft random by default
init() {
self.a = 214013
self.c = 2531011
self.m = Int(pow(2.0, 31.0)) //2^31 or 2147483648
self.shift = 16
}
... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #JavaScript | JavaScript | var isLeapYear = function (year) { return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); }; |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #jq | jq | def leap:
. as $y | ($y%4) == 0 and ($y < 1582 or ($y%400) == 0 or ($y%100) != 0); |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $flake = 'F--F--F' but Lindenmayer( { F => 'F+F--F+F' } );
$flake++ xx 5;
my @points = (50, 440);
for $flake.comb -> $v {
state ($x, $y) = @points[0,1];
... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Scala | Scala | import java.util
import scala.util.Random
object KnuthsAlgorithmS extends App {
import scala.collection.JavaConverters._
val (n, rand, bin) = (3, Random, new Array[Int](10))
for (_ <- 0 until 100000) {
val sample = new util.ArrayList[Int](n)
for (item <- 0 until 10) {
if (item < n) sample.ad... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Sidef | Sidef | func s_of_n_creator(n) {
var i = 0
var sample = []
{ |item|
if (++i <= n) {
sample << item;
}
elsif (i.rand < n) {
sample[n.rand] = item;
}
sample;
}
}
var items = 0..9;
var bin = [];
100000.times {
var s_of_n = s_of_n_creator(3);
... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #EchoLisp | EchoLisp |
(lib 'plot)
(lib 'types)
(define (move iter x dir constant: plane turns cmax width xmax (cidx 0))
(while (> iter 0)
;; get color index of current square
(set! cidx (vector-ref plane x))
;; turn
(if (vector-ref turns cidx)
(set! dir (if (= dir 3) 0 (1+ dir))) ;; right is #t
(set! dir (if (= dir 0) 3... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #PureBasic | PureBasic | EnableExplicit
DataSection
Matrix_A_B_Dimension_Bsp1:
Data.i 2,2,?MatrixA_Werte_Bsp1,2,2,?MatrixB_Werte_Bsp1
Matrix_A_B_Dimension_Bsp2:
Data.i 3,3,?MatrixA_Werte_Bsp2,3,4,?MatrixB_Werte_Bsp2
MatrixA_Werte_Bsp1:
Data.i 1,2,3,4
MatrixA_Werte_Bsp2:
Data.i 0,1,0,1,1,1,0,1,0
MatrixB_Werte_Bsp1:
D... |
http://rosettacode.org/wiki/Kronecker_product_based_fractals | Kronecker product based fractals | This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the matrix (filled with 0/1) we ... | #zkl | zkl | var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
fcn kronecker(A,B){ //--> new Matrix
m,n, p,q := A.rows,A.cols, B.rows,B.cols;
r:=GSL.Matrix(m*p, n*q);
foreach i,j,k,l in (m,n,p,q){ r[p*i + k, q*j + l]=A[i,j]*B[k,l] }
r
}
fcn kfractal(M,n,fname){
R:=M;
do(n){ R=kronecker... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Haskell | Haskell | import Data.Time.Calendar
(Day, addDays, showGregorian, fromGregorian, gregorianMonthLength)
import Data.Time.Calendar.WeekDate (toWeekDate)
import Data.List (transpose, intercalate)
-- [1 .. 7] for [Mon .. Sun]
findWeekDay :: Int -> Day -> Day
findWeekDay dayOfWeek date =
head
(filter
(\x ->
... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
var integer: maxPathLength is 0;
var integer: maxPathLengthCount is 0;
var string: maxPathExample is "";
var array string: names is [] (
"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor",
"carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "dein... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Pascal | Pascal | const
base = 10;
MaxDigitCnt = 11;
source1 : array[0..7] of integer = (1, 34, 3, 98, 9, 76, 45, 4);
source2 : array[0..3] of integer = (54,546,548,60);
source3 : array[0..3] of integer = (60, 54,545454546,0);
type
tdata = record
datOrg,
datMod : LongWord;
datStrOrg ... |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Lasso | Lasso | define gcd(a,b) => {
while(#b != 0) => {
local(t = #b)
#b = #a % #b
#a = #t
}
return #a
}
define lcm(m,n) => {
#m == 0 || #n == 0 ? return 0
local(r = (#m * #n) / decimal(gcd(#m, #n)))
return integer(#r)->abs
}
lcm(-6, 14)
lcm(2, 0)
lcm(12, 18)
lcm(12, 22)
lcm(7, 31) |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #LiveCode | LiveCode |
//Code By Neurox66
function Levenshtein pString1 pString2
put 0 into tPosChar1
repeat for each char tChar1 in pString1
add 1 to tPosChar1
put tPosChar1 into tDistance[tPosChar1][0]
put 0 into tPosChar2
repeat for each char tChar2 in pString2
add 1 to tPosChar2
put ... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Tcl | Tcl | package require Tcl 8.6
# General form of a linear-congruential RNG
oo::class create LCRNG {
variable seed A B C D
constructor {init a b c d} {
if {$init < 1} {set init [clock clicks]}
variable seed $init A $a B $b C $c D $d
}
method rand {} {
set seed [expr {($A * $seed + $B) % $C}]
return [expr ... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Julia | Julia | isleap(yr::Integer) = yr % 4 == 0 && (yr < 1582 || yr % 400 == 0 || yr % 100 != 0)
@assert all(isleap, [2400, 2012, 2000, 1600, 1500, 1400])
@assert !any(isleap, [2100, 2014, 1900, 1800, 1700, 1499]) |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Ring | Ring |
# Project : Koch curve
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Koch curve")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Ruby | Ruby |
attr_reader :koch
def settings
size 600, 600
end
def setup
sketch_title '2D Koch'
@koch = KochSnowflake.new
koch.create_grammar 5
no_loop
end
def draw
background 0
koch.render
end
# LSystem class
class Grammar
attr_reader :axiom, :rules
def initialize(axiom, rules)
@axiom = axiom
@rule... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Swift | Swift | import Darwin
func s_of_n_creator<T>(n: Int) -> T -> [T] {
var sample = [T]()
var i = 0
return {(item: T) in
i++
if (i <= n) {
sample.append(item)
} else if (Int(arc4random_uniform(UInt32(i))) < n) {
sample[Int(arc4random_uniform(UInt32(n)))] = item
}
return sample
}
}
var b... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Tcl | Tcl | package require Tcl 8.6
oo::class create SofN {
variable items size count
constructor {n} {
set size $n
}
method item {item} {
if {[incr count] <= $size} {
lappend items $item
} elseif {rand()*$count < $size} {
lset items [expr {int($size * rand())}] $item
}
return $items
}
}
# Te... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Ela | Ela | open list core generic
type Field = Field a
type Color = White | Black
type Direction = Lft | Fwd | Rgt | Bwd
field s = Field [[White \\ _ <- [1..s]] \\ _ <- [1..s]]
isBlack Black = true
isBlack _ = false
newfield xc yc (Field xs) = Field (newfield' 0 xs)
where newfield' _ [] = []
newfield' n (x::xs)
... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Python | Python | #!/usr/bin/env python3
# Sample 1
a1 = [[1, 2], [3, 4]]
b1 = [[0, 5], [6, 7]]
# Sample 2
a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
def kronecker(matrix1, matrix2):
final_list = []
sub_list = []
count = len(matrix2)
for elem1 in matrix1:
coun... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every write(lastfridays(!A))
end
procedure lastfridays(year)
every m := 1 to 12 do {
d := case m of {
2 : if IsLeapYear(year) then 29 else 28
4|6|9|11 : 30
default : 31
} # last day of month
z := 0
j := julian(m,d,year) + 1 # ... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Sidef | Sidef | class LLFL(Array words) {
has f = Hash()
method init {
words.each {|w|
var m = w.match(/^(.).*(.)$/)
f{m[0]}{w} = m[1]
}
}
method longest_chain {
var stack = []
var longest = []
func poke(c) {
var h = f{c}
... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Perl | Perl | sub maxnum {
join '', sort { "$b$a" cmp "$a$b" } @_
}
print maxnum(1, 34, 3, 98, 9, 76, 45, 4), "\n";
print maxnum(54, 546, 548, 60), "\n"; |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Liberty_BASIC | Liberty BASIC | print "Least Common Multiple of 12 and 18 is "; LCM(12, 18)
end
function LCM(m, n)
LCM = abs(m * n) / GCD(m, n)
end function
function GCD(a, b)
while b
c = a
a = b
b = c mod b
wend
GCD = abs(a)
end function
|
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Logo | Logo | to abs :n
output sqrt product :n :n
end
to gcd :m :n
output ifelse :n = 0 [ :m ] [ gcd :n modulo :m :n ]
end
to lcm :m :n
output quotient (abs product :m :n) gcd :m :n
end |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #Lobster | Lobster | def levenshtein(s: string, t: string) -> int:
def makeNxM(n: int, m: int, v: int) -> [[int]]:
let d:[[int]] = vector_reserve(typeof return, n)
for(n) i:
push(d, vector_reserve(typeof return, m))
for(m) j:
push(d[i], v)
return d
let ls = s.lengt... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #JavaScript | JavaScript | (function(txt) {
var cs = txt.split(''),
i = cs.length,
dct = {},
c = '',
keys;
while (i--) {
c = cs[i];
dct[c] = (dct[c] || 0) + 1;
}
keys = Object.keys(dct);
keys.sort();
return keys.map(function (c) { return [c, dct[c]]; });
})("Not all... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #uBasic.2F4tH | uBasic/4tH | w = 32 ' Change for different integer size
b = 0 ' Initial BSD seed
m = 0 ' Initial MS seed
Print "BSD" ' Get the first 10 numbers from BSD
For i = 1 To 10
GoSub _randBSD
Print Pop()
Ne... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #UNIX_Shell | UNIX Shell | #! /bin/bash
function BSD() {
SEED=$(((1103515245 * $SEED + 12345) % 2**31))
echo " $SEED"
}
function MS() {
SEED=$(((214013 * $SEED + 2531011) % 2**31))
echo " $(($SEED / 2**16))"
}
function output() {
SEED=0
echo "$1"
for i in {1..10}; do
eval "$1"
done
echo ""
}
output BSD
output ... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #K | K | leapyear:{(+/~x!'4 100 400)!2}
a@&leapyear'a:1900,1994,1996,1997,2000
1996 2000 |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Kotlin | Kotlin | fun isLeapYear(year: Int) = year % 400 == 0 || (year % 100 != 0 && year % 4 == 0) |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
use svg::node::element::path::Data;
use svg::node::element::Path;
use svg::node::element::Rectangle;
const SQRT3_2: f64 = 0.86602540378444;
fn koch_curve(mut data: Data, x0: f64, y0: f64, x1: f64, y1: f64, order: usize) -> Data {
if order == 0 {
data = data.line_to((... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Sidef | Sidef | var rules = Hash(
F => 'F+F--F+F',
)
var lsys = LSystem(
width: 800,
height: 800,
xoff: -210,
yoff: -90,
len: 8,
angle: 60,
color: 'dark green',
)
lsys.execute('F--F--F', 4, "koch_snowflake.png", rules) |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Vlang | Vlang | import rand
import rand.seed
fn s_of_ncreator(n int) fn(u8) []u8 {
mut s := []u8{len: 0, cap:n}
mut m := n
return fn[mut s, mut m, n](item u8) []u8 {
if s.len < n {
s << item
} else {
m++
if rand.intn(m) or {0} < n {
s[rand.intn(n) or {0}] ... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Wren | Wren | import "random" for Random
var r = Random.new()
var sOfNCreator = Fn.new { |n|
var s = List.filled(n, 0)
var next = 0
var m = n
return Fn.new { |item|
if (next < n) {
s[next] = item
next = next + 1
} else {
m = m + 1
if (r.int(m) < n) {... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Elixir | Elixir | defmodule Langtons do
def ant(sizex, sizey) do
{px, py} = {div(sizex,2), div(sizey,2)} # start position
move(MapSet.new, sizex, sizey, px, py, {1,0}, 0)
end
defp move(plane, sx, sy, px, py, _, step) when px<0 or sx<px or py<0 or sy<py, do:
print(plane, sx, sy, px, py, step)
defp move(plane, sx... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #R | R |
## Sample using:
a <- matrix(c(1,1,1,1), ncol=2, nrow=2, byrow=TRUE);
b <- matrix(c(0,1,1,0), ncol=2, nrow=2, byrow=TRUE);
a %x% b
|
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #J | J | require 'dates'
last_fridays=: 12 {. [: ({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1 |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Tcl | Tcl | proc search {path arcs} {
set solutions {}
set c [string index [lindex $path end] end]
set i -1
foreach arc $arcs {
incr i
if {[string index $arc 0] ne $c} continue
set soln [search [concat $path [list $arc]] [lreplace $arcs $i $i]]
lappend solutions [list [llength $soln] $soln]
}
if {[lleng... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Phix | Phix | with javascript_semantics
function catcmp(string a, string b)
return compare(b&a,a&b)
end function
function method2(sequence s)
return join(custom_sort(catcmp,apply(s,sprint)),"")
end function
?method2({1,34,3,98,9,76,45,4})
?method2({54,546,548,60})
|
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Lua | Lua | function gcd( m, n )
while n ~= 0 do
local q = m
m = n
n = q % n
end
return m
end
function lcm( m, n )
return ( m ~= 0 and n ~= 0 ) and m * n / gcd( m, n ) or 0
end
print( lcm(12,18) ) |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #Lua | Lua | function leven(s,t)
if s == '' then return t:len() end
if t == '' then return s:len() end
local s1 = s:sub(2, -1)
local t1 = t:sub(2, -1)
if s:sub(0, 1) == t:sub(0, 1) then
return leven(s1, t1)
end
return 1 + math.min(
leven(s1, t1),
leven(s, t1),
leven... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #jq | jq |
# Input: an array of strings.
# Output: an object with the strings as keys,
# the values of which are the corresponding frequencies.
def counter:
reduce .[] as $item ( {}; .[$item] += 1 ) ;
# For neatness we sort the keys:
explode | map( [.] | implode ) | counter | . as $counter
| keys | sort[] | [., $counter[.]... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #VBA | VBA | Public stateBSD As Variant
Public stateMS As Variant
Private Function bsd() As Long
Dim temp As Variant
temp = CDec(1103515245 * stateBSD + 12345)
temp2 = temp / 2 ^ 31
temp3 = CDec(WorksheetFunction.Floor_Precise(temp2))
stateBSD = temp - (2 ^ 31) * temp3
bsd = stateBSD
End Function
Private Fun... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Lasso | Lasso | define isLeapYear(y::integer) => {
#y % 400 == 0 ? return true
#y % 100 == 0 ? return false
#y % 4 == 0 ? return true
return false
}
with test in array(2012,2016,1933,1900,1999,2000) do => {^
isLeapYear(#test)
'\r'
^} |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Wren | Wren | import "graphics" for Canvas, Color, Point
import "dome" for Window
import "math" for M
class Game {
static init() {
Window.title = "Koch curve"
Canvas.resize(512, 512)
Window.resize(512, 512)
Canvas.cls(Color.white) // white background
koch(100, 100, 400, 400, 4)
k... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #zkl | zkl | fcn s_of_n_creator(n){
fcn(item,ri,N,samples){
i:=ri.inc(); // 1,2,3,4,...
if(i<=N) samples.append(item);
else if ((0).random(i) < N) samples[(0).random(N)] = item;
samples
}.fp1(Ref(1),n,L())
} |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Elm | Elm | import Maybe as M
import Matrix
import Time exposing (Time, every, second)
import List exposing (..)
import String exposing (join)
import Html exposing (div, h1, text)
import Html.App exposing (program)
import Svg
import Svg.Attributes exposing (version, viewBox, cx, cy, r, x, y, x1, y1, x2, y2, fill,style, width, he... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Racket | Racket | #lang typed/racket/base
(require math/array
math/matrix
racket/match)
(define-type (M A) (Matrix A))
(define #:forall (A B C) (general-⊗ [m1 : (M A)] [m2 : (M B)] [× : (A B -> C)]) : (M C)
(match-let* ((`(#(,rs1 ,cs1) . #(,rs2 ,cs2)) (cons (array-shape m1) (array-shape m2)))
(rs... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Raku | Raku | sub kronecker_product ( @a, @b ) {
return (@a X @b).map: { .[0].list X* .[1].list };
}
.say for kronecker_product([ <1 2>, <3 4> ],
[ <0 5>, <6 7> ]);
say '';
.say for kronecker_product([ <0 1 0>, <1 1 1>, <0 1 0> ],
[ <1 1 1 1>, <1 0 0 1>, <1 1 1 1>]);
|
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Java | Java | import java.text.*;
import java.util.*;
public class LastFridays {
public static void main(String[] args) throws Exception {
int year = Integer.parseInt(args[0]);
GregorianCalendar c = new GregorianCalendar(year, 0, 1);
for (String mon : new DateFormatSymbols(Locale.US).getShortMonths(... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Ursala | Ursala | #import std
mon =
~&*~ sep` mat` -[
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon l... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #VBScript | VBScript | ' Last letter-first letter - VBScript - 11/03/2019
names = array( _
"audino", "bagon", "baltoy", "banette", _
"bidoof", "braviary", "bronzor", "carracosta", "charmeleon", _
"cresselia", "croagunk", "darmanitan", "deino", "emboar", _
"emolga", "exeggcute", "gabite", "girafarig", "gulp... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #PHP | PHP | function maxnum($nums) {
usort($nums, function ($x, $y) { return strcmp("$y$x", "$x$y"); });
return implode('', $nums);
}
echo maxnum(array(1, 34, 3, 98, 9, 76, 45, 4)), "\n";
echo maxnum(array(54, 546, 548, 60)), "\n"; |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #m4 | m4 | divert(-1)
define(`gcd',
`ifelse(eval(`0 <= (' $1 `)'),`0',`gcd(eval(`-(' $1 `)'),eval(`(' $2 `)'))',
eval(`0 <= (' $2 `)'),`0',`gcd(eval(`(' $1 `)'),eval(`-(' $2 `)'))',
eval(`(' $1 `) == 0'),`0',`gcd(eval(`(' $2 `) % (' $1 `)'),eval(`(' $1 `)'))',
eval(`(' $2 `)'))')
define(`lcm',
... |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Maple | Maple | > ilcm( 12, 18 );
36
|
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
\\ Iterative with two matrix rows
function LevenshteinDistance(s$,t$) {
if len(s$)<len(t$) then swap s$, t$
n=len(t$)
m=len(s$)
dim base 0, v0(n+1), v1(n+1)
Rem dim sw() ' we can use stack of values to make the swap.
for i=0 to n : v0(i)=i:next
for i=0 to m-1
v1(0)=i+1
for j=0 ... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Julia | Julia | using DataStructures
function letterfreq(file::AbstractString; fltr::Function=(_) -> true)
sort(Dict(counter(filter(fltr, read(file, String)))))
end
display(letterfreq("src/Letter_frequency.jl"; fltr=isletter))
|
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
// basic linear congruential generator
var lcg = Fn.new { |a, c, m, seed|
var r = BigInt.new(seed)
return Fn.new {
r = (r*a + c) % m
return r
}
}
// Microsoft generator has extra division step
var msg = Fn.new { |seed|
var g = lcg.call(2... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Liberty_BASIC | Liberty BASIC | if leap(1996)then
print "leap"
else
print "ordinary"
end if
wait
function leap(n)
leap=date$("2/29/";n)
end function |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #XPL0 | XPL0 | real PosX, PosY, Angle;
proc DrawSide(Depth, Dist); \Draw side as 4 segments
int Depth; real Dist;
int I; real Dir;
def Deg2Rad = 3.14159265358979323846/180.;
[Dir:= [0., -60., 120., -60.];
for I:= 0 to 3 do
[Angle:= Angle + Dir(I);
if Depth < 4 then DrawSide(Depth+1, Dist/3.)
else [PosX:= PosX + Di... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #zkl | zkl | var width=512, height=512, img=PPM(width,height,0xFfffFF); // white canvas
var angle=(60.0).toRad();
const green=0x00FF00;
fcn koch(x1,y1, x2,y2, it){
x3,y3 := (x1*2 + x2) /3, (y1*2 + y2) /3;
x4,y4 := (x1 + x2*2)/3, (y1 + y2*2)/3;
x:=x3 + (x4-x3)*angle.cos() + (y4-y3)*angle.sin();
y:=y3 - (x4-x3)*... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Erlang | Erlang |
-module( langtons_ant ).
-export( [task/0] ).
-record( neighbour, {north, south, east, west} ).
-record( state, {colour=white, controller, max_x, max_y, neighbour, position} ).
task() ->
Controller = erlang:self(),
Max_x = Max_y = 100,
Pid_positions = plane_create( Controller, Max_x, Max_y ... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #REXX | REXX | /*REXX program calculates the Kronecker product of two arbitrary size matrices. */
w= 0 /*W: max width of any matrix element. */
aMat= 2x2 1 2 3 4 /*define A matrix size and elements.*/
bMat= 2x2 0 5 6 7 ... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #JavaScript | JavaScript | var last_friday_of_month, print_last_fridays_of_month;
last_friday_of_month = function(year, month) {
var i, last_day;
i = 0;
while (true) {
last_day = new Date(year, month, i);
if (last_day.getDay() === 5) {
return last_day.toDateString();
}
i -= 1;
}
};
print_last_fridays_of_month = ... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Wren | Wren | var maxPathLength = 0
var maxPathLengthCount = 0
var maxPathExample = ""
var names = [
"audino", "bagon", "baltoy", "banette", "bidoof",
"braviary", "bronzor", "carracosta", "charmeleon", "cresselia",
"croagunk", "darmanitan", "deino", "emboar", "emolga",
"exeggcute", "gabite", "girafarig", "gulpin", ... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Picat | Picat | s_perm1(L, Num) =>
permutation(L,P),
Num = [I.to_string() : I in P].flatten().to_integer(). |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #PicoLisp | PicoLisp | (load "@lib/simul.l") # For 'permute' |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | LCM[18,12]
-> 36 |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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)
In information theory and computer science, the Levenshtein ... | #Maple | Maple |
> with(StringTools):
> Levenshtein("kitten","sitting");
3
> Levenshtein("rosettacode","raisethysword");
8
|
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #K | K | +(?a;#:'=a:,/0:`) |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #X86_Assembly | X86 Assembly | ;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
;Assembled with NASM version 2.11.06
;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project)
;Assembled and linked with the following commands:... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Lingo | Lingo | on isLeapYear (year)
return date(year, 2, 29).month=2
end |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #LiveCode | LiveCode | function isLeapYear year
return (year MOD 4 is 0) AND ((year MOD 400 is 0) OR (year MOD 100 is not 0))
end isLeapYear
command testLeapYear
set itemDelimiter to comma
put "1900,1994,1996,1997,2000" into years
repeat for each item y in years
put y && "is" && isLeapYear(y) && return after tyears... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Euphoria | Euphoria | include std\console.e
include std\graphics.e
sequence grid = repeat(repeat(1,100),100) --fill 100 by 100 grid with white (1)
sequence antData = {48, 53, 360} --ant x coordinate, y coordinate, facing angle
integer iterations = 0
--while ant isn't out of bounds of the 100 by 100 area..
while antData[1] > 0 and antDat... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Ring | Ring |
# Project : Kronecker product
a = [[1, 2], [3, 4]]
b = [[0, 5], [6, 7]]
la1 = 1
ua1 = 2
la2 = 1
ua2 = 2
lb1 = 1
ub1 = 2
lb2 = 1
ub2 = 2
kroneckerproduct(a,b)
see nl
la1 = 1
ua1 = 3
la2 = 1
ua2 = 3
lb1 = 1
ub1 = 3
lb2 = 1
ub2 = 3
x = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
y = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #jq | jq | # In case your jq does not have "until" defined:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# Zeller's Congruence is from [[Day_of_the_week#jq]]
# Use Zeller's Congruence to determine the day of the week, given
# year, month and day as integers in the conventional wa... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Yabasic | Yabasic | all$ = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon "
all$ = all$ + "cresselia croagunk darmanitan deino emboar emolga exeggcute gabite "
all$ = all$ + "girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan "
all$ = all$ + "kricketune landorus ledyba loudred lumine... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #PL.2FI | PL/I |
/* Largest catenation of integers 16 October 2013 */
/* Sort using method 2, comparing pairs of adjacent integers. */
Largest: procedure options (main);
declare s(*) char (20) varying controlled, n fixed binary;
get (n);
allocate s(n);
get list (s);
s = trim(s);
put skip edit (s) (a, x(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.