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/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 ...
#Python
Python
import os from PIL import Image     def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path)     def get_shape(mat): return len(mat), len(mat[0])     def kron(matrix1, ma...
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...
#Fortran
Fortran
program fridays implicit none integer :: days(1:12) = (/31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31/) integer :: year, k, y, m read *, year if (mod(year, 400) == 0 .or. (mod(year, 4) == 0 .and. mod(year, 100) /= 0)) days(2) = 29 y = year - 1 k = 44 + y + y/4 + 6*(y/100) + y/400 do m = 1, 12 ...
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...
#Sidef
Sidef
func lah(n, k) { stirling3(n, k) #binomial(n-1, k-1) * n!/k! # alternative formula }   const r = (0..12)   var triangle = r.map {|n| 0..n -> map {|k| lah(n, k) } } var widths = r.map {|n| r.map {|k| (triangle[k][n] \\ 0).len }.max }   say ('n\k ', r.map {|n| "%*s" % (widths[n], n) }.join(' '))   r.each {|...
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...
#Python
Python
from collections import defaultdict   def order_words(words): byfirst = defaultdict(set) for word in words: byfirst[word[0]].add( word ) #byfirst = dict(byfirst) return byfirst   def linkfirst(byfirst, sofar): '''\ For all words matching last char of last word in sofar as FIRST char and ...
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,...
#jq
jq
def largest_int:   def pad(n): . + (n - length) * .[length-1:];   map(tostring) | (map(length) | max) as $max | map([., pad($max)]) | sort_by( .[1] ) | map( .[0] ) | reverse | join("") ;   # Examples: ([1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]) | largest_int  
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...
#Wren
Wren
var divByAll = Fn.new { |n, digits| digits.all { |d| n%(d-48) == 0 } }   var magic = 9 * 8 * 7 var high = (9876432/magic).floor * magic var i = high while (i >= magic) { if (i%10 != 0) { // can't end in '0' var s = "%(i)" if (!s.contains("0") && !s.contains("5")) { // can't contain '0' or '5' ...
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...
#GW-BASIC
GW-BASIC
10 PRINT "LCM(35, 21) = "; 20 LET MLCM = 35 30 LET NLCM = 21 40 GOSUB 200: ' Calculate LCM 50 PRINT LCM 60 END 195 ' Calculate LCM 200 LET MGCD = MLCM 210 LET NGCD = NLCM 220 GOSUB 400: ' Calculate GCD 230 LET LCM = MLCM / GCD * NLCM 240 RETURN 395 ' Calculate GCD 400 WHILE MGCD <> 0 410 LET TMP = MGCD 420 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 ...
#jq
jq
9ms overhead (invoking jq and compiling the program) 17ms for kitten/sitting 67ms for rosettacode/raisethysword 71ms for edocattesor/drowsyhtesiar
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...
#Go
Go
package main   import ( "fmt" "io/ioutil" "sort" "unicode" )   const file = "unixdict.txt"   func main() { bs, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return } m := make(map[rune]int) for _, r := range string(bs) { m[r]++ } // ans...
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 ...
#Run_BASIC
Run BASIC
global bsd global ms print "Num ___Bsd___";chr$(9);"__Ms_" for i = 1 to 10 print using("##",i);using("############",bsdRnd());chr$(9);using("#####",msRnd()) next i   function bsdRnd() bsdRnd = (1103515245 * bsd + 12345) mod (2 ^ 31) bsd = bsdRnd end function   function msRnd() ms = (214013 * ms + 2531...
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 ...
#Rust
Rust
extern crate rand;   pub use rand::{Rng, SeedableRng};   pub struct BsdLcg { state: u32, }   impl Rng for BsdLcg { // Because the output is in the range [0, 2147483647], this should technically be `next_u16` // (the largest integer size which is fully covered, as `rand::Rng` assumes). The `rand` // cra...
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)
#Groovy
Groovy
(1900..2012).findAll {new GregorianCalendar().isLeapYear(it)}.each {println it}
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Phix
Phix
-- -- demo\rosetta\Koch_curve.exw -- =========================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas integer ox = 0, oy = 0 procedure koch(atom x1, y1, x2, y2, integer iter) atom angle = -PI/3, -- -60 degrees x3 := (x1*2 + x2) / 3, y3 := ...
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...
#Phix
Phix
with javascript_semantics enum RID, I, SAMPLE function s_of_n(sequence env, integer item) integer i = env[I] + 1, n = length(env[SAMPLE]) env = deep_copy(env) env[I] = i if i<=n then env[SAMPLE][i] = item elsif n/i>rnd() then env[SAMPLE][rand(n)] = item end if r...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. langtons-ant.   DATA DIVISION. WORKING-STORAGE SECTION. 78 Grid-Size VALUE 100. 01 grid-area. 03 grid-x OCCURS Grid-Size TIMES. 05 grid-y OCCURS Grid-Size TIMES. ...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
KroneckerProduct[{{1, 2}, {3, 4}}, {{0, 5}, {6, 7}}]//MatrixForm KroneckerProduct[{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}]//MatrixForm
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 ...
#R
R
  ## Generate and plot Kronecker product based fractals. aev 8/12/16 ## gpKronFractal(m, n, pf, clr, ttl, dflg=0, psz=600): ## Where: m - initial matrix (filled with 0/1); n - order of the fractal; ## pf - plot file name (without extension); clr - color; ttl - plot title; ## dflg - writing dump file flag (0/1); psz - p...
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...
#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 ' from the leapyear entry If (Year_ Mod 4) <> 0 Then Return FALSE If (Year_ Mo...
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...
#Swift
Swift
import BigInt import Foundation   @inlinable public func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 }   return stride(from: n, to: 0, by: -1).reduce(1, *) }   @inlinable public func lah<T: BinaryInteger>(n: T, k: T) -> T { if k == 1 { return factorial(n) } else if k == n {...
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...
#Tcl
Tcl
proc prod {from to} { set r 1 if {$from <= $to} { set r $from while {[incr from] <= $to} { set r [expr {$r * $from}] } } return $r }   proc US3 {n k} { if {$n < 0 || $k < 0} { error "US3(): negative arg ($n,$k)" } ## L(0,0) = 1 ## L(n,0) = 0 ...
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...
#Racket
Racket
#lang racket   (define names " 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 lunatone machamp ...
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,...
#Julia
Julia
function maxconcat(arr::Vector{<:Integer}) b = sort(string.(arr); lt=(x, y) -> x * y < y * x, rev=true) |> join return try parse(Int, b) catch parse(BigInt, b) end end   tests = ([1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60])   for arr in test...
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,...
#Kotlin
Kotlin
import kotlin.Comparator   fun main(args: Array<String>) { val comparator = Comparator<Int> { x, y -> "$x$y".compareTo("$y$x") }   fun findLargestSequence(array: IntArray): String { return array.sortedWith(comparator.reversed()).joinToString("") { it.toString() } }   for (array in listOf( ...
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...
#XPL0
XPL0
int Digits; \bit array   func AllDiv(N); \Return 'true' if N is divisible by its digits int N, D; [for D:= 9 downto 2 do if 1<<D & Digits then if rem(N/D) # 0 then return false; return true; ];   func Unique(N); \Return 'true' if N contains unique digits int N; [Digits:= 1; \disallow 0 while N do ...
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...
#zkl
zkl
const magic_number=9*8*7; # 504 const div=9876432 / magic_number * magic_number; #largest 7 digit multiple of 504 < 9876432   foreach test in ([div..0,-magic_number]){ text:=test.toString(); if(text.holds("0","5")) continue; # skip numbers containing 0 or 5 if(text.unique().len()!=text.len()) continue; # s...
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...
#Haskell
Haskell
lcm :: (Integral a) => a -> a -> a lcm _ 0 = 0 lcm 0 _ = 0 lcm x y = abs ((x `quot` (gcd x y)) * y)
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...
#Icon_and_Unicon
Icon and Unicon
link numbers procedure main() write("lcm of 18, 36 = ",lcm(18,36)) write("lcm of 0, 9 = ",lcm(0,9)) 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 ...
#Jsish
Jsish
/* Levenshtein Distance, in Jsish */   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 - ...
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...
#Groovy
Groovy
def frequency = { it.inject([:]) { map, value -> map[value] = (map[value] ?: 0) + 1; map } }   frequency(new File('frequency.groovy').text).each { key, value -> println "'$key': $value" }
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 ...
#Scala
Scala
object LinearCongruentialGenerator { def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{ var seed=rseed override def hasNext:Boolean=true override def next:Int={seed=(seed * 1103515245 + 12345) & Int.MaxValue; seed} }   def msRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{ var seed=rseed ...
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)
#GW-BASIC_2
GW-BASIC
10 ' Leap year 20 DEF FN ISLEAPYEAR(Y%) = ((Y% MOD 4 = 0) AND (Y% MOD 100 <> 0)) OR (Y% MOD 400 = 0) 95 ' *** Test *** 100 FOR I% = 1 TO 5 110 READ YEAR% 120 PRINT YEAR%; "is "; 130 IF FN ISLEAPYEAR(YEAR%) = 0 THEN PRINT "not "; ELSE PRINT ""; 140 PRINT "a leap year." 150 NEXT I% 160 END 200 DATA 1900, 1994, 19...
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Processing
Processing
int l = 300;   void setup() { size(400, 400); background(0, 0, 255); stroke(255); // draw from center of screen translate(width/2.0, height/2.0); // center curve from lower-left corner of base equilateral triangle translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rot...
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...
#PHP
PHP
<?php function s_of_n_creator($n) { $sample = array(); $i = 0; return function($item) use (&$sample, &$i, $n) { $i++; if ($i <= $n) { // Keep first n items $sample[] = $item; } else if (rand(0, $i-1) < $n) { // Keep item $sample[rand(0,...
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...
#CoffeeScript
CoffeeScript
  class Ant constructor: (@world) -> @location = [0, 0] @direction = 'E'   move: => [x, y] = @location if @world.is_set x, y @world.unset x, y @direction = Directions.left @direction else @world.set x, y @direction = Directions.right @direction @location = Directions....
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 ...
#Nim
Nim
import strutils   type Matrix[M, N: static Positive; T: SomeNumber] = array[M, array[N, T]]   func kroneckerProduct[M, N, P, Q: static int; T: SomeNumber]( a: Matrix[M, N, T], b: Matrix[P, Q, T]): Matrix[M * P, N * Q, T] = for i in 0..<M: for j in 0..<N: for k in 0..<P: for l in 0..<Q: r...
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 ...
#Octave
Octave
>> kron([1 2; 3 4], [0 5; 6 7]) ans =   0 5 0 10 6 7 12 14 0 15 0 20 18 21 24 28   >> kron([0 1 0; 1 1 1; 0 1 0], [1 1 1 1; 1 0 0 1; 1 1 1 1]) ans =   0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 1 1...
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 ...
#Raku
Raku
sub kronecker-product ( @a, @b ) { (@a X @b).map: { (.[0].list X* .[1].list).Array } }   sub kronecker-fractal ( @pattern, $order = 4 ) { my @kronecker = @pattern; @kronecker = kronecker-product(@kronecker, @pattern) for ^$order; @kronecker }   use Image::PNG::Portable;   #Task requirements my @vicsek = ( [...
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...
#Frink
Frink
d = parseDate[ARGS@0] for m = 1 to 12 { d = beginningOfNextMonth[d] n = d - (((parseInt[d -> ### u ###] + 1) mod 7) + 1) days println[n -> ### yyyy-MM-dd ###] }
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...
#VBScript
VBScript
' Lah numbers - VBScript - 04/02/2021 Function F(i,n) Dim c: c=CCur(i): If n>Len(c) Then F=Space(n-Len(c))&c Else F=c End Function 'F Function Fact(ByVal n) Dim res If n=0 Then Fact = 1 Else res = 1 While n>0 res = res*n ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Function Factorial(n As BigInteger) As BigInteger If n = 0 Then Return 1 End If   Dim res As BigInteger = 1 While n > 0 res *= n n -= 1 End While Return res End Function   Function ...
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...
#Raku
Raku
my @names = < 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 lunatone machamp magnezone...
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,...
#Lua
Lua
function icsort(numbers) table.sort(numbers,function(x,y) return (x..y) > (y..x) end) return numbers end   for _,numbers in pairs({{1, 34, 3, 98, 9, 76, 45, 4}, {54, 546, 548, 60}}) do print(('Numbers: {%s}\n Largest integer: %s'):format( table.concat(numbers,","),table.concat(icsort(numbers)) )) end
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...
#J
J
12 *. 18 36 12 *. 18 22 36 132 *./ 12 18 22 396 0 1 0 1 *. 0 0 1 1 NB. for truth valued arguments (0 and 1) it is equivalent to "and" 0 0 0 1 *./~ 0 1 0 0 0 1
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...
#Java
Java
import java.util.Scanner;   public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in);   //prompts user for values to find the LCM for, then saves them to m and n System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out....
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 ...
#Julia
Julia
function levendist(s::AbstractString, t::AbstractString) ls, lt = length.((s, t)) ls == 0 && return lt lt == 0 && return ls   s₁, t₁ = s[2:end], t[2:end] ld₁ = levendist(s₁, t₁) s[1] == t[1] ? ld₁ : 1 + min(ld₁, levendist(s, t₁), levendist(s₁, t)) end   @show levendist("kitten", "sitting") # 3 @...
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...
#Harbour
Harbour
PROCEDURE Main() LOCAL s := hb_MemoRead( Left( __FILE__ , At( ".", __FILE__ )) +"prg") LOCAL c, n, i LOCAL a := {}   FOR EACH c IN s IF Asc( c ) > 31 AAdd( a, c ) ENDIF NEXT a := ASort( a ) i := 1 WHILE i <= Len( a ) c := a[i] ; n := 1 i++ IF i < Len(a) .AN...
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 ...
#Scheme
Scheme
(define ((bsd-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) seed)   (define ((msvcrt-rand seed)) (set! seed (remainder (+ (* 214013 seed) 2531011) 2147483648)) (quotient seed 65536))   ; auxiliary function to get a list of 'n random numbers from generator 'r (define (rand-list r n) = (if ...
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)
#Harbour
Harbour
FUNCTION IsLeapYear( nYear ) RETURN iif( nYear % 100 == 0, nYear % 400 == 0, nYear % 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)
#Haskell
Haskell
import Data.List import Control.Monad import Control.Arrow   leaptext x b | b = show x ++ " is a leap year" | otherwise = show x ++ " is not a leap year"   isleapsf j | 0==j`mod`100 = 0 == j`mod`400 | otherwise = 0 == j`mod`4
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Prolog
Prolog
main:- write_koch_snowflake('koch_snowflake.svg').   write_koch_snowflake(File):- open(File, write, Stream), koch_snowflake(Stream, 600, 5), close(Stream).   koch_snowflake(Stream, Size, N):- format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n", [Size, Size])...
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...
#PicoLisp
PicoLisp
(de s_of_n_creator (@N) (curry (@N (I . 0) (Res)) (Item) (cond ((>= @N (inc 'I)) (push 'Res Item)) ((>= @N (rand 1 I)) (set (nth Res (rand 1 @N)) Item)) ) Res ) )   (let Freq (need 10 0) (do 100000 (let S_of_n (s_of_n_creator 3) (for I (mapc S_of_n (0 1 2 3 4 5 6 7 8 9...
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...
#Python
Python
from random import randrange   def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i   i += 1 if i <= n: # Keep first n items sample.append(item) elif randrange(i) < n: # Keep item sample[randrange(n)] = 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...
#Common_Lisp
Common Lisp
(defmacro toggle (gv) `(setf ,gv (not ,gv)))   (defun langtons-ant (width height start-x start-y start-dir) (let ( (grid (make-array (list width height))) (x start-x) (y start-y) (dir start-dir) ) (loop while (and (< -1 x width) (< -1 y height)) do (if (toggle (aref grid 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 ...
#PARI.2FGP
PARI/GP
  \\ Print title and matrix mat rows. 4/17/16 aev matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))} \\ \\ Create and return the Kronecker product of the a and b matrices. 4/17/16 aev matkronprod(a,b,pflg=0)={ my(m=#a[,1],n=#a[1,],p=#b[,1],q=#b[1,],r,rtn,ctn); rtn=m*p; ctn=n*q; if(pflg,print(" *** K...
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 ...
#REXX
REXX
/*REXX program calculates the Kronecker product of two arbitrary size matrices. */ parse arg pGlyph . /*obtain optional argument from the CL.*/ if pGlyph=='' | pGlyph=="," then pGlyph= '█' /*Not specified? Then use the default.*/ if length(pGlyph)==2 then pGlyph= x2c(pGlyph) ...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Form_Open() Dim siYear As Short = InputBox("Please input a year", "Last Friday of each month") Dim siMonth, siDay As Short Dim dDay As Date   For siMonth = 1 To 12 For siDay = 31 DownTo 22 Try dDay = Date(siYear, siMonth, siDay) If Error Then Continue If WeekDay(dDay) = 5 Then Print Form...
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...
#Vlang
Vlang
import math.big   fn main() { limit := 100 last := 12 unsigned := true mut l := [][]big.Integer{len: limit+1} for n := 0; n <= limit; n++ { l[n] = []big.Integer{len: limit+1} for k := 0; k <= limit; k++ { l[n][k] = big.zero_int } l[n][n]= big.integer_from_...
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...
#Wren
Wren
import "/fmt" for Fmt   var fact = Fn.new { |n| if (n < 2) return 1 var fact = 1 for (i in 2..n) fact = fact * i return fact }   var lah = Fn.new { |n, k| if (k == 1) return fact.call(n) if (k == n) return 1 if (k > n) return 0 if (k < 1 || n < 1) return 0 return (fact.call(n) * fac...
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...
#REXX
REXX
/*REXX program finds the longest path of word's last─letter ───► first─letter. */ @='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 kangask...
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,...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
makeLargestInt[list_] := Module[{sortedlist}, sortedlist = Sort[list, Order[ToString[#1] <> ToString[#2], ToString[#2] <> ToString[#1]] < 0 &]; Map[ToString, sortedlist] // StringJoin // FromDigits ] (* testing with two examples *) makeLargestInt[{1, 34, 3, 98, 9, 76, 45, 4}] makeLargestInt[{54, 546, 548, 60}]
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,...
#min
min
(quote cons "" join) :s+ ('string map (over over swap s+ 's+ dip <) sort "" join int) :fn   (1 34 3 98 9 76 45 4) fn puts! (54 546 548 60) fn puts!
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...
#JavaScript
JavaScript
function LCM(A) // A is an integer array (e.g. [-50,25,-45,-18,90,447]) { var n = A.length, a = Math.abs(A[0]); for (var i = 1; i < n; i++) { var b = Math.abs(A[i]), c = a; while (a && b){ a > b ? a %= b : b %= a; } a = Math.abs(c*A[i])/(a+b); } return a; }   /* For example: ...
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 ...
#Kotlin
Kotlin
// version 1.0.6   // Uses the "iterative with two matrix rows" algorithm referred to in the Wikipedia article.   fun levenshtein(s: String, t: String): Int { // degenerate cases if (s == t) return 0 if (s == "") return t.length if (t == "") return s.length   // create two integer arrays of distanc...
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...
#Haskell
Haskell
import Data.List (group,sort) import Control.Arrow ((&&&)) main = interact (show . map (head &&& length) . group . sort)
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 ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   var bigInteger: bsdSeed is 0_; var bigInteger: msSeed is 0_;   const func integer: bsdRand is func result var integer: bsdRand is 0; begin bsdSeed := (1103515245_ * bsdSeed + 12345_) mod 2147483648_; bsdRand := ord(bsdSeed); end func;   const func in...
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 ...
#SequenceL
SequenceL
  import <Utilities/Random.sl>;   main(args(2)) := let bsdRandomGenerator := newRandomGenerator(0, 0, 2147483647, bsdNext); msRandomGenerator := newRandomGenerator(0, 0, 32767, msNext);   // Create a random sequence with each one of the generators numbers := getRandomSequence([bsdRandomGenerator, msRandomGener...
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)
#Hy
Hy
(defn leap? [y] (and (= (% y 4) 0) (or (!= (% y 100) 0) (= (% y 400) 0))))
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Python
Python
'''Koch curve'''   from math import cos, pi, sin from operator import add, sub from itertools import chain     # kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)] def kochSnowflake(n, a, b): '''List of points on a Koch snowflake of order n, derived from an equilateral triangle with...
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...
#Racket
Racket
#lang racket/base   (define (s-of-n-creator n) (define i 0) (define sample (make-vector n)) ; the sample of n items (lambda (item) (set! i (add1 i)) (cond [(<= i n)  ; we're not full, so kind of boring (vector-set! sample (sub1 i) item)] [(< (random i) n)  ; we've al...
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...
#Raku
Raku
sub s_of_n_creator($n) { my @sample; my $i = 0; -> $item { if ++$i <= $n { push @sample, $item; } elsif $i.rand < $n { @sample[$n.rand] = $item; } @sample; } }   my @items = 0..9; my @bin;   for ^100000 { my &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...
#D
D
void main() @safe { import std.stdio, std.traits;   enum width = 75, height = 52; enum maxSteps = 12_000; enum Direction { up, right, down, left } enum Color : char { white = '.', black = '#' } uint x = width / 2, y = height / 2; Color[width][height] M; auto dir = Direction.up;   wit...
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 ...
#Perl
Perl
#!/usr/bin/perl use strict; use warnings; use PDL;   sub kron { my ($x, $y) = @_;   return $x->dummy(0) ->dummy(0) ->mult($y, 0) ->clump(0, 2) ->clump(1, 2) }   my @mats = ( [pdl([[1, 2], [3, 4]]), pdl([[0, 5], [6, 7]])], [pdl([[0, 1, 0], [1, 1, 1],...
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 ...
#Rust
Rust
use std::{ fmt::{Debug, Display, Write}, ops::Mul, };   // Rust has (almost) no built-in support for multi-dimensional arrays or so. // Let's make a basic one ourselves for our use cases.   #[derive(Clone, Debug)] pub struct Mat<T> { col_count: usize, row_count: usize, items: Vec<T>, }   impl<T> Mat...
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...
#Gambas
Gambas
Public Sub Form_Open() Dim siYear As Short = InputBox("Please input a year", "Last Friday of each month") Dim siMonth, siDay As Short Dim dDay As Date   For siMonth = 1 To 12 For siDay = 31 DownTo 22 Try dDay = Date(siYear, siMonth, siDay) If Error Then Continue If WeekDay(dDay) = 5 Then Print Form...
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...
#Vala
Vala
uint64 factorial(uint8 n) { uint64 res = 1; if (n == 0) return res; while (n > 0) res *= n--; return res; }   uint64 lah(uint8 n, uint8 k) { if (k == 1) return factorial(n); if (k == n) return 1; if (k > n) return 0; if (k < 1 || n < 1) return 0; return (factorial(n) * factorial(n - 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...
#Ring
Ring
  # Project : Last letter-first letter   ready = [] names = ["audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpi...
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...
#Ruby
Ruby
class LastL_FirstL def initialize(names) @names = names.dup @first = names.group_by {|name| name[0]} @sequences = [] end   def add_name(seq) last_letter = seq[-1][-1] potentials = @first.include?(last_letter) ? (@first[last_letter] - seq) : [] if potentials.empty? @sequences << seq ...
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,...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method largestInt(il) public static ri = '' wa = '' -- put the list into an indexed string wa[0] = il.words loop ww = 1 to wa[...
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...
#jq
jq
# Define the helper function to take advantage of jq's tail-recursion optimization def lcm(m; n): def _lcm: # state is [m, n, i] if (.[2] % .[1]) == 0 then .[2] else (.[0:2] + [.[2] + m]) | _lcm end; [m, n, m] | _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...
#Julia
Julia
lcm(m,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 ...
#LFE
LFE
  (defun levenshtein-simple (('() str) (length str)) ((str '()) (length str)) (((cons a str1) (cons b str2)) (when (== a b)) (levenshtein-simple str1 str2)) (((= (cons _ str1-tail) str1) (= (cons _ str2-tail) str2)) (+ 1 (lists:min (list (levenshtein-simple str1 str2-tail) ...
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...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) every PrintCount(CountLetters(!A)) end   procedure CountLetters(fn) #: Return case insensitive count of letters K := table(0) if f := open(fn,"r") then { every c := !map(|read(f)) do if any(&lcase,c) then K[c] +:= 1 close(f) return K } else...
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 ...
#Sidef
Sidef
module LCG {   # Creates a linear congruential generator and remembers the initial seed. class Common(r) { has seed = r }   # LCG::Berkeley generates 31-bit integers using the same formula # as BSD rand(). class Berkeley < Common { method rand { self.r = ((1103515245 * self.r + 12345) & 0x7ff...
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)
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) every y := !([2000,1900,2012]|||arglist) do write("The year ",y," is ", leapyear(y) | "not ","a leap year.") end   procedure leapyear(year) #: determine if year is leap if (numeric(year) % 4 = 0 & year % 100 ~= 0) | (numeric(year) % 400 = 0) then return end
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#QBasic
QBasic
' Chaos: start at any point, this program uses the middle of the screen (or universe. One of six ' degrees of freedom (a direction) is chosen at random (by throwing a six-sided die), and a line ' is drawn from the old point to the new point in the direction indicated by the pip on the die. ' ...
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...
#REXX
REXX
/*REXX program using Knuth's algorithm S (a random sampling N of M items). */ parse arg trials size . /*obtain optional arguments from the CL*/ if trials=='' | trials=="," then trials= 100000 /*Not specified? Then use the default.*/ if size=='' | size=="," then size= ...
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...
#Dyalect
Dyalect
let xInc = [0, 1, -1, 0] let yInc = [-1, 0, 0, 1] let north = 0 let east = 1 let west = 2 let south = 3   let leftTurns = [ west, north, south, east ] let rightTurns = [ east, south, north, west ]   func move(ant) { ant.position.x += xInc[ant.direction] ant.position.y += yInc[ant.direction] }   func Array.Step...
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 ...
#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/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 ...
#Sidef
Sidef
func kronecker_product (a, b) { a ~X b -> map { _[0] ~X* _[1] } }   func kronecker_fractal(pattern, order=4) { var kronecker = pattern { kronecker = kronecker_product(kronecker, pattern) } * order return kronecker }   var vicsek = [[0,1,0], [1,1,1], [0,1,0]] var carpet = [[1,1,1], [1,0,1], [1,1,1]] var six ...
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...
#Go
Go
package main   import ( "fmt" "os" "strconv" "time" )   func main() { y := time.Now().Year() if len(os.Args) == 2 { if i, err := strconv.Atoi(os.Args[1]); err == nil { y = i } } for m := time.January; m <= time.December; m++ { d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour) d = d...
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...
#zkl
zkl
fcn lah(n,k,fact=fcn(n){ [1..n].reduce('*,1) }){ if(n==k) return(1); if(k==1) return(fact(n)); if(n<1 or k<1) return(0); (fact(n)*fact(n - 1)) /(fact(k)*fact(k - 1)) /fact(n - k) }
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...
#Rust
Rust
/// # Panics /// /// If string is empty. fn first_char(string: &str) -> char { string.chars().next().unwrap() }   /// # Panics /// /// If string is empty. fn first_and_last_char(string: &str) -> (char, char) { ( first_char(string), first_char(string.rmatches(|_: char| true).next().unwrap()), ...
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,...
#Nim
Nim
import algorithm, sequtils, strutils, sugar   proc maxNum(x: seq[int]): string = var c = x.mapIt($it) c.sort((x, y) => cmp(y&x, x&y)) c.join()   echo maxNum(@[1, 34, 3, 98, 9, 76, 45, 4]) echo maxNum(@[54, 546, 548, 60])
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,...
#OCaml
OCaml
let myCompare a b = compare (b ^ a) (a ^ b) let icsort nums = String.concat "" (List.sort myCompare (List.map string_of_int nums))
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...
#K
K
gcd:{:[~x;y;_f[y;x!y]]} lcm:{_abs _ x*y%gcd[x;y]}   lcm .'(12 18; -6 14; 35 0) 36 42 0   lcm/1+!20 232792560
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...
#Klingphix
Klingphix
:gcd { u v -- n } abs int swap abs int swap   [over over mod rot drop] [dup] while drop ;   :lcm { m n -- n } over over gcd rot swap div mult ;   12 18 lcm print nl { 36 }   "End " input
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 ...
#Liberty_BASIC
Liberty BASIC
'Levenshtein Distance translated by Brandon Parker '08/19/10 'from http://www.merriampark.com/ld.htm#VB 'No credit was given to the Visual Basic Author on the site :-(   Print LevenshteinDistance("kitten", "sitting") End   'Get the minum of three values Function Minimum(a, b, c) Minimum = Min(a, Min(b, c)) End Func...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "Letters.bas" 110 NUMERIC LETT(65 TO 90) 120 FOR I=65 TO 90 130 LET LETT(I)=0 140 NEXT 150 LET EOF=0 160 OPEN #1:"list.txt" 170 WHEN EXCEPTION USE IOERROR 180 DO 190 GET #1:A$ 200 LET A$=UCASE$(A$) 210 IF A$>="A" AND A$<="Z" THEN LET LETT(ORD(A$))=LETT(ORD(A$))+1 220 LOOP UNTIL EOF 230 END...
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 ...
#Sparkling
Sparkling
var states = { "BSD": 0, "MS": 0 };   function BSD_seed(n) { states.BSD = n; }   function BSD_rand() { return states.BSD = (1103515245 * states.BSD + 12345) % (1 << 31); }   function Microsoft_seed(n) { states.MS = n; }   function Microsoft_rand() { return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) ...
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 ...
#Standard_ML
Standard ML
local open Word32 in fun bsdLcg (seed : int) : int = toInt (andb (0w1103515245 * fromInt seed + 0w12345, 0wx7fffffff)) fun mscLcg (seed : word) : int * word = let val state = andb (0w214013 * seed + 0w2531011, 0wx7fffffff) in (toInt (>> (state, 0w16)), state) end end