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/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 ...
#Oforth
Oforth
: genLCG(a, c, m, seed) | ch | Channel newSize(1) dup send(seed) drop ->ch #[ ch receive a * c + m mod dup ch send drop ] ;
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)
#Dc
Dc
[0q]s0 [1q]s1   [ S. [ l. 4% 0!=0 ## if y % 4: return 0 l. 100% 0!=1 ## if y % 100: return 1 l. 400% 0!=0 ## if y % 400: return 0 1 ## return 1 ]x s.L. ]sL ## L = isleapYear()   [ Sy lyn [ is ]P ly lLx [not ] 0:y ...
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)
#Delphi.2FPascal
Delphi/Pascal
program TestLeapYear;   {$APPTYPE CONSOLE}   uses SysUtils;   var Year: Integer;   begin Write('Enter the year: '); Readln(Year); if IsLeapYear(Year) then Writeln(Year, ' is a Leap year') else Writeln(Year, ' is not a Leap year'); Readln; end.
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#BASIC256
BASIC256
global RtoD, DtoR RtoD = 180 / Pi DtoR = Pi / 180   global posX, posY, angulo posX = 170 : posY = 100 : angulo = 0   global ancho, alto ancho = 650 : alto = 650 graphsize ancho, alto   subroutine kochLado(longitud, fondo) if fondo = 0 then dx = cos(angulo*DtoR) * longitud dy = sin(angulo*DtoR) * longitud color r...
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Amazing_Hopper
Amazing Hopper
hopper src/kock_curve.com > kockcurve.svg or ./src/kock_curve.com > kockcurve.svg
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...
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h>   struct s_env { unsigned int n, i; size_t size; void *sample; };   void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * siz...
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...
#Action.21
Action!
DEFINE DIRN="0" DEFINE DIRE="1" DEFINE DIRS="2" DEFINE DIRW="3" DEFINE BLACK="1" DEFINE WHITE="2" DEFINE MAXX="159" DEFINE MAXY="95"   BYTE FUNC TurnLeft(BYTE dir) IF dir=DIRN THEN RETURN (DIRW) FI RETURN (dir-1)   BYTE FUNC TurnRight(BYTE dir) IF dir=DIRW THEN RETURN (DIRN) FI RETURN (dir+1)   PROC Dra...
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...
#F.23
F#
  // Integer exponentiation using Knuth power tree. Nigel Galloway: October 29th., 2020 let kT α=let n=Array.zeroCreate<int*int list>((pown 2 (α+1))+1) let fN g=let rec fN p=[yield g+p; if p>0 then let g,_=n.[p] in yield! fN g] in (g+g)::(fN (fst n.[g]))|>List.rev let fG g=[for α,β in g do for g in β ...
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 ...
#Arturo
Arturo
define :matrix [X][ print: [ result: "" loop this\X 'arr [ result: result ++ "[" ++ (join.with:" " map to [:string] arr 'item -> pad item 3) ++ "]\n" ] return result ] ]   kroneckerProduct: function [a,b][ M: size a\X,...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Lua
Lua
function write_array(a) io.write("[") for i=0,#a do if i>0 then io.write(", ") end io.write(tostring(a[i])) end io.write("]") end   function kosaraju(g) -- 1. For each vertex u of the graph, mark u as unvisited. Let l be empty. local size = #g   local vis ...
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 ...
#Factor
Factor
USING: io kernel math math.matrices.extras sequences ;   : mat-kron-pow ( m n -- m' ) 1 - [ dup kronecker-product ] times ;   : print-fractal ( m -- ) [ [ 1 = "*" " " ? write ] each nl ] each ;   { { 0 1 0 } { 1 1 1 } { 0 1 0 } } { { 1 1 1 } { 1 0 1 } { 1 1 1 } } { { 0 1 1 } { 0 1 0 } { 1 1 0 } } [ 3 mat-kron-p...
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...
#Haskell
Haskell
import Data.List (group) import Control.Monad (forM_)   replicateAtLeastOne :: Int -> a -> [a] replicateAtLeastOne n x = x : replicate (n-1) x   zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c] zipWithLazy f ~(x:xs) ~(y:ys) = f x y : zipWithLazy f xs ys   kolakoski :: [Int] -> [Int] kolakoski items = s where s = con...
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...
#Befunge
Befunge
":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v v2++1**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5< >:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v ^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6 >$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8 ^<# #"#"##"#"##!` +76:+1g00,+55,+*<
http://rosettacode.org/wiki/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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
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...
#Icon_and_Unicon
Icon and Unicon
global words   procedure main() words := table() every word := genwords(&input) do { /words[word[1]] := [] put(words[word[1]], word) } bP := [] every p := getPath(!!words,[]) do if *\p > *bP then bP := copy(p) write("Longest: ",*bP) every writes((!bP||" ")|"\n") end   pro...
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,...
#Ceylon
Ceylon
shared void run() {   function comparator(Integer x, Integer y) { assert (is Integer xy = Integer.parse(x.string + y.string), is Integer yx = Integer.parse(y.string + x.string)); return yx <=> xy; }   function biggestConcatenation({Integer*} ints) => "".join(ints.sort(comparator));   value test1 = {1, 34, 3,...
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...
#J
J
  Filter =: (#~`)(`:6) combinations =: <@#"1~ [: #: [: i. 2 ^ # permutations =: A.&i.~ ! f =: [: \:~ _ ". [: ; [: ({~ permutations@#)L:_1 }.@combinations test =: 0 = ([: +/ (|~ 10&#.inv))&>   test Filter f '12346789' 9867312 9812376 9782136 9781632 9723168 9718632 9678312 9617832 9617328 9283176 92781...
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Phix
Phix
puts(1,join_by(apply(true,sprintf,{{"%3d"},vslice(apply(apply(true,factors,{tagset(100),-1}),reverse),1)}),1,10,""))
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Picat
Picat
main => foreach(I in 1..100) printf("%2d%s",a(I), cond(I mod 10 == 0,"\n", " ")) end.   a(1) = 1. a(N) = Div => a(N,N//2,Div). a(N,I,I) :- N mod I == 0. a(N,I,Div) :- a(N,I-1,Div).
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...
#Common_Lisp
Common Lisp
CL-USER> (lcm 12 18) 36 CL-USER> (lcm 12 18 22) 396
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...
#Cowgol
Cowgol
include "cowgol.coh";   sub gcd(m: uint32, n: uint32): (r: uint32) is while n != 0 loop var t := m; m := n; n := t % n; end loop; r := m; end sub;   sub lcm(m: uint32, n: uint32): (r: uint32) is if m==0 or n==0 then r := 0; else r := m*n / gcd(m,n); end if...
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#zkl
zkl
fcn reducedLatinSquare(n,write=False){ if(n<=1) return(n); rlatin:=n.pump(List(), List.createLong(n,0).copy); // matrix of zeros foreach i in (n){ rlatin[0][i]=i+1 } // first row: (1,2,3..n)   count:=Ref(0); // recursive closure to compute reduced latin squares and count or print them rows,rsz := de...
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#REXX
REXX
/*REXX pgm finds integer sided triangles that satisfy Law of cosines for 60º, 90º, 120º.*/ parse arg os1 os2 os3 os4 . /*obtain optional arguments from the CL*/ if os1=='' | os1=="," then os1= 13; s1=abs(os1) /*Not specified? Then use the default.*/ if os2=='' | os2=="," then os2= 13; s2=abs(os2...
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 ...
#F.23
F#
  open System   let getInput (name : string) = Console.Write ("String {0}: ", name) Console.ReadLine ()   let levDist (strOne : string) (strTwo : string) = let strOne = strOne.ToCharArray () let strTwo = strTwo.ToCharArray ()   let (distArray : int[,]) = Array2D.zeroCreate (strOne.Length + 1) (strTw...
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...
#Draco
Draco
proc nonrec main() void: file() infile; [256] char linebuf; [256] word count; *char line; char c; byte i; word n; channel input text filech; channel input text linech;   for i from 0 upto 255 do count[i] := 0 od; line := &linebuf[0];   open(filech, infile, "unixdict.txt")...
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Smalltalk
Smalltalk
  | test |   test := [ :a :b :c | a*a+(b*b)=(c*c) ].   (1 to: 20) combinations: 3 atATimeDo: [ :x | (test valueWithArguments: x) ifTrue: [ ':-)' logCr: x ] ].   "output on Transcript: #(3 4 5) #(5 12 13) #(6 8 10) #(8 15 17) #(9 12 15) #(12 16 20)"  
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...
#Quackery
Quackery
[ 1 swap times [ i 1+ * ] ] is ! ( n --> n )   [ 0 swap times [ i ! + ] ] is !n ( n --> n )   say "First 11 left factorials:" cr 11 times [ i^ !n echo sp ] cr cr say "20 through 110 (inclusive) by tens:" cr 10 times [ i^ 2 + 10 * !n echo cr ] cr say "Digits in 1,000 through 10,000 by thousands:" c...
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...
#R
R
library(gmp)   left_factorial <- function(n) { if (n == 0) return(0) result <- as.bigz(0)   adder <- as.bigz(1) for (k in 1:n) { result <- result + adder adder <- adder * k } result }   digit_count <- function(n) { nchar(as.character(n)) }   for (n in 0:10) { cat("!",n," = ",sep = "") cat(as.character(lef...
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 ...
#PARI.2FGP
PARI/GP
BSDseed=Mod(1,1<<31); MSFTseed=Mod(1,1<<31); BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed); MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);
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)
#Draco
Draco
proc nonrec leap_year(word year) bool: year%400=0 or (year%4=0 and year%100/=0) corp   proc nonrec main() void: [15]word years = (1899, 1900, 1901, 1902, 1903, 1904, 1905, 1999, 2000, 2001, 2002, 2003, 2004, 2021, 2022); word i;   for i from 0 upto 14 do writeln(years[i], ...
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)
#DWScript
DWScript
function IsLeapYear(y : Integer) : Boolean; begin Result:= (y mod 4 = 0) and ( ((y mod 100) <> 0) or ((y mod 400) = 0) ); end;   const good : array [0..13] of Integer = [1600,1660,1724,1788,1848,1912,1972,2032,2092,2156,2220,2280,2344,2348]; const bad : array [0..13] of Integer = ...
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#AutoHotkey
AutoHotkey
gdip1() KochX := 0, KochY := 0 Koch(0, 0, A_ScreenWidth, A_ScreenHeight, 4, Arr:=[]) xmin := xmax := ymin := ymax := 0 for i, point in Arr { xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x xmax := point.x > xmax ? point.x : xmax ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y ymax :=...
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...
#C.2B.2B
C++
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime>   template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (st...
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...
#Ada
Ada
with Ada.Text_IO;   procedure Langtons_Ant is   Size: constant Positive := 100; -- change this to extend the playground   subtype Step is Integer range -1 .. +1;   procedure Right(N, W: in out Step) is Tmp: Step := W; begin W := - N; N := Tmp; end Right;   procedure Left(N, W: in out...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   var ( p = map[int]int{1: 0} lvl = [][]int{[]int{1}} )   func path(n int) []int { if n == 0 { return []int{} } for { if _, ok := p[n]; ok { break } var q []int for _, x := range lvl[0] { ...
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 ...
#AWK
AWK
  # syntax: GAWK -f KRONECKER_PRODUCT.AWK BEGIN { A[++a] = "1 2" ; B[++b] = "0 5" A[++a] = "3 4" ; B[++b] = "6 7" main("sample 1",1234) A[++a] = "0 1 0" ; B[++b] = "1 1 1 1" A[++a] = "1 1 1" ; B[++b] = "1 0 0 1" A[++a] = "0 1 0" ; B[++b] = "1 1 1 1" main("sample 2",3) exit(0) } function ...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
g = Graph[{0 -> 1, 1 -> 2, 2 -> 0, 3 -> 1, 3 -> 2, 3 -> 4, 4 -> 3, 4 -> 5, 5 -> 2, 5 -> 6, 6 -> 5, 7 -> 4, 7 -> 6, 7 -> 7}]; cc = ConnectedComponents[g] Catenate[ConstantArray[Min[#], Length[#]] & /@ SortBy[cc, First]]
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Nim
Nim
type Vertex = int Graph = seq[seq[Vertex]] Scc = seq[Vertex]   func korasaju(g: Graph): seq[Scc] =   var size = g.len visited = newSeq[bool](size) # All false by default. l = newSeq[Vertex](size) # All zero by default. x = size # Index for filling "l"...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub kosaraju { our(%k) = @_; our %g = (); our %h; my $i = 0; $g{$_} = $i++ for sort keys %k; $h{$g{$_}} = $_ for keys %g; # invert   our(%visited, @stack, @transpose, @connected); sub visit { my($u) = @_; unless ($...
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 ...
#Fortran
Fortran
program Kron_frac implicit none   interface function matkronpow(M, n) result(Mpowern) integer, dimension(:,:), intent(in) :: M integer, intent(in) :: n integer, dimension(size(M, 1)**n, size(M,2)**n) :: Mpowern end function matkronpow   function kron(A, B) result(M) integer, dime...
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...
#J
J
  NB. cyclic   create_cycle_=: 3 :0 I=: 0 A=: y N=: # A )   next_cycle_=: 3 :0 r=. A {~ N | I I=: >: I r )   NB. kolakoski   kolakoski =: 30&$: :(dyad define) NB. TERMS kolakoski ALPHABET c=. y conew'cycle' s=. i. 0 term=. 0 while. x > # s do. s=. (, ([: #~ next__c)`(term&{ # next__c)@.(term < #)) s term...
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...
#Java
Java
import java.util.Arrays;   public class Kolakoski { private static class Crutch { final int len; int[] s; int i;   Crutch(int len) { this.len = len; s = new int[len]; i = 0; }   void repeat(int count) { for (int j = 0; j...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   int main(int c, char *v[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w;   if (c < 2 || (y = atoi(v[1])) <= 1700) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6;   for(m = 0; m ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
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...
#J
J
pokenames=: ;:0 :0-.LF 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 ma...
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,...
#Clojure
Clojure
(defn maxcat [coll] (read-string (apply str (sort (fn [x y] (apply compare (map read-string [(str y x) (str x y)]))) coll))))   (prn (map maxcat [[1 34 3 98 9 76 45 4] [54 546 548 60]]))
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...
#Java
Java
public class LynchBell {   static String s = "";   public static void main(String args[]) { //Highest number with unique digits (no 0 or 5) int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); ...
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#PL.2FI
PL/I
largestProperDivisor: procedure options(main); lpd: procedure(n) returns(fixed); declare (n, i) fixed; if n <= 1 then return(1); do i=n-1 repeat(i-1) while(i>=1); if mod(n,i)=0 then return(i); end; end lpd;   declare i fixed; do i=1 to 100; put edit(lp...
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2,CH); END PUT$CHAR; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$3: PROCEDURE (N); DECLARE N BYTE; CAL...
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...
#D
D
import std.stdio, std.bigint, std.math;   T gcd(T)(T a, T b) pure nothrow { while (b) { immutable t = b; b = a % b; a = t; } return a; }   T lcm(T)(T m, T n) pure nothrow { if (m == 0) return m; if (n == 0) return n; return abs((m * n) / gcd(m, n)); }   void main() { ...
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Ruby
Ruby
grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c| sumaabb, ab = a*a + b*b, a*b case c*c when sumaabb then 90 when sumaabb - ab then 60 when sumaabb + ab then 120 end end   grouped.delete(nil) res = grouped.transform_values{|v| v.map(&:sort).uniq }   res.each do |k,v| puts "For...
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Wren
Wren
var squares13 = {} var squares10000 = {}   var initMaps = Fn.new { for (i in 1..13) squares13[i*i] = i for (i in 1..10000) squares10000[i*i] = i }   var solve = Fn.new { |angle, maxLen, allowSame| var solutions = [] for (a in 1..maxLen) { for (b in a..maxLen) { var lhs = a*a + b*b ...
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 ...
#Factor
Factor
USING: lcs prettyprint ; "kitten" "sitting" levenshtein .
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...
#EchoLisp
EchoLisp
  ;; bump count when letter added (define (hash-counter hash key ) ;; (set! key (string-downcase key)) - if ignore case wanted (putprop hash (1+ (or (getprop hash key) 0 )) key))   ;; apply to exploded string ;; and sort result (define (hash-compare a b) ( < (first a) (first b))) (define (count-letters hash strin...
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Stata
Stata
function grid(n,p) { return(colshape(J(1,p,1::n),1),J(n,1,1::p)) }   n = 20 a = grid(n,n) a = a,sqrt(a[.,1]:^2+a[.,2]:^2) a[selectindex(floor(a[.,3]):==a[.,3] :& a[.,3]:<=n),]
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#SuperCollider
SuperCollider
  var pyth = { |n| all {: [x,y,z], x <- (1..n), y <- (x..n), z <- (y..n), (x**2) + (y**2) == (z**2) } };   pyth.(20) // example call
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...
#Racket
Racket
#lang racket (define ! (let ((rv# (make-hash))) (λ (n) (hash-ref! rv# n (λ () (if (= n 0) 1 (* n (! (- n 1)))))))))   (define (!n n)  ;; note that in-range n is from 0 to n-1 inclusive (for/sum ((k (in-range n))) (! k)))   (define (dnl. s) (for-each displayln s)) (dnl "Display the left factorials for:" "zero thr...
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...
#Raku
Raku
sub prefix:<!> ($k) { (constant l = 0, |[\+] 1, (|[\*] 1..*))[$k] }   $ = !10000; # Pre-initialize   .say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d = %s", $_, !$_ }; .say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars !$_ };
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 ...
#Pascal
Pascal
Program LinearCongruentialGenerator(output); {$mode iso} var x1, x2: int64;   function bsdrand: cardinal; const a = 1103515245; c = 12345; m = 2147483648; begin x1 := (a * x1 + c) mod m; bsdrand := x1; end;   function msrand: cardinal; const a = 214013; c = 2531011; m = 214748...
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)
#Dyalect
Dyalect
func isLeap(y) { if y % 100 == 0 { y % 400 == 0 } else { y % 4 == 0 } }   print(isLeap(1984))
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#C
C
  #include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h>   #define pi M_PI   typedef struct{ double x,y; }point;   void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3;   if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p...
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...
#Clojure
Clojure
(defn s-of-n-fn-creator [n] (fn [[sample iprev] item] (let [i (inc iprev)] (if (<= i n) [(conj sample item) i] (let [r (rand-int i)] (if (< r n) [(assoc sample r item) i] [sample i]))))))   (def s-of-3-fn (s-of-n-fn-creator 3))   (->> #(reduce s-of-3-fn [[] ...
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...
#Aime
Aime
void ant(integer x, y, d, list map) { while (-1 < x && x < 100 && -1 < y && y < 100) { integer e, p, w; data b;   b = map[y]; w = b[x >> 3]; p = 1 << (7 - (x & 7)); b[x >> 3] = w ^ p;   d += w & p ? 1 : 3;   e = d & 1; set(e, $e + ((d & 2) - 1)...
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...
#Groovy
Groovy
class PowerTree { private static Map<Integer, Integer> p = new HashMap<>() private static List<List<Integer>> lvl = new ArrayList<>()   static { p[1] = 0   List<Integer> temp = new ArrayList<Integer>() temp.add 1 lvl.add temp }   private static List<Integer> path(int ...
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 ...
#BQN
BQN
KProd ← ∾·<⎉2 ×⌜
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 ...
#C
C
  #include<stdlib.h> #include<stdio.h>   int main(){   char input[100],output[100]; int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol; double **matrixA,**matrixB,**matrixC;   printf("Enter full path of input file : "); fscanf(stdin,"%s",input);   printf("Enter full path of output file : "); fscanf(stdi...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Phix
Phix
with javascript_semantics sequence visited, l, t, c procedure visit(sequence g, integer u) if not visited[u] then visited[u] = true for i=1 to length(g[u]) do integer v = g[u][i] visit(g,v) t[v] = deep_copy(t[v]) & u end for l &= u end if en...
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 ...
#gnuplot
gnuplot
  ## KPF.gp 4/8/17 aev ## Plotting 3 KPF pictures. ## dat-files are PARI/GP generated output files: #cd 'C:\gnupData'   ##PKF1 from PARI/GP created file pkf1.dat ttl = "Vicsec fractal"; clr = '"blue"'; filename = "pkf1"; load "plotff.gp"   ##PKF2 from PARI/GP created file pkf2.dat ttl = "Sierpinski carpet fractal"; c...
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...
#jq
jq
def cycle: def c: .[], c; c;
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...
#Julia
Julia
function kolakoski(vec, len) seq = Vector{Int}() k = 0 denom = length(vec) while length(seq) < len n = vec[k % denom + 1] k += 1 seq = vcat(seq, repeat([n], k > length(seq) ? n : seq[k])) end seq[1:len] end   function iskolakoski(seq) count = 1 rle = Vector{Int}()...
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...
#Kotlin
Kotlin
// Version 1.2.41   fun IntArray.nextInCycle(index: Int) = this[index % this.size]   fun IntArray.kolakoski(len: Int): IntArray { val s = IntArray(len) var i = 0 var k = 0 while (true) { s[i] = this.nextInCycle(k) if (s[k] > 1) { repeat(s[k] - 1) { if (++i == ...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq;   namespace RosettaCode.LastFridaysOfYear { internal static class Program { private static IEnumerable<DateTime> LastFridaysOfYear(int year) { for (var month = 1; month <= 12; month++) ...
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...
#Haskell
Haskell
import Text.Printf (printf) import Control.Monad (when)   factorial :: Integral n => n -> n factorial 0 = 1 factorial n = product [1..n]   lah :: Integral n => n -> n -> n lah n k | k == 1 = factorial n | k == n = 1 | k > n = 0 | k < 1 || n < 1 = 0 | otherwise = f n `div` f k `div` factorial (n - k) wh...
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...
#Java
Java
// derived from C final class LastLetterFirstLetter { static int maxPathLength = 0; static int maxPathLengthCount = 0; static final StringBuffer maxPathExample = new StringBuffer(500);   static final String[] names = {"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carr...
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,...
#Common_Lisp
Common Lisp
  (defun int-concat (ints) (read-from-string (format nil "~{~a~}" ints)))   (defun by-biggest-result (first second) (> (int-concat (list first second)) (int-concat (list second first))))   (defun make-largest-int (ints) (int-concat (sort ints #'by-biggest-result)))  
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,...
#D
D
import std.stdio, std.algorithm, std.conv, std.array, permutations2;   auto maxCat1(in int[] arr) pure @safe { return arr.to!(string[]).permutations.map!join.reduce!max; }   auto maxCat2(in int[] arr) pure nothrow @safe { return arr.to!(string[]).sort!q{b ~ a < a ~ b}.join; }   auto maxCat3(in int[] arr) /*pure...
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...
#jq
jq
  def has_unique_digits: tostring | explode | label $out | (foreach map([.] | implode)[] as $d ({}; .[$d] += 1; select(.[$d] > 1) | (0, break $out))) // true | . == true;   # exclude numbers with a 0 def is_divisible_by_all_its_digits: . as $n | tostring | explode | map([.] | implode...
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...
#Julia
Julia
function main() num = 9876432 dif = [4, 2, 2, 2] local k = 1 @label start local str = dec(num) for (i, ch) in enumerate(str) if ch in ('0', '5') || num % (ch - '0') != 0 num -= dif[k] k = (k + 1) % 4 + 1 @goto start end for j in i+1:end...
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#PureBasic
PureBasic
Procedure.i lpd(v.i) For i=v/2 To 1 Step -1 If v%i=0 : ProcedureReturn i : EndIf Next ProcedureReturn 1 EndProcedure   If OpenConsole("") For i=1 To 100 Print(RSet(Str(lpd(i)),3)) If i%10=0 : PrintN("") : EndIf Next Input() EndIf
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Python
Python
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1   for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
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...
#Dart
Dart
  main() { int x=8; int y=12; int z= gcd(x,y); var lcm=(x*y)/z; print('$lcm'); }   int gcd(int a,int b) { if(b==0) return a; if(b!=0) return gcd(b,a%b); }    
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...
#Delphi
Delphi
PrintLn(Lcm(12, 18));
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#XPL0
XPL0
proc LawCos(Eqn); int Eqn; int Cnt, A, B, C;   proc Show; [Cnt:= Cnt+1; IntOut(0, A); ChOut(0, ^ ); IntOut(0, B); ChOut(0, ^ ); IntOut(0, C); CrLf(0); ];   [Cnt:= 0; for A:= 1 to 13 do for B:= 1 to A do for C:= 1 to 13 do case Eqn of 1: if A*A + B*B ...
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#zkl
zkl
fcn tritri(N=13){ sqrset:=[0..N].pump(Dictionary().add.fp1(True),fcn(n){ n*n }); tri90, tri60, tri120 := List(),List(),List(); foreach a,b in ([1..N],[1..a]){ aa,bb := a*a,b*b; ab,c  := a*b, aa + bb - ab; // 60* if(sqrset.holds(c)){ tri60.append(abc(a,b,c)); continue; }   c=aa + bb; /...
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 ...
#Forth
Forth
: levenshtein ( a1 n1 a2 n2 -- n3) dup \ if either string is empty, difference if \ is inserting all chars from the other 2>r dup if 2dup 1- chars + c@ 2r@ 1- chars + c@ = if 1- 2r> 1- recurse exi...
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...
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make -- Read from the file and print frequencies. local file: PLAIN_TEXT_FILE do create file.make_open_read("input.txt") file.read_stream(file.count) file.close across get_frequencies(file.last_string) as f loop print(f.ke...
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Swift
Swift
typealias F1 = (Int) -> [(Int, Int, Int)] typealias F2 = (Int) -> Bool   func pythagoreanTriples(n: Int) -> [(Int, Int, Int)] { (1...n).flatMap({x in (x...n).flatMap({y in (y...n).filter({z in x * x + y * y == z * z } as F2).map({ (x, y, $0) }) } as F1) } as F1) }   print(pythagoreanTrip...
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Tcl
Tcl
package require Tcl 8.5   # from http://wiki.tcl.tk/12574 proc lcomp {expression args} { # Check the number of arguments. if {[llength $args] < 2} { error "wrong # args: should be \"lcomp expression var1 list1\  ?... varN listN? ?condition?\"" }   # Extract condition from $args, or u...
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...
#REXX
REXX
/*REXX program computes/display the left factorial (or its dec. width) of N (or a range)*/ parse arg bot top inc . /*obtain optional arguments from the CL*/ if bot=='' | bot=="," then bot= 1 /*Not specified: Then use the default.*/ if top=='' | top=="," then top= bot ...
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 ...
#Perl
Perl
use strict; package LCG;   use overload '0+' => \&get;   use integer; sub gen_bsd { (1103515245 * shift() + 12345) % (1 << 31) }   sub gen_ms { my $s = (214013 * shift() + 2531011) % (1 << 31); $s, $s / (1 << 16) }   sub set { $_[0]->{seed} = $_[1] } # srand sub get { my $o = shift; ($o->{seed}, my $r) = $o->{met...
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)
#Ela
Ela
isLeap y | y % 100 == 0 = y % 400 == 0 | else = y % 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)
#Elixir
Elixir
leap_year? = fn(year) -> :calendar.is_leap_year(year) end IO.inspect for y <- 2000..2020, leap_year?.(y), do: y
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#C.2B.2B
C++
// See https://en.wikipedia.org/wiki/Koch_snowflake #include <fstream> #include <iostream> #include <vector>   constexpr double sqrt3_2 = 0.86602540378444; // sqrt(3)/2   struct point { double x; double y; };   std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.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...
#CoffeeScript
CoffeeScript
  s_of_n_creator = (n) -> arr = [] cnt = 0 (elem) -> cnt += 1 if cnt <= n arr.push elem else pos = Math.floor(Math.random() * cnt) if pos < n arr[pos] = elem arr.sort()   sample_size = 3 range = [0..9] num_trials = 100000   counts = {}   for digit in range counts[di...
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...
#Common_Lisp
Common Lisp
(defun s-n-creator (n) (let ((sample (make-array n :initial-element nil)) (i 0)) (lambda (item) (if (<= (incf i) n) (setf (aref sample (1- i)) item) (when (< (random i) n) (setf (aref sample (random n)) item))) sample)))   (defun algorithm-s () (let ((*random-stat...
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...
#ALGOL_68
ALGOL 68
BEGIN # size of board for Langton's ant # INT max board = 100; [ 1 : max board, 1 : max board ]CHAR board; # start with the board all white # CHAR white = " ", black = "#"; FOR r TO 1 UPB board DO FOR c TO 2 UPB board DO board[ r, c ] := white OD OD; # possible ant directions # INT head ...
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...
#Haskell
Haskell
{-# LANGUAGE ScopedTypeVariables #-}   module Rosetta.PowerTree ( Natural , powerTree , power ) where   import Data.Foldable (toList) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.List (foldl') impo...
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 ...
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class KroneckerProduct { public static void Main() { int[,] left = { {1, 2}, {3, 4} }; int[,] right = { {0, 5}, {6, 7} }; Print(Multiply(left, right));   lef...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Python
Python
def kosaraju(g): class nonlocal: pass   # 1. For each vertex u of the graph, mark u as unvisited. Let l be empty. size = len(g)   vis = [False]*size # vertexes that have been visited l = [0]*size nonlocal.x = size t = [[]]*size # transpose graph   def visit(u): if not vis[u]: ...
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Racket
Racket
#lang racket   (require racket/dict)   ;; G is a dictionary of vertex -> (list vertex) (define (Kosuraju G) (letrec ((vertices (remove-duplicates (append (dict-keys G) (append* (dict-values G))))) (visited?-dict (make-hash)) ; or any mutable dict type (assigned-dict (make-hash)) ; or any mutable d...