task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #C | C | #include <stdio.h>
int is_leap_year(int year)
{
return (!(year % 4) && year % 100 || !(year % 400)) ? 1 : 0;
}
int main()
{
int test_case[] = {1900, 1994, 1996, 1997, 2000}, key, end, year;
for (key = 0, end = sizeof(test_case)/sizeof(test_case[0]); key < end; ++key) {
year = test_case[key];
... |
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... | #11l | 11l | F kosaraju(g)
V size = g.len
V vis = [0B] * size
V l = [0] * size
V x = size
V t = [[Int]()] * size
F visit(Int u) -> N
I !@vis[u]
@vis[u] = 1B
L(v) @g[u]
@visit(v)
@t[v] [+]= u
@x--
@l[@x] = u
L(u) 0 .< g.len
visit(u)
V... |
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... | #Ada | Ada | with Ada.Text_IO, GNAT.Calendar.Time_IO, Ada.Command_Line,
Ada.Calendar.Formatting, Ada.Calendar.Arithmetic;
procedure Last_Weekday_In_Month is
procedure Put_Line(T: Ada.Calendar.Time) is
use GNAT.Calendar.Time_IO;
begin
Ada.Text_IO.Put_Line(Image(Date => T, Picture => ISO_Date));
end Put_Lin... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN # calculate Lah numbers upto L( 12, 12 ) #
PR precision 400 PR # set the precision for LONG LONG INT #
# returns Lah Number L( n, k ), f must be a table of factorials to at least n #
PROC lah = ( INT n, k, []LONG LONG INT f )LONG LONG 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... | #Clojure | Clojure | (ns rosetta-code.last-letter-first-letter
(:require clojure.string))
(defn by-first-letter
"Returns a map from letters to a set of words that start with that letter"
[words]
(into {} (map (fn [[k v]]
[k (set v)]))
(group-by first words)))
(defn longest-path-from
"Find a longest p... |
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,... | #Aime | Aime | largest(...)
{
index x;
for (, integer e in xcall(list).__list) {
x[999999999 - 9.times(b_, data(), e).b_size(9).atoi] = e;
}
x.ucall(o_, 0);
o_newline();
}
main(void)
{
largest(1, 34, 3, 98, 9, 76, 45, 4);
largest(54, 546, 548, 60);
0;
} |
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,... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns the integer value of s #
OP TOINT = ( STRING s)INT:
BEGIN
INT result := 0;
FOR s pos FROM LWB s TO UPB s DO
result *:= 10 +:= ( ABS s[ s pos ] - ABS "0" )
OD;
result
END # TOINT # ;
# returns the first digit of n #
OP FIRSTDIGIT = ( INT... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #C.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <set>
bool checkDec(int num) {
std::set<int> set;
std::stringstream ss;
ss << num;
auto str = ss.str();
for (int i = 0; i < str.size(); ++i) {
char c = str[i];
int d = c - '0';
if (d == 0) return false;
if (num % d... |
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 .
| #Factor | Factor | USING: grouping kernel math math.bitwise math.functions
math.ranges prettyprint sequences ;
: odd ( m -- n )
dup 3 /i 1 - next-odd 1 -2 <range>
[ divisor? ] with find nip ;
: largest ( m -- n ) dup odd? [ odd ] [ 2/ ] if ;
100 [1,b] [ largest ] map 10 group simple-table. |
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 .
| #Fermat | Fermat | Func Lpd(n) =
if n = 1 then Return(1) fi;
for i = n\2 to 1 by -1 do
if n|i = 0 then Return(i) fi;
od.;
for m = 1 to 100 do
!(Lpd(m):4);
if m|10=0 then ! fi;
od; |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
set num1=12
set num2=18
call :lcm %num1% %num2%
exit /b
:lcm <input1> <input2>
if %2 equ 0 (
set /a lcm = %num1%*%num2%/%1
echo LCM = !lcm!
pause>nul
goto :EOF
)
set /a res = %1 %% %2
call :lcm %2 %res%
goto :EOF |
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... | #MiniZinc | MiniZinc |
%Latin Squares in Reduced Form. Nigel Galloway, September 5th., 2019
include "alldifferent.mzn";
int: N;
array[1..N,1..N] of var 1..N: p; constraint forall(n in 1..N)(p[1,n]=n /\ p[n,1]=n);
constraint forall(n in 1..N)(alldifferent([p[n,g]|g in 1..N])/\alldifferent([p[g,n]|g in 1..N]));
|
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... | #Nim | Nim | import algorithm, math, sequtils, strformat
type
# Row managed as a sequence of ints with base index 1.
Row = object
value: seq[int]
# Matrix managed as a sequence of rows with base index 1.
Matrix = object
value: seq[Row]
func newRow(n: Natural = 0): Row =
## Create a new row of length "n".
... |
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 ... | #Lua | Lua | function solve(angle, maxlen, filter)
local squares, roots, solutions = {}, {}, {}
local cos2 = ({[60]=-1,[90]=0,[120]=1})[angle]
for i = 1, maxlen do squares[i], roots[i^2] = i^2, i end
for a = 1, maxlen do
for b = a, maxlen do
local lhs = squares[a] + squares[b] + cos2*a*b
local c = roots[lhs]... |
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 ... | #DWScript | DWScript | function LevenshteinDistance(s, t : String) : Integer;
var
i, j : Integer;
begin
var d:=new Integer[Length(s)+1, Length(t)+1];
for i:=0 to Length(s) do
d[i, 0] := i;
for j:=0 to Length(t) do
d[0, j] := j;
for j:=1 to Length(t) do
for i:=1 to Length(s) do
if s[i]=t[j] then
... |
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... | #C.2B.2B | C++ | #include <fstream>
#include <iostream>
int main()
{
std::ifstream input("filename.txt", std::ios_base::binary);
if (!input)
{
std::cerr << "error: can't open file\n";
return -1;
}
size_t count[256];
std::fill_n(count, 256, 0);
for (char c; input.get(c); ++count[uint8_t(c)]) // process input file
; //... |
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... | #R | R |
x = (0:10)
> x^2
[1] 0 1 4 9 16 25 36 49 64 81 100
> Reduce(function(y,z){return (y+z)},x)
[1] 55
> x[x[(0:length(x))] %% 2==0]
[1] 0 2 4 6 8 10
|
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #zkl | zkl | foreach i in ([1..5]){
foreach j in (i){print("*")}
println();
} |
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... | #Nim | Nim | import iterutils, bigints
proc lfact: iterator: BigInt =
result = iterator: BigInt =
yield 0.initBigInt
var
fact = 1.initBigInt
sum = 0.initBigInt
n = 1.initBigInt
while true:
sum += fact
fact *= n
n += 1
yield sum
echo "first 11:\n "
for i in lfact().slice(l... |
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... | #Oforth | Oforth | : leftFact | i | 0 1 rot loop: i [ tuck + swap i * ] drop ; |
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
... | #Java | Java | import java.util.stream.IntStream;
import static java.util.stream.IntStream.iterate;
public class LinearCongruentialGenerator {
final static int mask = (1 << 31) - 1;
public static void main(String[] args) {
System.out.println("BSD:");
randBSD(0).limit(10).forEach(System.out::println);
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #zkl | zkl | fcn leonardoNumber(n, n1=1,n2=1,addnum=1){
if(n==0) return(n1);
if(n==1) return(n2);
self.fcn(n-1,n1,n2,addnum) + self.fcn(n-2,n1,n2,addnum) + addnum
} |
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)
| #C.23 | C# | using System;
class Program
{
static void Main()
{
foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
{
Console.WriteLine("{0} is {1}a leap year.",
year,
DateTime.IsLeapYear(year) ? string.Empty : "not ");... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>... |
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... | #11l | 11l | F gen_kolakoski(s, n)
[Int] seq
V i = 0
L seq.len < n
V next = s[i % s.len]
seq [+]= [next] * (I i >= seq.len {next} E seq[i])
i++
R seq[0 .< n]
F is_possible_kolakoski(s)
[Int] r
V i = 0
L i < s.len
V count = 1
L(j) i + 1 .< s.len
I s[j] != s[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... | #ALGOL_68 | ALGOL 68 | BEGIN # find the last Friday in each month of a year #
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
PROC is leap year = ( INT year )BOOL:
year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 );
# ... |
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... | #ALGOL_W | ALGOL W | begin % calculate Lah numbers upto L( 12, 12 ) %
% sets lahNumber to L( n, k ), lahScale is returned as the power of 10 %
% lahNumber should be multiplied by %
% f must be a table of factorials to at least n ... |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #Arturo | Arturo | factorial: function [n]-> product 1..n
lah: function [n,k][
if k=1 -> return factorial n
if k=n -> return 1
if k>n -> return 0
if or? k<1 n<1 -> return 0
return (((factorial n)*factorial n-1) / ((factorial k) * factorial k-1)) / factorial n-k
]
print @["n/k"] ++ map to [:string] 1..12 's -> pad ... |
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... | #Common_Lisp | Common Lisp | ;;; return all the words that start with an initial letter
(defun filter-with-init (words init)
(remove-if-not (lambda (word) (eql init (aref word 0))) words))
;;; produce a hash table whose key is the initial letter of a word and whose value is
;;; a list of the words that start with that initial letter
(defun... |
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,... | #Arturo | Arturo | largestConcInt: function [arr]->
max map permutate arr 's [
to :integer join map s => [to :string]
]
loop [[1 34 3 98 9 76 45 4] [54 546 548 60]] 'a ->
print largestConcInt a |
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... | #Clojure | Clojure |
(require '[clojure.string :as str]) ;'
(def the_base 16)
;A sequence named digits containing the non-zero digits for the current number base.
(def digits (rest (range the_base)))
;A container for the digits which are prime.
(def primes [])
;Populate the primes sequence with the primes less than the current base... |
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 .
| #FOCAL | FOCAL | 01.10 F N=1,100;D 2;D 3
01.20 Q
02.10 S V=1
02.20 I (1-N)2.3;R
02.30 S V=N-1
02.40 S A=N/V
02.50 I (FITR(A)-A)2.6;R
02.60 S V=V-1
02.70 G 2.4
03.10 T %2,V
03.20 S A=N/10
03.30 I (FITR(A)-A)3.4;T !
03.40 R |
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 .
| #Forth | Forth | : largest-proper-divisor { n -- n }
n 1 and 0= if n 2/ exit then
3
begin
dup dup * n <=
while
dup n swap /mod swap
0= if nip exit else drop then
2 +
repeat drop 1 ;
: main
101 1 do
i largest-proper-divisor 2 .r
i 10 mod 0= if cr else space then
loop ;
main
bye |
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... | #bc | bc | /* greatest common divisor */
define g(m, n) {
auto t
/* Euclid's method */
while (n != 0) {
t = m
m = n
n = t % n
}
return (m)
}
/* least common multiple */
define l(m, n) {
auto r
if (m == 0 || n == 0) return (0)
r = m * n / g(m, n)
if (r < 0) return (-r)
return (r)
} |
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... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Latin_Squares_in_reduced_form
use warnings;
my $n = 0;
my $count;
our @perms;
while( ++$n <= 7 )
{
$count = 0;
@perms = perm( my $start = join '', 1 .. $n );
find( $start );
print "order $n size $count total @{[$count * fact($n) * fact($n-1)]}\n... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Solve[{a^2+b^2==c^2,1<=a<=13,1<=b<=13,1<=c<=13,a<=b},{a,b,c},Integers]
Length[%]
Solve[{a^2+b^2-a b==c^2,1<=a<=13,1<=b<=13,1<=c<=13,a<=b},{a,b,c},Integers]
Length[%]
Solve[{a^2+b^2+a b==c^2,1<=a<=13,1<=b<=13,1<=c<=13,a<=b},{a,b,c},Integers]
Length[%]
Solve[{a^2+b^2-a b==c^2,1<=a<=10000,1<=b<=10000,1<=c<=10000,a<=b,a!=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 ... | #Nim | Nim | import strformat
import tables
# Generate tables at compile time. This eliminates the initialization at
# the expense of a bigger executable.
const square13 = block:
var tmp = newSeq[tuple[a, b: int]]()
for i in 1..13:
tmp.add((i * i, i))
toTable(tmp)
const square10000 = block:
var tmp = newSeq[tuple[... |
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 ... | #Dyalect | Dyalect | func levenshtein(s, t) {
var n = s.Length()
var m = t.Length()
var d = Array.Empty(n + 1, () => Array.Empty(m + 1))
if n == 0 {
return m
}
if (m == 0) {
return n
}
for i in 0..n {
d[i][0] = i
}
for j in 0..m {
d[0][j] = j
}
for 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... | #Clojure | Clojure | (println (sort-by second >
(frequencies (map #(java.lang.Character/toUpperCase %)
(filter #(java.lang.Character/isLetter %) (slurp "text.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... | #Racket | Racket |
#lang racket
(for*/list ([x (in-range 1 21)]
[y (in-range x 21)]
[z (in-range y 21)]
#:when (= (+ (* x x) (* y y)) (* z z)))
(list x y z))
|
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Zig | Zig | const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
var i: u8 = 1;
while (i < 5) : (i += 1) {
var j: u8 = 1;
while (j <= i) : (j += 1)
try stdout_wr.writeAll("*");
try stdout_wr.writeAll("\n");
}
} |
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... | #PARI.2FGP | PARI/GP | lf(n)=sum(k=0,n-1,k!);
apply(lf, [0..10])
apply(lf, 10*[2..11])
forstep(n=1000,1e4,1000,print1(#digits(lf(n))", ")) |
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
... | #jq | jq | # 15-bit integers generated using the same formula as rand()
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
def next_rand_Microsoft:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ];
# Generate the first n pseudo-ra... |
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)
| #C.2B.2B | C++ | g++ -std=c++11 leap_year.cpp
|
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... | #C.2B.2B | C++ | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
wh... |
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... | #Arturo | Arturo | kolakoski: function [a, length][
result: array.of: length 0
i: new 0
k: new 0
loop.forever a 'x [
result\[i]: x
if result\[k] > 1 [
loop 1..dec result\[k] 'j [
inc 'i
if i = length -> return result
result\[i]: result\[i-1]
... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #ALGOL_W | ALGOL W | begin % find the last Friday in each month of a year %
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
logical procedure isLeapYear ( integer value year ) ;
year rem 400 = 0 or ( year rem 4 = 0 and year rem 100... |
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... | #AWK | AWK |
# syntax: GAWK -f LAH_NUMBERS.AWK
# converted from C
BEGIN {
print("unsigned Lah numbers: L(n,k)")
printf("n/k")
for (i=0; i<13; i++) {
printf("%11d",i)
}
printf("\n")
for (row=0; row<13; row++) {
printf("%-3d",row)
for (i=0; i<row+1; i++) {
printf(" %10d",lah(row,i))... |
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... | #D | D | import std.stdio, std.algorithm, std.string;
void trySwap(string[] items, ref string item, in size_t len, ref string[] longest)
pure nothrow @safe {
swap(items[len], item);
search(items, len + 1, longest);
swap(items[len], item);
}
void search(string[] items, in size_t len, ref string[] longest)
pure no... |
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,... | #AutoHotkey | AutoHotkey | LargestConcatenatedInts(var){
StringReplace, var, A_LoopField,%A_Space%,, all
Sort, var, D`, fConcSort
StringReplace, var, var, `,,, all
return var
}
ConcSort(a, b){
m := a . b , n := b . a
return m < n ? 1 : m > n ? -1 : 0
} |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Crystal | Crystal | magic_number = 9*8*7
div = (9876432 // magic_number) * magic_number
candidates = div.step(to: 0, by: -magic_number)
res = candidates.find do |c|
digits = c.to_s.chars.map(&.to_i)
(digits & [0,5]).empty? && digits == digits.uniq
end
puts "Largest decimal number is #{res}" |
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 .
| #Fortran | Fortran | program LargestProperDivisors
implicit none
integer i, lpd
do 10 i=1, 100
write (*,'(I3)',advance='no') lpd(i)
10 if (i/10*10 .eq. i) write (*,*)
end program
integer function lpd(n)
implicit none
integer n, i
if (n .le. 1) then
... |
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 .
| #FreeBASIC | FreeBASIC | Print !"El mayor divisor propio de n es:\n"
Print " 1 1";
For i As Byte = 3 To 100
For j As Byte = i-1 To 1 Step -1
If i Mod j = 0 Then Print Using "###"; j; : Exit For
Next j
If i Mod 10 = 0 Then Print
Next i
Sleep |
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... | #BCPL | BCPL | get "libhdr"
let lcm(m,n) =
m=0 -> 0,
n=0 -> 0,
abs(m*n) / gcd(m,n)
and gcd(m,n) =
n=0 -> m,
gcd(n, m rem n)
let start() be writef("%N*N", lcm(12, 18)) |
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... | #Phix | Phix | string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
function rfls(integer n, bool count_only=true)
if n>length(aleph) then ?9/0 end if -- too big...
if n=1 then return iff(count_only?1:{{1}}) end if
sequence tn = tagset(n), -- {1..n}
vcs = repeat(tn,n), -- valid... |
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 ... | #Perl | Perl | use utf8;
binmode STDOUT, "utf8:";
use Sort::Naturally;
sub triples {
my($n,$angle) = @_;
my(@triples,%sq);
$sq{$_**2}=$_ for 1..$n;
for $a (1..$n-1) {
for $b ($a+1..$n) {
my $ab = $a*$a + $b*$b;
my $cos = $angle == 60 ? $ab - $a * $b :
$angle == 120 ? $ab + $a... |
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 ... | #EchoLisp | EchoLisp |
;; Recursive version adapted from Clojure
;; Added necessary memoization
(define (levenshtein str1 str2 (cost 0) (rest1 0) (rest2 0) (key null))
(set! key (string-append str1 "|" str2))
(if (get 'mem key) ;; memoized ?
(get 'mem key)
;; else memoize
(putprop 'mem
(let [(len1 (string-length str1))
(le... |
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... | #Common_Lisp | Common Lisp | (defun letter-freq (file)
(with-open-file (stream file)
(let ((str (make-string (file-length stream)))
(arr (make-array 256 :element-type 'integer :initial-element 0)))
(read-sequence str stream)
(loop for c across str do (incf (aref arr (char-code c))))
(loop for c from 32 to 126 for i from ... |
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... | #Raku | Raku | my $n = 20;
gather for 1..$n -> $x {
for $x..$n -> $y {
for $y..$n -> $z {
take $x,$y,$z if $x*$x + $y*$y == $z*$z;
}
}
} |
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... | #Perl | Perl | #!perl
use 5.010;
use strict;
use warnings;
use bigint;
sub leftfact {
my ($n) = @_;
state $cached = 0;
state $factorial = 1;
state $leftfact = 0;
if( $n < $cached ) {
($cached, $factorial, $leftfact) = (0, 1, 0);
}
while( $n > $cached ) {
$leftfact += $factorial;
$factorial *= ++$cached;
}
return $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
... | #Julia | Julia | using Printf
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
state = r
return function lgcrand()
state = mod(a * state + c, m)
return state >> sh
end
end
seed, nrep = 0, 10
bsdrand = getlgc(seed, 1103515245, 12345, 2 ^ 31, 0)
println("The first $nrep result... |
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)
| #Clipper | Clipper | Function IsLeapYear( nYear )
Return Iif( nYear%100 == 0, (nYear%400 == 0), (nYear%4 == 0) ) |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Clojure | Clojure | (defn leap-year? [y]
(and (zero? (mod y 4)) (or (pos? (mod y 100)) (zero? (mod y 400))))) |
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 ... | #11l | 11l | V a1 = [[1, 2], [3, 4]]
V b1 = [[0, 5], [6, 7]]
V a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
V b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
F kronecker(matrix1, matrix2)
[[Int]] final_list
[Int] sub_list
V count = matrix2.len
L(elem1) matrix1
V counter = 0
V check = 0
L check < count
... |
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... | #D | D | import std.container.array;
import std.stdio;
/* the list index is the first vertex in the edge(s) */
auto g = [
[1],
[2],
[0],
[1, 2, 4],
[3, 5],
[2, 6],
[5],
[4, 6, 7],
];
int[] kosaraju(int[][] g) {
// 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
int next_in_cycle(int *c, int len, int index) {
return c[index % len];
}
void kolakoski(int *c, int *s, int clen, int slen) {
int i = 0, j, k = 0;
while (TRUE) {
s[i] = next_in_cycle(c, clen, k);
... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #AppleScript | AppleScript | -- LAST FRIDAYS OF YEAR ------------------------------------------------------
-- lastFridaysOfYear :: Int -> [Date]
on lastFridaysOfYear(y)
-- lastWeekDaysOfYear :: Int -> Int -> [Date]
script lastWeekDaysOfYear
on |λ|(intYear, iWeekday)
-- lastWeekDay :: Int -> Int -> Date
... |
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... | #BQN | BQN | F ← (≥⟜0)◶⟨0,×´1+↕⟩
Lah ← {
𝕨 𝕊 0: 0;
0 𝕊 𝕩: 0;
𝕨 𝕊 1: F 𝕨;
n 𝕊 k:
(n=k)⊑⟨((n ×○F n-1) ÷ k ×○F k-1) (0=⊢)◶÷‿0 F n-k, 1⟩
}
•Show Lah⌜˜↕12 |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #C | C | #include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t res = 1;
if (n == 0) return res;
while (n > 0) res *= n--;
return res;
}
uint64_t lah(uint64_t n, uint64_t k) {
if (k == 1) return factorial(n);
if (k == n) return 1;
if (k > n) return 0;
if (k < 1 || n ... |
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... | #Delphi | Delphi | unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DBCtrls, DB, DBClient, Grids, DBGrids, ExtCtrls;
type
TLastLFirstL = class(TForm)
Panel1: TPanel;
Button1: TButton;
Memo1: TMemo;
DataSource1: TDataSource;
ClientDataS... |
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,... | #AWK | AWK |
function cmp(i1, v1, i2, v2, u1, u2) {
u1 = v1""v2;
u2 = v2""v1;
return (u2 - u1)
}
function largest_int_from_concatenated_ints(X) {
PROCINFO["sorted_in"]="cmp";
u="";
for (i in X) u=u""X[i];
return u
}
BEGIN {
split("1 34 3 98 9 76 45 4",X);
print largest_int_from_concatenated_ints(X)
split("5... |
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... | #D | D | import std.algorithm.iteration : filter, map;
import std.algorithm.searching : all;
import std.conv : to;
import std.range : iota;
import std.stdio : writeln;
bool chkDec(int num) {
int[int] set;
return num
.to!string
.map!(c => c.to!int - '0')
.all!(d => (d != 0) && (num % d == 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 .
| #Frink | Frink | for n = 1 to 100
println[last[allFactors[n,true,false]]] |
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 .
| #Go | Go | package main
import "fmt"
func largestProperDivisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
func main() {
fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
fmt.Print(" 1 ")
for n := 2... |
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... | #Befunge | Befunge | &>:0`2*1-*:&>:#@!#._:0`2*1v
>28*:*:**+:28*>:*:*/\:vv*-<
|<:%/*:*:*82\%*:*:*82<<>28v
>$/28*:*:*/*.@^82::+**:*:*< |
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... | #BQN | BQN | Lcm ← ×÷{𝕨(|𝕊⍟(>⟜0)⊣)𝕩} |
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... | #Python | Python | def dList(n, start):
start -= 1 # use 0 basing
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
# rescursive closure permutes a[1:]
r = []
def recurse(last):
if (last == first):
# bottom of recursion. you get here once for each permutat... |
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 ... | #Phix | Phix | with javascript_semantics
--constant lim = iff(platform()=JS?13:10000)
constant lim = 10000
--sequence squares = repeat(0,lim*lim)
sequence squares = iff(platform()=JS?{}:repeat(0,lim*lim))
for c=1 to lim do
squares[c*c] = c
end for
function solve(integer angle, maxlen, bool samelen=true)
sequence res = {}
... |
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 ... | #Ela | Ela | open list
levenshtein s1 s2 = last <| foldl transform [0 .. length s1] s2
where transform (n::ns')@ns c = scanl calc (n+1) <| zip3 s1 ns ns'
where calc z (c', x, y) = minimum [y+1, z+1, x + toInt (c' <> c)] |
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... | #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. Letter-Frequency.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 12 December 2021.
************************************************************
** Program Abstract:
** A rather simplistic program to do the kind ... |
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... | #Rascal | Rascal |
public list[tuple[int, int, int]] PythTriples(int n) = [<a, b, c> | a <- [1..n], b <- [1..n], c <- [1 .. n], a*a + b*b == c*c];
|
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... | #REXX | REXX | /*REXX program displays a vertical list of Pythagorean triples up to a specified number.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 100 /*Not specified? Then use the default.*/
say 'Pythagorean triples (a² + b² = c², 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... | #Phix | Phix | with javascript_semantics
include mpfr.e
sequence lf_list
procedure init(integer n)
mpz f = mpz_init(1)
lf_list = repeat(f,n+1)
for i=1 to n do
f = mpz_init_set(f)
mpz_mul_si(f,f,i)
lf_list[i+1] = f
end for
end procedure
function lf(integer n, bool len=false)
-- Returns le... |
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
... | #K | K | bsd:{1_ y{((1103515245*x)+12345)!(_2^31)}\x}
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
bsd[0;10]
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
ms[0;10]
38 7719 21238 2437 8855 11797 8365 32285 10450 30612 |
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
... | #Kotlin | Kotlin | // version 1.1.3
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
private var state = s
fun nextInt(): Long {
state = (a * state + c) % m
return state / d
}
}
fun main(args: Array<String>) {
println("First 10 BSD random numbers - seed 0")
val bsd = L... |
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)
| #CLU | CLU | is_leap_year = proc (year: int) returns (bool)
return(year//400 =0 cor (year//4 = 0 cand year//100 ~= 0))
end is_leap_year
start_up = proc ()
po: stream := stream$primary_output()
years: sequence[int] := sequence[int]$
[1899, 1900, 1901, 1902, 1903, 1904, 1905, 1999,
2000, 2001, 2002, 200... |
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)
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. leap-year.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 examples VALUE "19001994199619972000".
03 year PIC 9(4) OCCURS 5 TIMES
INDEXED BY year-index.
01 remainders.
03 400-rem PIC 9(4).
... |
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 ... | #360_Assembly | 360 Assembly | * Kronecker product 06/04/2017
KRONECK CSECT
USING KRONECK,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST... |
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 ... | #Action.21 | Action! | SET EndProg=* |
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... | #Delphi | Delphi |
program KosarajuApp;
uses
System.SysUtils;
type
TKosaraju = TArray<TArray<Integer>>;
var
g: TKosaraju;
procedure Init();
begin
SetLength(g, 8);
g[0] := [1];
g[1] := [2];
g[2] := [0];
g[3] := [1, 2, 4];
g[4] := [3, 5];
g[5] := [2, 6];
g[6] := [5];
g[7] := [4, 6, 7];
end;
procedure Pri... |
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 ... | #11l | 11l | F kroneckerProduct(a, b)
V m = a.len
V n = a[0].len
V p = b.len
V q = b[0].len
V result = [[0] * (n * q)] * (m * p)
L(i) 0 .< m
L(j) 0 .< n
L(k) 0 .< p
L(l) 0 .< q
result[i * p + k][j * q + l] = a[i][j] * b[k][l]
R result
F kroneckerPower(m, n)
V resul... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KolakoskiSequence {
class Crutch {
public readonly int len;
public int[] s;
public int i;
public Crutch(int len) {
this.len = len;
... |
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... | #Arturo | Arturo | lastFridayForMonth: function [m][
ensure -> in? m 1..12
daysOfMonth: [0 31 27 31 30 31 30 31 31 30 31 30 31]
loop range get daysOfMonth m 1 [d][
dt: to :date.format:"yyyy-M-dd" ~"2012-|m|-|d|"
if dt\Day = "Friday" -> return dt
]
]
loop 1..12 'month [
print to :string.format:"yyyy... |
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... | #C.23 | C# | using System;
using System.Linq;
using System.Numerics;
namespace LahNumbers {
class Program {
static BigInteger Factorial(BigInteger n) {
if (n == 0) return 1;
BigInteger res = 1;
while (n > 0) {
res *= n--;
}
return res;
... |
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... | #Elixir | Elixir | defmodule LastLetter_FirstLetter do
def search(names) do
first = Enum.group_by(names, &String.first/1)
sequences = Enum.reduce(names, [], fn name,acc -> add_name(first, acc, [name]) end)
max = Enum.max_by(sequences, &length/1) |> length
max_seqs = Enum.filter(sequences, fn seq -> length(seq) == max en... |
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,... | #BBC_BASIC | BBC BASIC | DIM Nums%(10)
Nums%()=1,34,3,98,9,76,45,4
PRINT FNlargestint(8)
Nums%()=54,546,548,60
PRINT FNlargestint(4)
END
DEF FNlargestint(len%)
LOCAL i%,l$,a$,b$,sorted%
REPEAT
sorted%=TRUE
FOR i%=0 TO len%-2
a$=STR$Nums%(i%)
b$=STR$Nums... |
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,... | #Bracmat | Bracmat | ( ( maxnum
= A Z F C
. !arg:#
| !arg
: %@?F
?
( #%@?C
& ( str$(!F !C)+-1*str$(!C !F):~<0
| !C:?F
)
& ~
)
?
| !arg:?A !F ?Z&!F maxnum$(!A !Z)
)
& out$(str$(maxnum$(1 34 3 98 9 76 45 4))... |
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... | #Delphi | Delphi |
program Largest_number_divisible_by_its_digits;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TSetAnsiChar = set of AnsiChar;
function DivByAll(num: Integer; digits: TSetAnsiChar): Boolean;
var
offset: byte;
begin
offset := ord('0');
for var d in digits do
begin
if (num mod (ord(d) - offset)) ... |
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 .
| #GW-BASIC | GW-BASIC | 10 PRINT 1;
20 FOR I = 1 TO 101
30 FOR D = I\2 TO 1 STEP -1
40 IF I MOD D = 0 THEN PRINT D; : GOTO 60
50 NEXT D
60 NEXT 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 .
| #Haskell | Haskell | import Data.List.Split (chunksOf)
import Text.Printf (printf)
lpd :: Int -> Int
lpd 1 = 1
lpd n = head [x | x <- [n -1, n -2 .. 1], n `mod` x == 0]
main :: IO ()
main =
(putStr . unlines . map concat . chunksOf 10) $
printf "%3d" . lpd <$> [1 .. 100] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.