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/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #R | R | Lah_numbers <- function(n, k, type = "unsigned") {
if (n == k)
return(1)
if (n == 0 | k == 0)
return(0)
if (k == 1)
return(factorial(n))
if (k > n)
return(NA)
if (type == "unsigned")
return((factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 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... | #OpenEdge.2FProgress | OpenEdge/Progress | DEFINE VARIABLE cpokemon AS CHARACTER INITIAL "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 lun... |
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,... | #Groovy | Groovy | def largestInt = { c -> c.sort { v2, v1 -> "$v1$v2" <=> "$v2$v1" }.join('') as BigInteger } |
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,... | #Haskell | Haskell | import Data.List (sortBy)
import Data.Ord (comparing)
main = print (map maxcat [[1,34,3,98,9,76,45,4], [54,546,548,60]] :: [Integer])
where
sorted xs = let pad x = concat $ replicate (maxLen `div` length x + 1) x
maxLen = maximum $ map length xs
in sortBy (flip $ co... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Red | Red | Red []
t0: now/time/precise ;; measure runtime
lbn: 98764321 + 1 ;; because digit 5 is ruled out, this is the highest 8 digit number
;; possible, add 1 because only even numbers are possible
check: func [tos [ string! ]] [ ;; function to check if number is divideable by
... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #REXX | REXX | /*REXX program finds the largest (decimal) integer divisible by all its decimal digits. */
$= 7 * 8 * 9 /*a # that it must divide the found #. */
t= 0 /*the number of divisibility trials. */
do #=9876432 % $ * $ by -$ ... |
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... | #Fortran | Fortran |
integer function lcm(a,b)
integer:: a,b
lcm = a*b / gcd(a,b)
end function lcm
integer function gcd(a,b)
integer :: a,b,t
do while (b/=0)
t = b
b = mod(a,b)
a = t
end do
gcd = abs(a)
end function gcd
|
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every process(!&input)
end
procedure process(s)
s ? (s1 := tab(upto(' \t')), s2 := (tab(many(' \t')), tab(0))) | fail
write("'",s1,"' -> '",s2,"' = ", levenshtein(s1,s2))
end
procedure levenshtein(s, t)
if (n := *s+1) = 1 then return *t
if (m := *t+1) = 1 then return *s
ev... |
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... | #Forth | Forth | create counts 26 cells allot
: freq ( filename -- )
counts 26 cells erase
slurp-file bounds do
i c@ 32 or [char] a -
dup 0 26 within if
cells counts +
1 swap +!
else drop then
loop
26 0 do
cr [char] ' emit [char] a i + emit ." ': "
counts i cells + @ .
loop ;
s" example.t... |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Wren | Wren | import "/fmt" for Fmt
import "/big" for BigInt
var lfacts = List.filled(12, BigInt.zero)
var lfact = BigInt.one
var sum = BigInt.zero
for (i in 1..10) {
sum = sum + lfact
lfacts[i] = sum
lfact = lfact * i
}
System.print("Left factorials from 0 to 10:")
for (i in 0..10) System.write(" %(lfacts[i])")
fo... |
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
... | #Quackery | Quackery | [ number$
10 over size -
space swap of
swap join echo$ ] is echonum ( n --> )
[ stack 0 ] is BSD-seed ( --> n )
[ BSD-seed take
1103515245 *
12345 +
hex 7FFFFFFF &
dup BSD-seed put ] is BSD-rand ( --> n )
[ stack 0 ] is MCR-seed ( --> n )
[ MCR-s... |
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)
| #FreeBASIC | FreeBASIC | ' version 23-06-2015
' compile with: fbc -s console
#Ifndef TRUE ' define true and false for older freebasic versions
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function leapyear(Year_ As Integer) As Integer
If (Year_ Mod 4) <> 0 Then Return FALSE
If (Year_ Mod 100) = 0 AndAlso (Year_ Mo... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Kotlin | Kotlin | // Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import kotlin.math.*
import java.io.File
import javax.imageio.ImageIO
val Double.asI get() = this.toInt()
class Point(var x: Int, var y: Int)
class BasicBitmapStorage(width: Int, height: Int) {
val image = 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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[sofncreator]
sofncreator[n_] := Module[{sample, i},
sample = {};
i = 0;
Return[
Function[{item},
i++;
If[i <= n,
AppendTo[sample, item]
,
If[RandomInteger[{1, i}] <= n,
sample[[RandomInteger[{1, n}]]] = item
]
];
sample
]
]
]
bin = ConstantArray[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... | #Nim | Nim | import random
func sOfNCreator[T](n: Positive): proc(item: T): seq[T] =
var sample = newSeqOfCap[T](n)
var i = 0
result = proc(item: T): seq[T] =
inc i
if i <= n:
sample.add(item)
elif rand(1..i) <= n:
sample[rand(n - 1)] = item
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int w = 0, h = 0;
unsigned char *pix;
void refresh(int x, int y)
{
int i, j, k;
printf("\033[H");
for (i = k = 0; i < h; putchar('\n'), i++)
for (j = 0; j < w; j++, k++)
putchar(pix[k] ? '#' : ' ');
}
void walk()
{
int dx = 0,... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Racket | Racket | #lang racket
(define pow-path-cache (make-hash '((0 . (0)) (1 . (0 1)))))
(define pow-path-level '(1))
(define (pow-path-extend!)
(define next-level
(for*/fold ([next-level '()])
([x (in-list pow-path-level)]
[y (in-list (pow-path x))]
[s (in-value (+ x y))]
... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Raku | Raku | use v6;
sub power-path ($n ) {
state @unused_nodes = (2,);
state @power-tree = (False,0,1);
until @power-tree[$n].defined {
my $node = @unused_nodes.shift;
for $node X+ power-path($node).pick(*) {
next if @power-tree[$_].defined;
@unused_nodes.push($_);
... |
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 ... | #J | J | KP=: dyad def ',/"2 ,/ 1 3 |: x */ 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 ... | #Java | Java |
package kronecker;
/**
* Defines a function to calculate the Kronecker product of two
* rectangular matrices and tests it with two examples.
*/
public class Product {
/**
* Find the Kronecker product of the arguments.
* @param a The first matrix to multiply.
* @param b The second matrix to multiply.
... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | m = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}};
ArrayPlot[KroneckerProduct[m, m, m, m]]
m = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
ArrayPlot[KroneckerProduct[m, m, m, m]]
m = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}};
ArrayPlot[KroneckerProduct[m, m, m, m]] |
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 ... | #Nim | Nim | import sequtils
type Matrix[T] = seq[seq[T]]
func kroneckerProduct[T](a, b: Matrix[T]): Matrix[T] =
result = newSeqWith(a.len * b.len, newSeq[T](a[0].len * b[0].len))
let m = a.len
let n = a[0].len
let p = b.len
let q = b[0].len
for i in 0..<m:
for j in 0..<n:
for k in 0..<p:
for l in ... |
http://rosettacode.org/wiki/Kolakoski_sequence | Kolakoski sequence | The Kolakoski sequence is an infinite sequence of natural numbers, (excluding zero); with the property that:
if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence.
Example
This is not a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2... | #Vlang | Vlang | fn next_in_cycle(c []int, index int) int {
return c[index % c.len]
}
fn kolakoski(c []int, slen int) []int {
mut s := []int{len: slen}
mut i, mut k := 0, 0
for {
s[i] = next_in_cycle(c, k)
if s[k] > 1 {
for j := 1; j < s[k]; j++ {
i++
if i ==... |
http://rosettacode.org/wiki/Kolakoski_sequence | Kolakoski sequence | The Kolakoski sequence is an infinite sequence of natural numbers, (excluding zero); with the property that:
if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence.
Example
This is not a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2... | #Wren | Wren | var kolakoski = Fn.new { |c, slen|
var s = List.filled(slen, 0)
var i = 0
var k = 0
while (true) {
s[i] = c[k % c.count]
if (s[k] > 1) {
for (j in 1...s[k]) {
i = i + 1
if (i == slen) return s
s[i] = s[i-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... | #Elm | Elm | import Html exposing (Html, Attribute, text, div, input)
import Html.App exposing (beginnerProgram)
import Html.Attributes exposing (placeholder, value, style)
import Html.Events exposing (onInput)
import String exposing (toInt)
import Maybe exposing (withDefault)
import List exposing (map, map2)
import List.Extra expo... |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #Raku | Raku | constant @factorial = 1, |[\*] 1..*;
sub Lah (Int \n, Int \k) {
return @factorial[n] if k == 1;
return 1 if k == n;
return 0 if k > n;
return 0 if k < 1 or n < 1;
(@factorial[n] * @factorial[n - 1]) / (@factorial[k] * @factorial[k - 1]) / @factorial[n - k]
}
my $upto = 12;
my $mx = (1..$upto).... |
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... | #Perl | Perl | use strict;
my(%f,@m);
/^(.).*(.)$/,$f{$1}{$_}=$2 for qw(
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 lumin... |
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,... | #Icon_and_Unicon | Icon and Unicon | import Collections # For the Heap (dense priority queue) class
procedure main(a)
write(lici(a))
end
procedure lici(a)
every (result := "") ||:= Heap(a,,cmp).gen()
return result
end
procedure cmp(a,b)
return (a||b) > (b||a)
end |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Ring | Ring |
# Project : Largest number divisible by its digits
for n = 9867000 to 9867400
numbers = list(9)
for t=1 to 9
numbers[t] = 0
next
flag = 1
flag2 = 1
flag3 = 1
str=string(n)
for m=1 to len(str)
if number(str[m]) > 0
numbers[number(str[m])] = numbers[number(s... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Ruby | Ruby | magic_number = 9*8*7
div = 9876432.div(magic_number) * magic_number
candidates = div.step(0, -magic_number)
res = candidates.find do |c|
digits = c.digits
(digits & [0,5]).empty? && digits == digits.uniq
end
puts "Largest decimal number is #{res}" |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function lcm (m As Integer, n As Integer) As Integer
If m = 0 OrElse n = 0 Then Return 0
If m < n Then Swap m, n '' to minimize iterations needed
Var count = 0
Do
count +=1
Loop Until (m * count) Mod n = 0
Return m * count
End Function
Print "lcm(12, 18) ="; lcm(12, 18)
Print "lcm... |
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 ... | #Io | Io | Io 20110905
Io> Range ; "kitten" levenshtein("sitting")
==> 3
Io> "rosettacode" levenshtein("raisethysword")
==> 8
Io> |
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... | #Fortran | Fortran |
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 18:09:46
a=./F && make $a && $a < configuration.file
f95 -Wall -ffree-form F.F -o F
92 21 17 24 82 19 19 22 67 0 2 27... |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #zkl | zkl | var BN=Import("zklBigNum");
fcn leftFact(n){
[1..n].reduce(fcn(p,n,rf){ p+=rf.value; rf.set(rf.value*n); p },
BN(0),Ref(BN(1)));
} |
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
... | #R | R | library(gmp) # for big integers
rand_BSD <- function(n = 1) {
a <- as.bigz(1103515245)
c <- as.bigz(12345)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c) %% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c) %% m
i <- i + 1
}
as.integer(x)
}
seed <- 0
rand_BSD(10... |
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
... | #Racket | Racket |
#lang racket
(require racket/generator)
(define (bsd-update state_n)
(modulo (+ (* 1103515245 state_n) 12345)
(expt 2 31)))
(define (ms-update state_n)
(modulo (+ (* 214013 state_n) 2531011)
(expt 2 31)))
(define ((rand update ->rand) seed)
(generator ()
(let loop ([state_n seed])
... |
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)
| #FutureBasic | FutureBasic | window 1
// In-line C function to generate random number in range
BeginCFunction
long randomInRange( long min, long max ) {
int i = (arc4random()%(max-min+1))+min;
return (long)i;
}
EndC
toolbox fn randomInRange( long min, long max ) = long
// Leap year test function
local fn LeapYear( year as long ) as B... |
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)
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Form_Open()
Dim dDate As Date
Dim siYear As Short = InputBox("Enter a year", "Leap year test")
Dim sMessage As String = " is a leap year."
Try dDate = Date(siYear, 02, 29)
If Error Then sMessage = " is not a leap year."
Message(siYear & sMessage)
End |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Lambdatalk | Lambdatalk |
{def koch
{lambda {:d :n}
{if {< :n 1}
then M:d
else {koch {/ :d 3} {- :n 1}} T-60
{koch {/ :d 3} {- :n 1}} T120
{koch {/ :d 3} {- :n 1}} T-60
{koch {/ :d 3} {- :n 1}} }}}
-> koch
{def K {koch 300 4}}
-> K
{svg {@ width="580" height="580" style="box-shadow:0 0 8px #000;"}
{polyl... |
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... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
typedef NSArray *(^SOfN)(id);
SOfN s_of_n_creator(int n) {
NSMutableArray *sample = [[NSMutableArray alloc] initWithCapacity:n];
__block int i = 0;
return [^(id item) {
i++;
if (i <= n) {
[sample addObject:item];
} else if (rand() % i < n) {
sample[ran... |
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... | #C.23 | C# | using System;
namespace LangtonAnt
{
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
enum Direction
{
North, East, West, South
}
public class Langton
{
... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #REXX | REXX | /*REXX program produces & displays a power tree for P, and calculates & displays X^P.*/
numeric digits 1000 /*be able to handle some large numbers.*/
parse arg XP /*get sets: X, low power, high power.*/
if XP='' then XP='2 -4 17 3 191 191 1.1 81... |
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 ... | #JavaScript | JavaScript |
// matkronprod.js
// Prime function:
// mkp arrow function: Return the Kronecker product of the a and b matrices.
// Note: both a and b must be matrices, i.e., 2D rectangular arrays.
mkp=(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t;
// Helper functions:
// Log title and matrix mat t... |
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 ... | #PARI.2FGP | PARI/GP |
\\ Build block matrix applying Kronecker product to the special matrix m
\\ (n times to itself). Then plot Kronecker fractal. 4/25/2016 aev
pkronfractal(m,n=2,clr)={
my(r=m);
for(i=1,n, r=matkronprod(r,m));
iPlotmat(r,clr);
}
\\Requireq tests:
{\\ Vicsek fractal: VicsekFractalgp.png
my(M=[0,1,0;1,1,1;0,1,0]);... |
http://rosettacode.org/wiki/Kolakoski_sequence | Kolakoski sequence | The Kolakoski sequence is an infinite sequence of natural numbers, (excluding zero); with the property that:
if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence.
Example
This is not a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2... | #zkl | zkl | fcn kolakoski(start_items=List(1,2), length=20){ //-->List
Walker.tweak(fcn(s,rk,cw){ // infinite iterator
s.append( c_next:=cw() );
sk:=s[rk.inc()]; // inc returns previous value, ie k++
if(sk>1) s.extend((List.createLong(sk - 1,c_next))); // list of sk cn's
sk // where we are in s, not ... |
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... | #Emacs_Lisp | Emacs Lisp | (require 'calendar)
(defun last-friday (year)
"Print the last Friday 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/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #REXX | REXX | /*REXX pgm computes & display (unsigned) Stirling numbers of the 3rd kind (Lah numbers).*/
parse arg lim . /*obtain optional argument from the CL.*/
if lim=='' | lim=="," then lim= 12 /*Not specified? Then use the default.*/
olim= lim ... |
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... | #Phix | Phix | with javascript_semantics
constant words = {"audino","bagon","baltoy","banette","bidoof","braviary","bronzor","carracosta","charmeleon","cresselia","croagunk",
"darmanitan","deino","emboar","emolga","exeggcute","gabite","girafarig","gulpin","haxorus","heatmor","heatran",
"ivysaur","j... |
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,... | #J | J | maxlen=: [: >./ #&>
maxnum=: (0 ". ;)@(\: maxlen $&> ])@(8!:0) |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Scala | Scala | import scala.collection.mutable
def largestDecimal: Int = Iterator.from(98764321, -1).filter(chkDec).next
def chkDec(num: Int): Boolean = {
val set = mutable.HashSet[Int]()
num.toString.toVector.map(_.asDigit).forall(d => (d != 0) && (num%d == 0) && set.add(d))
} |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Sidef | Sidef | func largest_number(base) {
var digits = @(base ^.. 1)
digits.each {|k|
digits.variations(k, {|*a|
var n = Number(a.join, base)
if (a.all {|d| d.divides(n) }) {
return n
}
})
}
}
say largest_number(10) #=> 9867312 |
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... | #Frink | Frink |
println[lcm[2562047788015215500854906332309589561, 6795454494268282920431565661684282819]]
|
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... | #FunL | FunL | def
lcm( _, 0 ) = 0
lcm( 0, _ ) = 0
lcm( x, y ) = abs( (x\gcd(x, y)) y ) |
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 ... | #J | J | levenshtein=:4 :0
D=. x +/&i.&>:&# y
for_i.1+i.#x do.
for_j.1+i.#y do.
if. ((<:i){x)=(<:j){y do.
D=.(D {~<<:i,j) (<i,j)} D
else.
min=. 1+<./D{~(i,j) <@:-"1#:1 2 3
D=. min (<i,j)} D
end.
end.
end.
{:{:D
) |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim a(65 to 90) As Integer ' array to hold frequency of each letter, all elements zero initially
Dim fileName As String = "input.txt"
Dim s As String
Dim i As Integer
Open fileName For Input As #1
While Not Eof(1)
Line Input #1, s
s = UCase(s)
For i = 0 To Len(s) - 1
a(s[i]) += 1
Next... |
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
... | #Raku | Raku | constant modulus = 2**31;
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
}
sub ms {
map * +> 16, (
$^seed, ( 214013 * * + 2531011 ) % modulus ... *
)
}
say 'BSD LCG first 10 values (first one is the seed):';
.say for bsd(0)[^10];
say "\nMS LCG first 10 values (first one is the seed):";... |
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)
| #Gambas | Gambas | Public Sub Form_Open()
Dim dDate As Date
Dim siYear As Short = InputBox("Enter a year", "Leap year test")
Dim sMessage As String = " is a leap year."
Try dDate = Date(siYear, 02, 29)
If Error Then sMessage = " is not a leap year."
Message(siYear & sMessage)
End |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Logo | Logo |
to ff :l :i
cs
right 90
pd
pr [lenght] show form :l 4 0
pr [iterations] show form :i 4 0
koch :l :i
end
to koch :len :iterations
ifelse :iterations = 1 [fd :len] [
koch :len :iterations - 1
left 60
koch :len :iterations - 1
right 120
koch :len :iterations - 1
left 60
koch :len :iterations - 1]
end
to zz... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Lua | Lua | local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = func... |
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... | #OCaml | OCaml | let s_of_n_creator n =
let i = ref 0
and sample = ref [| |] in
fun item ->
incr i;
if !i <= n then sample := Array.append [| item |] !sample
else if Random.int !i < n then !sample.(Random.int n) <- item;
!sample
let test n items_set =
let s_of_n = s_of_n_creator n in
Array.fold_left (fun _ v... |
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... | #C.2B.2B | C++ |
#include <windows.h>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 600, CELL_SIZE = 4, GRID_SIZE =... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Sidef | Sidef | var lvl = [[1]]
var p = Hash(1 => 0)
func path(n) is cached {
n || return []
while (n !~ p) {
var q = []
for x in lvl[0] {
for y in path(x) {
break if (x+y ~~ p)
y = x+y
p{y} = x
q << 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 ... | #jq | jq | def kprod(a; b):
# element-wise multiplication of a matrix by a number, "c"
def multiply(c): map( map(. * c) );
# "right" should be a vector with the same length as the input
def laminate(right):
[range(0; right|length) as $i
| (.[$i] + [right[$i]]) ];
# "matrix" and the input matrix should have... |
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 ... | #Julia | Julia | # v0.6
# Julia has a builtin kronecker product function
a = [1 2; 3 4]
b = [0 5; 6 7]
k = kron(a, b)
println("$a × $b =")
for row in 1:size(k)[1]
println(k[row,:])
end
println()
a = [0 1 0; 1 1 1; 0 1 0]
b = [1 1 1 1; 1 0 0 1; 1 1 1 1]
k = kron(a, b)
println("$a × $b =")
for row in 1:size(k)[1]
println(k[ro... |
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 ... | #Perl | Perl | use Imager;
use Math::Cartesian::Product;
sub kronecker_product {
our @a; local *a = shift;
our @b; local *b = shift;
my @c;
cartesian {
my @cc;
cartesian {
push @cc, $_[0] * $_[1];
} [@{$_[0]}], [@{$_[1]}];
push @c, [@cc];
} [@a], [@b];
@c
}
sub k... |
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... | #Erlang | Erlang |
-module( last_date_each_month ).
-export( [monday/1, tuesday/1, wednesday/1, thursday/1, friday/1, saturday/1, sunday/1] ).
monday( Year ) -> last( Year, 1 ).
tuesday( Year ) -> last( Year, 2 ).
wednesday( Year ) -> last( Year, 3 ).
thursday( Year ) -> last( Year, 4 ).
friday( Year ) -> last( Year, 5 ).
saturday(... |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #Ruby | Ruby | def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*)
def lah(n, k)
case k
when 1 then fact(n)
when n then 1
when (..1),(n..) then 0
else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k)
end
end
r = (0..12)
puts "Unsigned Lah numbers: L(n, k):"
puts "n/k #{r.map{|n| "%11d" % n}.join}... |
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... | #Picat | Picat | go =>
words(Words),
% Words that starts with same letter as <this words>'s last letter.
Starts = new_map(),
foreach(Word in Words)
S = [ Word2 : Word2 in Words, Word != Word2, Word.last() = Word2.first()],
Starts.put(Word,S)
end,
% Sort the words according to lengths in decreasing order.
Wo... |
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,... | #Java | Java | import java.util.*;
public class IntConcat {
private static Comparator<Integer> sorter = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
String o1s = o1.toString();
String o2s = o2.toString();
if(o1s.length() == o2s.length())... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #VBScript | VBScript | ' Largest number divisible by its digits - base10 - VBScript
s=7*8*9 'reasonable assumption
m=9876432 'reasonable assumption
for i=(m\s)*s to 1 step -s
if instr(i,"5")=0 and instr(i,"0")=0 then '5 or 0 impossible
b=false: j=1
while j<=len(i)-1 and not b
if instr(j+1,i,mid(i,j,1))<>0 then b=true 'no... |
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... | #GAP | GAP | # Built-in
LcmInt(12, 18);
# 36 |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
} |
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 ... | #Java | Java | public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length();... |
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... | #Frink | Frink | print[formatTable[countToArray[select[graphemeList[lc[normalizeUnicode[read["https://www.gutenberg.org/files/135/135-0.txt", "UTF-8"],"NFC"]]], %r/[[:alpha:]]/ ]] , "right"]] |
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
... | #REXX | REXX | /*REXX program uses a linear congruential generator (LCG) that simulates the old BSD */
/*──────── and MS random number generators: BSD= 0──►(2^31)-1 MS= 0──►(2^16)-1 */
numeric digits 20 /*use enough dec. digs for the multiply*/
two@@16= 2**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)
| #GAP | GAP | IsLeapYear := function(n)
return (n mod 4 = 0) and ((n mod 100 <> 0) or (n mod 400 = 0));
end;
# alternative using built-in function
IsLeapYear := function(n)
return DaysInYear(n) = 366;
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)
| #Genie | Genie | [indent=4]
/*
Leap year, in Genie
valac leapYear.gs
./leapYear
*/
init
years:array of DateYear = {1900, 1994, 1996, 1997, 2000, 2100}
for year in years
status:string = year.is_leap_year() ? "" : "not "
stdout.printf("%d is %sa leap year.\n", year, status) |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Graphics[{GeometricTransformation[KochCurve[5], RotationTransform[Pi, {0.5, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[-Pi/3, {1, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[Pi/3, {0, 0}]]}] |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Nim | Nim |
from math import sin, cos, PI
import libgd
const
width = 512
height = 512
iterations = 4
proc kochCurve(img: gdImagePtr, x1, y1, x2, y2: float, iter: int): void =
let angle = PI / 3 # 60 degrees
let x3 = (x1 * 2 + x2) / 3
let y3 = (y1 * 2 + y2) / 3
let x4 = (x1 + x2 * 2) / 3
let y4 = (y1 + y2 * 2... |
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... | #PARI.2FGP | PARI/GP | KnuthS(v,n)={
my(u=vector(n,i,i));
for(i=n+1,#v,
if(random(i)<n,u[random(n)+1]=i)
);
vecextract(v,u)
};
test()={
my(v=vector(10),t);
for(i=1,1e5,
t=KnuthS([0,1,2,3,4,5,6,7,8,9],3);
v[t[1]+1]++;v[t[2]+1]++;v[t[3]+1]++
);
v
}; |
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... | #Chapel | Chapel |
config const gridHeight: int = 100;
config const gridWidth: int = 100;
class PBMWriter {
var imgDomain: domain(2);
var imgData: [imgDomain] int;
proc PBMWriter( height: int, width: int ){
imgDomain = { 1..#height, 1..#width };
}
proc this( i : int, j : int) ref : int{
return this.imgData[ i, j... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Wren | Wren | import "/big" for BigRat
import "/fmt" for Fmt
var p = { 1: 0 }
var lvl = [[1]]
var path // recursive
path = Fn.new { |n|
if (n == 0) return []
while (!p.containsKey(n)) {
var q = []
for (x in lvl[0]) {
System.write("") // guard against VM recursion bug
for (y in path... |
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 ... | #Kotlin | Kotlin | // version 1.1.2 (JVM)
typealias Matrix = Array<IntArray>
fun kroneckerProduct(a: Matrix, b: Matrix): Matrix {
val m = a.size
val n = a[0].size
val p = b.size
val q = b[0].size
val rtn = m * p
val ctn = n * q
val r: Matrix = Array(rtn) { IntArray(ctn) } // all elements zero by default
... |
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 ... | #Phix | Phix | function kronecker(sequence a, b)
integer ar = length(a),
ac = length(a[1]),
br = length(b),
bc = length(b[1])
sequence res = repeat(repeat(0,ac*bc),ar*br)
for ia=1 to ar do
integer i0 = (ia-1)*br
for ja=1 to ac do
integer j0 = (ja-1)*bc
... |
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... | #Factor | Factor | USING: calendar calendar.format command-line io kernel math.parser sequences ;
IN: rosetta-code.last-fridays
(command-line) second string>number <year> 12 <iota>
[ months time+ last-friday-of-month ] with map
[ timestamp>ymd print ] each |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #Scheme | Scheme | ; Compute the Unsigned Lah number L(n, k).
(define lah
(lambda (n k)
(/ (/ (* (fact n) (fact (1- n))) (* (fact k) (fact (1- k)))) (fact (- n k)))))
; Procedure to compute factorial.
(define fact
(lambda (n)
(if (<= n 0)
1
(* n (fact (1- n))))))
; Generate a table of the Unsigned Lah numbers ... |
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... | #PicoLisp | PicoLisp | (de pokemonChain (File)
(let Names (make (in File (while (read) (link @))))
(for Name Names
(let C (last (chop Name))
(set Name
(filter '((Nm) (pre? C Nm)) Names) ) ) )
(let Res NIL
(for Name Names
(let Lst NIL
(recur (Name Lst)
... |
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... | #Prolog | Prolog | :- use_module(library(lambda)).
:- dynamic res/3.
last_first(Len, Nb, L) :-
retractall(res(_,_,_)),
assert(res(0, 0, [])),
% compute all the lists of connected words
last_first,
res(Len, Nb, L1),
% to have only the words
maplist(\X^Y^(X = [Y, _, _]), L1, L).
% create the lists of connected words (initiate... |
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,... | #JavaScript | JavaScript | (function () {
'use strict';
// maxCombine :: [Int] -> Int
function maxCombine(xs) {
return parseInt(
xs.sort(
function (x, y) {
var a = x.toString(),
b = y.toString(),
ab = parseInt(a + b),
... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ChkDec(num As Integer) As Boolean
Dim sett As New HashSet(Of Integer)
Return num.ToString() _
.Select(Function(c) Asc(c) - Asc("0")) _
.All(Function(d) (d <> 0) AndAlso (num Mod d = 0) AndAlso sett.Add(d))
End Function
Sub Main()
Di... |
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... | #Groovy | Groovy | def gcd
gcd = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcd(n, m % n) }
def lcd = { m, n -> Math.abs(m * n) / gcd(m, n) }
[[m: 12, n: 18, l: 36],
[m: -6, n: 14, l: 42],
[m: 35, n: 0, l: 0]].each { t ->
println "LCD of $t.m, $t.n is $t.l"
assert lcd(t.m, t.n) == t.l
} |
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 ... | #JavaScript | JavaScript | function levenshtein(a, b) {
var t = [], u, i, j, m = a.length, n = b.length;
if (!m) { return n; }
if (!n) { return m; }
for (j = 0; j <= n; j++) { t[j] = j; }
for (i = 1; i <= m; i++) {
for (u = [i], j = 1; j <= n; j++) {
u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1])... |
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... | #Gambas | Gambas | Public Sub Form_Open()
Dim sData As String = File.Load("data.txt")
Dim iCount, iSpaces, iLetters, iOther As Integer
Dim bPunctuation As Boolean
For iCount = 1 To Len(sData)
If InStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase(Mid(sData, iCount, 1))) Then
Inc iLetters
bPunctuation = True
End If
If Mid(sData, 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
... | #Ruby | Ruby | module LCG
module Common
# The original seed of this generator.
attr_reader :seed
# Creates a linear congruential generator with the given _seed_.
def initialize(seed)
@seed = @r = seed
end
end
# LCG::Berkeley generates 31-bit integers using the same formula
# as BSD rand().
clas... |
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)
| #Go | Go | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
} |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Perl | Perl | use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
# Compute the curve with a Lindemayer-system
my $koch = 'F--F--F';
$koch =~ s/F/F+F--F+F/g for 1..5;
# Draw the curve in SVG
($x, $y) = (0, 0);
$theta = pi/3;
$r = 2;
for (split //, $koch) {
if (/F/) {
push @X, sprintf ... |
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... | #Perl | Perl | use strict;
sub s_of_n_creator {
my $n = shift;
my @sample;
my $i = 0;
sub {
my $item = shift;
$i++;
if ($i <= $n) {
# Keep first n items
push @sample, $item;
} elsif (rand() < $n / $i) {
# Keep item
@sample[rand $n] = $it... |
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... | #Clojure | Clojure | (let [bounds (set (range 100))
xs [1 0 -1 0] ys [0 -1 0 1]]
(loop [dir 0 x 50 y 50
grid {[x y] false}]
(if (and (bounds x) (bounds y))
(let [cur (not (grid [x y]))
dir (mod (+ dir (if cur -1 1)) 4)]
(recur dir (+ x (xs dir)) (+ y (ys dir))
(merge grid {[x y]... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #zkl | zkl | # remember the tree generation state and expand on demand
fcn path(n,p=Dictionary(1,0),lvl=List(List(1))){
if(n==0) return(T);
while(not p.holds(n)){
q:=List();
foreach x,y in (lvl[0],path(x,p,lvl)){
if(p.holds(x+y)) break; // not this y
y=x+y; p[y]=x;
q.append(y);
}
lvl[0]=q... |
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 ... | #Lua | Lua |
function prod( a, b )
print( "\nPRODUCT:" )
for m = 1, #a do
for p = 1, #b do
for n = 1, #a[m] do
for q = 1, #b[p] do
io.write( string.format( "%3d ", a[m][n] * b[p][q] ) )
end
end
print()
end
end
end
-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.