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/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... | #Lua | Lua | -- BUILDING:
pokemon = [[
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 mam... |
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,... | #Fortran | Fortran | SUBROUTINE SWAP(A,B) !Why can't the compiler supply these!
INTEGER A,B,T
T = B
B = A
A = T
END
SUBROUTINE BIGUP(TEXT,N) !Outputs the numbers in TEXT to give the biggest number.
CHARACTER*(*) TEXT(*) !The numbers as text, aligned left.
INTEGER N !The numb... |
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... | #Phix | Phix | with javascript_semantics
integer magic = 9*8*7,
high = 9876432,
n = high-mod(high,magic)
sequence seen
while true do
string s = sprintf("%d",n)
seen = {1,0,0,0,0,1,0,0,0,0}
for j=1 to length(s) do
seen[s[j]-'0'+1] += 1
end for
if max(seen)=1 then exit end if
n -= magic... |
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 .
| #True_BASIC | True BASIC | PRINT "El mayor divisor propio de n es:"
PRINT
PRINT " 1 1";
FOR i = 3 TO 100
FOR j = i-1 TO 1 STEP -1
IF remainder(i, j) = 0 THEN
PRINT USING$("###", j);
EXIT FOR
END IF
NEXT j
IF remainder(i, 10) = 0 THEN PRINT
NEXT i
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 .
| #Vlang | Vlang | fn largest_proper_divisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
fn main() {
println("The largest proper divisors for numbers in the interval [1, 100] are:")
print(" 1 ")
for n := 2; n <= 100; n++ {
if n%2 == 0 {
... |
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 .
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
System.print("The largest proper divisors for numbers in the interval [1, 100] are:")
System.write(" 1 ")
for (n in 2..100) {
if (n % 2 == 0) {
Fmt.write("$2d ", n / 2)
} else {
Fmt.write("$2d ", Int.properDivisors(n)[-1])
}
if (n % 10 ==... |
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... | #ERRE | ERRE | PROGRAM LCM
PROCEDURE GCD(A,B->GCD)
LOCAL C
WHILE B DO
C=A
A=B
B=C MOD B
END WHILE
GCD=ABS(A)
END PROCEDURE
PROCEDURE LCM(M,N->LCM)
IF M=0 OR N=0 THEN
LCM=0
EXIT PROCEDURE
ELSE
GCD(M,N->GCD)
LCM=ABS(M*N)/GCD
END IF
END PROCEDURE... |
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... | #Euphoria | Euphoria | function gcd(integer m, integer n)
integer tmp
while m do
tmp = m
m = remainder(n,m)
n = tmp
end while
return n
end function
function lcm(integer m, integer n)
return m / gcd(m, n) * n
end function |
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 ... | #FutureBasic | FutureBasic | window 1
local fn LevenshteinDistance( aStr as Str255, bStr as Str255 ) as long
dim as long m, n, i, j, min, k, l
dim as long distance( 255, 255 )
m = len$(aStr)
n = len$(bStr)
for i = 0 to m
distance( i, 0 ) = i
next
for j = 0 to n
distance( 0, j ) = j
next
for j = 1 to n
for i ... |
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... | #Euphoria | Euphoria |
-- LetterFrequency.ex
-- Count frequency of each letter in own source code.
include std/console.e
include std/io.e
include std/text.e
sequence letters = repeat(0,26)
sequence content = read_file("LetterFrequency.ex")
content = lower(content)
for i = 1 to length(content) do
if content[i] > 96 and content[i]... |
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... | #zkl | zkl | var n=20;
[[(x,y,z); [1..n]; {[x..n]}; {[y..n]},{ x*x + y*y == z*z }; _]]
//-->L(L(3,4,5),L(5,12,13),L(6,8,10),L(8,15,17),L(9,12,15),L(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... | #Scheme | Scheme |
(import (scheme base) ;; library imports in R7RS style
(scheme write)
(srfi 1 lists))
(define (factorial n)
(fold * 1 (iota n 1)))
(define (left-factorial n)
(fold + 0 (map factorial (iota n))))
(define (show i r) ; to pretty print the results
(display "!") (display i) (display " ") (d... |
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
... | #PicoLisp | PicoLisp | (zero *BsdSeed *MsSeed)
(de bsdRand ()
(setq *BsdSeed
(& (+ 12345 (* 1103515245 *BsdSeed)) `(dec (** 2 31))) ) )
(de msRand ()
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 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
... | #PL.2FI | PL/I |
(nofixedoverflow, nosize):
LCG: procedure options (main);
declare i fixed binary;
put skip list ('BSD', 'MS');
do i = 1 to 20;
put skip list (BSD(), MS());
end;
bsd: procedure returns (fixed binary (31));
declare const fixed binary static initial (12345);
declare s fixed binary (31) stat... |
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)
| #Euphoria | Euphoria | function isLeapYear(integer year)
return remainder(year,4)=0 and remainder(year,100)!=0 or remainder(year,400)=0
end function |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Haskell | Haskell | import Data.Bifunctor (bimap)
import Text.Printf (printf)
------------------------ KOCH CURVE ----------------------
kochSnowflake ::
Int ->
(Float, Float) ->
(Float, Float) ->
[(Float, Float)]
kochSnowflake n a b =
concat $
zipWith (kochCurve n) points (xs <> [x])
where
points@(x : xs) = [a, equi... |
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... | #Haskell | Haskell |
import Control.Monad.Random
import Control.Monad.State
import qualified Data.Map as M
import System.Random
-- s_of_n_creator :: Int -> a -> RandT StdGen (State (Int, [a])) [a]
s_of_n_creator :: Int -> a -> StateT (Int, [a]) (Rand StdGen) [a]
s_of_n_creator n v = do
(i, vs) <- get
let i' = i + 1
if i' <= n
... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #BBC_BASIC | BBC BASIC |
REM Implementation of Langton's ant for Rosetta Code
fieldsize%=100
REM Being pedantic, this will actually result in a field of 101 square,
REM since arrays start at 0, and my implementation allows them to use it
DIM field&(fieldsize%,fieldsize%) : REM variables with an & suffix are by... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[NextStep, TreePow]
NextStep[pows_List] := Module[{maxlen, sel, new, vals, knows},
maxlen = Max[Length /@ pows[[All, "Path"]]];
sel = Select[pows, Length[#["Path"]] == maxlen &];
knows = pows[[All, "P"]];
new = {};
Do[
vals = s["P"] + s["Path"];
vals = DeleteCases[vals, Alternatives @@ Join[s["P... |
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... | #Nim | Nim | import tables
import bignum
type
Id = Natural # Node identifier (= exponent value).
Tree = object
parents: Table[Id, Id] # Mapping node id -> parent node id.
lastLevel: seq[Id] # List of node ids in current last level.
func initTree(): Tree =
## Return an initialized tree.
const Root ... |
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 ... | #FreeBASIC | FreeBASIC | ' version 06-04-2017
' compile with: fbc -s console
Sub kronecker_product(a() As Long, b() As Long, frmt As String = "#")
Dim As Long i, j, k, l
Dim As Long la1 = LBound(a, 1) : Dim As Long ua1 = UBound(a, 1)
Dim As Long la2 = LBound(a, 2) : Dim As Long ua2 = UBound(a, 2)
Dim As Long lb1 = LBound(b,... |
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... | #Wren | Wren | var kosaraju = Fn.new { |g|
var gc = g.count
// 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
var vis = List.filled(gc, false)
var l = List.filled(gc, 0)
var x = gc // index for filling l in reverse order
var t = List.filled(gc, null) // transpose g... |
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 ... | #JavaScript | JavaScript |
// KPF.js 6/23/16 aev
// HFJS: Plot any matrix mat (filled with 0,1)
function pmat01(mat, color) {
// DCLs
var cvs = document.getElementById('canvId');
var ctx = cvs.getContext("2d");
var w = cvs.width; var h = cvs.height;
var m = mat[0].length; var n = mat.length;
// Cleaning canvas and setting plotting... |
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... | #Raku | Raku | sub kolakoski (*@seed) {
my $k = @seed[0] == 1 ?? 1 !! 0;
my @k = flat @seed[0] == 1 ?? (1, @seed[1] xx @seed[1]) !! @seed[0] xx @seed[0],
{ $k++; @seed[$k % @seed] xx @k[$k] } … *
}
sub rle (*@series) { @series.join.subst(/((.)$0*)/, -> { $0.chars }, :g).comb».Int }
# Testing
for [1, 2], 20,
[2, ... |
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... | #Common_Lisp | Common Lisp | (defun friday-before (year month day)
(let*
((timestamp (encode-universal-time 0 0 12 day month year))
(weekday (nth 6 (multiple-value-list (decode-universal-time timestamp))))
(fri (- timestamp (* (+ (mod (+ weekday 2) 7) 1) 86400))))
(multiple-value-bind (_ _ _ d m y) (decode-universal-time fri)
(l... |
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... | #Phix | Phix | with javascript_semantics
include mpfr.e
constant lim = 100,
lim1 = lim+1,
last = 12
sequence l = repeat(0,lim1)
for n=1 to lim1 do
l[n] = mpz_inits(lim1)
mpz_set_si(l[n][n],1)
if n!=2 then
mpz_fac_ui(l[n][2],n-1)
end if
end for
mpz {t, m100} = mpz_inits(2)
for n=1 to lim do... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | longestChain[list_] :=
NestWhileList[
Append @@@
Select[DeleteDuplicatesBy[
Tuples[{#, list}], {#[[1, 1]], #[[2]]} &], ! MemberQ @@ # &&
StringTake[#[[1, -1]], -1] == StringTake[#[[2]], 1] &] &,
List /@ list, # != {} &][[-2, 1]];
Print[longestChain[{"audino", "bagon", "baltoy", "ban... |
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,... | #FreeBASIC | FreeBASIC | #define MAXDIGITS 8
function catint( a as string, b as string ) as uinteger
return valint(a+b)
end function
function grt( a as string, b as string ) as boolean
return catint(a, b)>catint(b, a)
end function
sub shellsort( a() as string )
'quick and dirty shellsort, not the focus of this exercise
di... |
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... | #Prolog | Prolog | % Find the largest integer divisible by all it's digits, with no digit repeated.
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% We go for a generic algorithm here. Test for divisibility is done by
% calculating the least common multiplier for all digits, and testing
% whether a... |
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 .
| #Yabasic | Yabasic | print "El mayor divisor propio de n es:\n"
print " 1 1 ";
for i = 3 to 100
for j = i-1 to 1 step -1
If mod(i, j) = 0 then print j using "##"; : break : fi
next j
if mod(i, 10) = 0 then print : fi
next i
print
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 .
| #X86_Assembly | X86 Assembly | 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 org 100h ;.com program starts here
5
6 ;bl... |
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... | #Excel | Excel | =LCM(A1:J1) |
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... | #Ezhil | Ezhil |
## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்
நிரல்பாகம் மீபொம(எண்1, எண்2)
@(எண்1 == எண்2) ஆனால்
## இரு எண்களும் சமம் என்பதால், மீபொம அந்த எண்ணேதான்
பின்கொடு எண்1
@(எண்1 > எண்2) இல்லைஆனால்
சிறியது = எண்2
பெரியது = எண்1
இல்ல... |
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 ... | #Go | Go | package main
import "fmt"
func main() {
fmt.Println(ld("kitten", "sitting"))
}
func ld(s, t string) int {
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = 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... | #F.23 | F# | let alphabet =
['A'..'Z'] |> Set.ofList
let letterFreq (text : string) =
text.ToUpper().ToCharArray()
|> Array.filter (fun x -> alphabet.Contains(x))
|> Seq.countBy (fun x -> x)
|> Seq.sort
let v = "Now is the time for all good men to come to the aid of the party"
let res = letterFreq v
for ... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const func bigInteger: leftFact (in integer: n) is func
result
var bigInteger: leftFact is 0_;
local
var bigInteger: factorial is 1_;
var integer: i is 0;
begin
for i range 1 to n do
leftFact +:= factorial;
factorial *:= bigInteger co... |
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... | #Sidef | Sidef | say 20.of { .left_factorial } |
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
... | #PowerShell | PowerShell |
Function msstate{
Param($current_seed)
Return (214013*$current_seed+2531011)%2147483648}
Function randMS{
Param($MSState)
Return [int]($MSState/65536)}
Function randBSD{
Param($BSDState)
Return (1103515245*$BSDState+12345)%2147483648}
Write-Host "MS: seed=0"
$seed=0 #initialize seed
... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Excel | Excel |
=IF(OR(NOT(MOD(A1,400)),AND(NOT(MOD(A1,4)),MOD(A1,100))),"Leap Year","Not a Leap Year")
|
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #F.23 | F# | let isLeapYear = System.DateTime.IsLeapYear
assert isLeapYear 1996
assert isLeapYear 2000
assert not (isLeapYear 2001)
assert not (isLeapYear 1900) |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Koch.bas"
110 OPTION ANGLE DEGREES
120 SET 22,1:SET 23,0:SET 24,42:SET 25,26
130 OPEN #101:"video:"
140 DISPLAY #101:AT 1 FROM 1 TO 26
150 SET PALETTE 0,252
160 PLOT 300,700;ANGLE 0;
170 FOR I=1 TO 3
180 CALL KOCH(0,800)
190 PLOT RIGHT 120;
200 NEXT
210 DEF KOCH(A,D)
220 IF D>12 THEN
230 LET D=D... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #J | J | seg=: [ + [: +/\ (0,1r3*1,(^j.(,-)_2 o.1r2),1) * -~
koch=: [: ,/ 2 seg/\ ]
require'plot'
tri=: ^ j. 4r3 * (_2 o. 0) * i._4
plot koch ^: 5 tri |
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... | #Icon_and_Unicon | Icon and Unicon | import Utils
procedure main(A)
freq := table(0)
every 1 to (\A[2] | 100000)\1 do {
s_of_n := s_of_n_creator(\A[1] | 3)
every sample := s_of_n(0 to 9)
every freq[!sample] +:= 1
}
every write(i := 0 to 9,": ",right(freq[i],6))
end
procedure s_of_n_creator(n)
items := []... |
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... | #J | J | s_of_n_creator=: 1 :0
ctx=: conew&'inefficient' m
s_of_n__ctx
)
coclass'inefficient'
create=:3 :0
N=: y
ITEMS=: ''
K=:0
)
s_of_n=:3 :0
K=: K+1
if. N>:#ITEMS do.
ITEMS=: ITEMS,y
else.
if. (N%K)>?0 do.
ITEMS=: ((<<<?N){ITEMS),y
else.
ITEMS
end.... |
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... | #bc | bc | define o() {
auto i, j
"P1 "
w
h
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
a[j * w + i]
}
}
}
define l(w, h, x, y) {
auto a[], d, i, x[], y[]
/* d represents one of the four possible directions:
* 0
* ⇑
* ... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Perl | Perl | my @lvl = [1];
my %p = (1 => 0);
sub path {
my ($n) = @_;
return () if ($n == 0);
until (exists $p{$n}) {
my @q;
foreach my $x (@{$lvl[0]}) {
foreach my $y (path($x)) {
my $z = $x + $y;
last if exists($p{$z});
$p{$z} = $x;
... |
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 ... | #Frink | Frink | a = [[1,2],[3,4]]
b = [[0,5],[6,7]]
println[formatProd[a,b]]
c = [[0,1,0],[1,1,1],[0,1,0]]
d = [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
println[formatProd[c,d]]
formatProd[a,b] := formatTable[[[formatMatrix[a], "\u2297", formatMatrix[b], "=", formatMatrix[KroneckerProduct[a,b]]]]]
KroneckerProduct[a, b] :=
{
[m,n] = a.... |
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 ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strings"
)
type uintMatrix [][]uint
func (m uintMatrix) String() string {
var max uint
for _, r := range m {
for _, e := range r {
if e > max {
max = e
}
}
}
w := len(fmt.Sprint(max))
b := &strings.Bui... |
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... | #zkl | zkl | const VISITED=0,ASSIGNED=1;
fcn visit(u,G,L){ // u is ((visited,assigned), (id,edges))
u0:=u[0];
if(u0[VISITED]) return();
u0[VISITED]=True;
foreach idx in (u[1][1,*]){ visit(G[idx],G,L) } // vist out-neighbours
L.insert(0,u); // prepend u to L
}
fcn assign(u,root,G){ // u as above, root is a list of ... |
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 ... | #Julia | Julia | function matkronpow(M::Matrix, n::Int)
P = copy(M)
for i in 1:n P = kron(P, M) end
return P
end
function fracprint(M::Matrix)
for i in 1:size(M, 1)
for j in 1:size(M, 2)
print(M[i, j] == 1 ? '*' : ' ')
end
println()
end
end
M = [0 1 0; 1 1 1; 0 1 0]
matkronpow... |
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... | #Ruby | Ruby | def create_generator(ar)
Enumerator.new do |y|
cycle = ar.cycle
s = []
loop do
t = cycle.next
s.push(t)
v = s.shift
y << v
(v-1).times{s.push(t)}
end
end
end
def rle(ar)
ar.slice_when{|a,b| a != b}.map(&:size)
end
[[20, [1,2]],
[20, [2,1]],
[30, [1,3,1,2]],
[... |
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... | #D | D | import std.stdio, std.datetime, std.traits;
void lastFridays(in uint year) {
auto date = Date(year, 1, 1);
foreach (_; [EnumMembers!Month]) {
date.day(date.daysInMonth);
date.roll!"days"(-(date.dayOfWeek + 2) % 7);
writeln(date);
date.add!"months"(1, AllowDayOverflow.no);
}... |
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... | #PicoLisp | PicoLisp | (de fact (N)
(if (=0 N)
1
(* N (fact (dec N))) ) )
(de lah (N K)
(cond
((=1 K) (fact N))
((= N K) 1)
((> K N) 0)
((or (> 1 N) (> 1 K)) 0)
(T
(/
(* (fact N) (fact (dec N)))
(* (fact K) (fact (dec K)))
(fact (- N K)) ) ) ) )
(pri... |
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... | #Prolog | Prolog | % Reference: https://en.wikipedia.org/wiki/Lah_number#Identities_and_relations
:- dynamic unsigned_lah_number_cache/3.
unsigned_lah_number(N, N, 1):-!.
unsigned_lah_number(_, 0, 0):-!.
unsigned_lah_number(N, K, 0):-
K > N,
!.
unsigned_lah_number(N, K, L):-
unsigned_lah_number_cache(N, K, L),
!.
unsigned_lah_num... |
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... | #Nim | Nim | import tables
const Names = ["audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor",
"carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino",
"emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus",
"heatmor", "heatra... |
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,... | #Gambas | Gambas | 'Largest int from concatenated ints
Public Sub Main()
Dim iList1 As Integer[] = [1, 34, 3, 98, 9, 76, 45, 4] 'Integer list 1
Dim iList2 As Integer[] = [54, 546, 548, 60] 'Integer list 2
Calc(iList1) 'Send List 1 to Calc routine
Calc(iList2) ... |
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... | #Python | Python | '''Largest number divisible by its digits'''
from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)
# main :: IO ()
def main():
'''Tests'''
# (Division by zero is not an option, so 0 and 5 are omitted)
digits = [1, 2, 3, 4, 6, 7, 8, 9]
# Least common ... |
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 .
| #XPL0 | XPL0 | int N, D;
[for N:= 1 to 100 do
[D:= if N=1 then 1 else N/2;
while rem(N/D) do D:= D-1;
if D<10 then ChOut(0, ^ );
IntOut(0, D);
if rem(N/10) = 0 then CrLf(0) else ChOut(0, ^ );
];
] |
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... | #F.23 | F# | let rec gcd x y = if y = 0 then abs x else gcd y (x % y)
let lcm x y = x * y / (gcd x 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... | #Factor | Factor | USING: math.functions prettyprint ;
26 28 lcm . |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Groovy | Groovy | def distance(String str1, String str2) {
def dist = new int[str1.size() + 1][str2.size() + 1]
(0..str1.size()).each { dist[it][0] = it }
(0..str2.size()).each { dist[0][it] = it }
(1..str1.size()).each { i ->
(1..str2.size()).each { j ->
dist[i][j] = [dist[i - 1][j] + 1, dist[i][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... | #Factor | Factor | USING: hashtables locals io assocs kernel io.encodings.utf8 io.files formatting ;
IN: count-letters
<PRIVATE
: count-from-stream ( -- counts )
52 <hashtable>
[ read1 dup ] [ over inc-at ] while
drop ;
: print-counts ( counts -- )
[ "%c: %d\n" printf ] assoc-each ;
PRIVATE>
: count-letters ( filename -... |
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... | #Standard_ML | Standard ML |
(* reuse earlier factorial calculations in dfac, apply to listed arguments in cumlfac *)
(* example: left factorial n, is #3 (dfac (0,n-1,1,1) ) *)
(* output list contains (number, factorial, left factorial) *)
(* tested in PolyML *)
val store = ref 0;
val rec dfac = fn
(from,to,acc,cm) => if from = to... |
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... | #Swift | Swift | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func ! <T: BinaryInteger>(n: T) -> T {
guard n != 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #PureBasic | PureBasic | Procedure ms_LCG(seed.q = -1)
Static state.q
If seed >= 0
state = seed
Else
state = (state * 214013 + 2531011) % (1 << 31)
ProcedureReturn state >> 16
EndIf
EndProcedure
Procedure.q bsd_LCG(seed.q = -1)
Static state.q
If seed >= 0
state = seed
Else
state = (state * 1103515245 + 12... |
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)
| #Factor | Factor | USING: calendar prettyprint ;
2011 leap-year? . |
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)
| #Fermat | Fermat | Function IsLeap(y) = if y|4>0 then 0 else if y|100=0 and y|400>0 then 0 else 1 fi fi. |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #JavaScript | JavaScript | (() => {
'use strict';
// kochSnowflake :: Int -> (Float, Float) -> (Float, Float)
// -> [(Float, Float)]
const kochSnowflake = n => a => b => {
// List of points on a Koch snowflake of order n, derived
// from an equilateral triangle with base a b.
const 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... | #Java | Java | import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Befunge | Befunge | "22222 -"*>>>1-:0\:"P"%\v>\7%1g48*-/2%3*48*+,1+:20g`!v1g01+55p03:_$$$>@
!"$(0@`vp00_^#!:p+7/"P"<<^g+7/*5"p"\%"P"/7::+g03*"d":_$,1+>:40g`!^1g03<
_::10g\v>00g+4%:00p::3\`\1-*50g+50p:2\-\0`*+::0\`\"c"`+50g:0\`\"c"`++#^
-*84g1<v^+1*2g09pg08g07-*g06-1*2p09:%2/g06:gp08:+7/*5"p"\p07:%"P"/7:p06
0p+:7%^>>-:0`!*+10p::20g\-:0`*+2... |
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... | #Phix | Phix | with javascript_semantics
constant p = new_dict({{1,0}})
sequence lvl = {1}
function path(integer n)
if n=0 then return {} end if
while getd_index(n,p)=NULL do
sequence q = {}
for i=1 to length(lvl) do
integer x = lvl[i]
sequence px = path(x)
for j=1 to leng... |
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 ... | #Go | Go | package main
import (
"fmt"
"strings"
)
type uintMatrix [][]uint
func (m uintMatrix) String() string {
var max uint
for _, r := range m {
for _, e := range r {
if e > max {
max = e
}
}
}
w := len(fmt.Sprint(max))
b := &strings.Bui... |
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 ... | #Kotlin | Kotlin | // version 1.2.31
typealias Matrix = Array<IntArray>
fun kroneckerProduct(a: Matrix, b: Matrix): Matrix {
val m = a.size
val n = a[0].size
val p = b.size
val q = b[0].size
val rtn = m * p
val ctn = n * q
val r: Matrix = Array(rtn) { IntArray(ctn) } // all elements zero by default
for... |
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... | #Rust | Rust |
use itertools::Itertools;
fn get_kolakoski_sequence(iseq: &[usize], size: &usize) -> Vec<usize> {
assert!(*size > 0);
assert!(!iseq.is_empty());
let mut kseq: Vec<usize> = Vec::default();
// create an itertor which keeps repeating the initial sequence infinitely
let repeater = iseq.iter().cl... |
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... | #Sidef | Sidef | func create_generator(arr) {
Enumerator({|f|
var s = []
var i = 0
loop {
var t = arr[i++ % arr.len]
s << t
f(var v = s.shift)
s << (v-1).of(t)...
}
})
}
var tests = [
[20, [1,2]],
[20, [2,1]],
[30, [1,3,1,2]],
[30,... |
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... | #Delphi | Delphi | program LastFridayOfMonth;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.DateUtils;
var
Year: Word;
Month: Word;
D1: TDateTime;
D2: Word;
begin
Write('Enter year: ');
ReadLn(Year);
for Month := MonthJanuary to MonthDecember do begin
D1 := EndOfAMonth(Year, Month);
D2 := DayOfTheWeek(... |
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... | #Python | Python | def factorial(n):
if n == 0:
return 1
res = 1
while n > 0:
res *= n
n -= 1
return res
def lah(n,k):
if k == 1:
return factorial(n)
if k == n:
return 1
if k > n:
return 0
if k < 1 or n < 1:
return 0
return (factorial(n) * facto... |
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... | #ooRexx | ooRexx |
-- create the searcher and run it
searcher = .chainsearcher~new
::class chainsearcher
::method init
expose max searchsize currentlongest
pokemon_names = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon" -
"cresselia croagunk darmanitan deino emboar emolga exeggcute ... |
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,... | #Go | Go | // Variation of method 3. Repeat digits to at least the size of the longest,
// then sort as strings.
package main
import (
"fmt"
"math/big"
"sort"
"strconv"
"strings"
)
type c struct {
i int
s, rs string
}
type cc []*c
func (c cc) Len() int { return len(c) }
func (c c... |
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... | #R | R | largest_LynchBell_number <- function(from, to){
from = round(from)
to = round(to)
to_chosen = to
if(to > 9876432) to = 9876432 #cap the search space to this number
LynchBell = NULL
range <- to:from #search starting from the end of the range
range <- range[range %% 5 != 0] #reduce search space
f... |
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... | #Raku | Raku | my $magic-number = 9 * 8 * 7; # 504
my $div = 9876432 div $magic-number * $magic-number; # largest 7 digit multiple of 504 < 9876432
for $div, { $_ - $magic-number } ... * -> $test { # only generate multiples of 504
next if $test ~~ / <[05]> /; # skip numbers contai... |
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... | #Fermat | Fermat | Func Lecm(a,b)=|a|*|b|/GCD(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... | #Forth | Forth | : gcd ( a b -- n )
begin dup while tuck mod repeat drop ;
: lcm ( a b -- n )
over 0= over 0= or if 2drop 0 exit then
2dup gcd abs */ ; |
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 ... | #Haskell | Haskell | levenshtein :: Eq a => [a] -> [a] -> Int
levenshtein s1 s2 = last $ foldl transform [0 .. length s1] s2
where
transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1
where
calc z (c1, x, y) = minimum [y + 1, z + 1, x + fromEnum (c1 /= c)]
main :: IO ()
main = print (levenshtein "kitten" "sitt... |
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... | #FBSL | FBSL | #APPTYPE CONSOLE
'Open a text file and count the occurrences of each letter.
FUNCTION countBytes(fileName AS STRING)
DIM c AS STRING
DIM ascii[]
DIM handle AS INTEGER = FILEOPEN(fileName, BINARY)
WHILE NOT FILEEOF(handle)
c = FILEGETC(handle)
IF c = "" THEN EXIT WHILE
ascii[ASC] = ascii[ASC(c)] + 1
WEND
F... |
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... | #Tcl | Tcl | proc leftfact {n} {
set s 0
for {set i [set f 1]} {$i <= $n} {incr i} {
incr s $f
set f [expr {$f * $i}]
}
return $s
}
for {set i 0} {$i <= 110} {incr i [expr {$i>9?10:1}]} {
puts "!$i = [leftfact $i]"
}
for {set i 1000} {$i <= 10000} {incr i 1000} {
puts "!$i has [string length [leftfact $i... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Python | Python | def bsd_rand(seed):
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
return rand.seed
rand.seed = seed
return rand
def msvcrt_rand(seed):
def rand():
rand.seed = (214013*rand.seed + 2531011) & 0x7fffffff
return rand.seed >> 16
rand.seed = seed
return rand |
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)
| #Forth | Forth | : leap-year? ( y -- ? )
dup 400 mod 0= if drop true exit then
dup 100 mod 0= if drop false exit then
4 mod 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)
| #Fortran | Fortran | program leap
implicit none
write(*,*) leap_year([1900, 1996, 1997, 2000])
contains
pure elemental function leap_year(y) result(is_leap)
implicit none
logical :: is_leap
integer,intent(in) :: y
is_leap = (mod(y,4)==0 .and. .not. mod(y,100)==0) .or. (mod(y,400)==0)
end function leap_year
end progra... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #jq | jq | include "turtle" {search: "."};
def rules:
{ F: "F+F--F+F",
"": "F--F--F" };
def koch($count):
rules as $rules
| def repeat($count):
if $count <= 0 then .
else gsub("F"; $rules["F"])
| repeat($count-1)
end;
$rules[""] | repeat($count) ;
def interpret($x):
if $x == "+" t... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Julia | Julia | using Plots
function pointskoch(points, maxk, α = sqrt(3)/2)
Q = [0 -1; 1 0]
for k = 1:maxk
n = length(points)
new_points = Vector{Float64}[]
for i = 1:n-1
p1, p2 = points[i], points[i+1]
v = (p2 - p1) / 3
q1 = p1 + v
q2 = p1 + 1.5v + α * Q * v
q3 = q1 + v
append!(n... |
http://rosettacode.org/wiki/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #Julia | Julia | using Printf
function makesofn(n::Integer)
buf = Vector{typeof(n)}(0)
i = 0
return function sofn(item)
i += 1
if i ≤ n
push!(buf, item)
else
j = rand(1:i)
if j ≤ n buf[j] = item end
end
return buf
end
end
nhist = zeros(Int, ... |
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... | #Kotlin | Kotlin | // version 1.2.51
import java.util.Random
val rand = Random()
class SOfN<T>(val n: Int) {
private val sample = ArrayList<T>(n)
private var i = 0
fun process(item: T): List<T> {
if (++i <= n)
sample.add(item)
else if (rand.nextInt(i) < n)
sample[rand.nextInt(n)... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #BQN | BQN | Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩}
Fmt ← ⊏⟜" #"
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Ant ← 2⊑{ # Generator Block
p‿d‿g:
r ← d Rot˜ p⊑g
⟨
p + r
r
¬⌾(p⊸⊑)g
⟩
} _while_ { # Condition Block
p‿d‿g:
∧´(p≥0‿0)∧p<≢g
}
•Show Fmt Ant ⟨50‿50, 0‿1, 100‿100⥊0⟩ |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Python | Python | from __future__ import print_function
# remember the tree generation state and expand on demand
def path(n, p = {1:0}, lvl=[[1]]):
if not n: return []
while n not in p:
q = []
for x,y in ((x, x+y) for x in lvl[0] for y in path(x) if not x+y in p):
p[y] = x
q.append(y)
lvl[0] = q
return path(p[n]) + [... |
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 ... | #Haskell | Haskell | import Data.List (transpose)
-------------------- KRONECKER PRODUCT -------------------
kroneckerProduct :: Num a => [[a]] -> [[a]] -> [[a]]
kroneckerProduct xs ys =
fmap (`f` ys) <$> xs
>>= fmap concat . transpose
where
f = fmap . fmap . (*)
--------------------------- TEST ------------------------... |
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 ... | #Lua | Lua |
function prod( a, b )
local rt, l = {}, 1
for m = 1, #a do
for p = 1, #b do
rt[l] = {}
for n = 1, #a[m] do
for q = 1, #b[p] do
table.insert( rt[l], a[m][n] * b[p][q] )
end
end
l = l + 1
end
... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
Class Crutch
Public ReadOnly len As Integer
Public s() As Integer
Public i As Integer
Public Sub New(len As Integer)
Me.len = len
s = New Integer(len - 1) {}
i = 0
... |
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... | #Elixir | Elixir | defmodule RC do
def lastFriday(year) do
Enum.map(1..12, fn month ->
lastday = :calendar.last_day_of_the_month(year, month)
daynum = :calendar.day_of_the_week(year, month, lastday)
friday = lastday - rem(daynum + 2, 7)
{year, month, friday}
end)
end
end
y = String.to_integer(hd(Syst... |
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... | #Quackery | Quackery | [ table ] is ! ( n --> n )
1
101 times
[ dup ' ! put
i^ 1+ * ]
drop
[ 2dup = iff [ 2drop 1 ] done
2dup * 0 = iff * done
dup 1 = iff [ drop ! ] done
2dup - ! unrot
dup !
swap 1 - ! *
swap dup !
swap 1 - ! *
swap /
swap / ] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.