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/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... | #Bracmat | Bracmat | (gcd=
a b
. !arg:(?a.?b)
& den$(!a*!b^-1)
* (!a:<0&-1|1)
* !a
);
out$(gcd$(12.18) gcd$(-6.14) gcd$(35.0) gcd$(117.18)) |
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... | #Brat | Brat |
gcd = { a, b |
true? { a == 0 }
{ b }
{ gcd(b % a, a) }
}
lcm = { a, b |
a * b / gcd(a, b)
}
p lcm(12, 18) # 36
p lcm(14, 21) # 42
|
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... | #Raku | Raku | # utilities: factorial, sub-factorial, derangements
sub postfix:<!>($n) { (constant f = 1, |[\×] 1..*)[$n] }
sub prefix:<!>($n) { (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] }
sub derangements(@l) { @l.permutations.grep(-> @p { none(@p Zeqv @l) }) }
sub LS-reduced (Int $n) {
return [1] if $n == 1;... |
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 ... | #Prolog | Prolog | find_solutions(Limit, Solutions):-
find_solutions(Limit, Solutions, Limit, []).
find_solutions(_, S, 0, S):-
!.
find_solutions(Limit, Solutions, A, S):-
find_solutions1(Limit, A, A, S1, S),
A_next is A - 1,
find_solutions(Limit, Solutions, A_next, S1).
find_solutions1(Limit, _, B, Triples, Tripl... |
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 ... | #Elixir | Elixir | defmodule Levenshtein do
def distance(a, b) do
ta = String.downcase(a) |> to_charlist |> List.to_tuple
tb = String.downcase(b) |> to_charlist |> List.to_tuple
m = tuple_size(ta)
n = tuple_size(tb)
costs = Enum.reduce(0..m, %{}, fn i,acc -> Map.put(acc, {i,0}, i) end)
costs = Enum.reduce(0..n... |
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... | #Component_Pascal | Component Pascal |
MODULE LetterFrecuency;
IMPORT Files,StdLog,Strings;
PROCEDURE Do*;
VAR
loc: Files.Locator;
fd: Files.File;
rd: Files.Reader;
x: BYTE;
frecuency: ARRAY 26 OF LONGINT;
c: CHAR;
i: INTEGER;
BEGIN
loc := Files.dir.This("BBTest/Mod");
fd := Files.dir.Old(loc,"LetterFrecuency.odc",FALSE);
rd := fd.NewReader(NI... |
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... | #Ring | Ring |
for x = 1 to 20
for y = x to 20
for z = y to 20
if pow(x,2) + pow(y,2) = pow(z,2)
see "[" + x + "," + y + "," + z + "]" + nl ok
next
next
next
|
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... | #Ruby | Ruby | n = 20
# select Pythagorean triplets
r = ((1..n).flat_map { |x|
(x..n).flat_map { |y|
(y..n).flat_map { |z|
[[x, y, z]].keep_if { x * x + y * y == z * z }}}})
p r # print the array _r_ |
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... | #PicoLisp | PicoLisp | (de n! (N)
(cache '(NIL) N
(if (> 2 N) 1
(* N (n! (dec N))))))
(de !n (Num)
(if (= Num 0) 1
(sum n! (range 0 (dec Num)))))
(de pril (List) (mapcar 'println List))
(prinl "0-10")
(pril (mapcar '!n (range 0 10)))
(prinl "20 - 110")
(pril (mapcar '!n (range 20 110 10)))
(prinl "length... |
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... | #PL.2FI | PL/I | lf: procedure (n) returns (fixed decimal (31) );
declare n fixed binary;
declare (s, f) fixed (31);
declare (i, j) fixed;
s = 0;
do i = n-1 to 0 by -1;
f = 1;
do j = i to 1 by -1;
f = f * j;
end;
s = s + f;
end;
return (s);
end lf;
declare n fixed binary;
... |
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
... | #Liberty_BASIC | Liberty BASIC |
'by default these are 0
global BSDState
global MSState
for i = 1 to 10
print randBSD()
next i
print
for i = 1 to 10
print randMS()
next i
function randBSD()
randBSD = (1103515245 * BSDState + 12345) mod (2 ^ 31)
BSDState = randBSD
end function
function randMS()
MSState = (214013 * MSStat... |
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)
| #Common_Lisp | Common Lisp | (defun leap-year-p (year)
(destructuring-bind (fh h f)
(mapcar #'(lambda (n) (zerop (mod year n))) '(400 100 4))
(or fh (and (not h) f)))) |
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)
| #Component_Pascal | Component Pascal |
MODULE LeapYear;
IMPORT StdLog, Strings, Args;
PROCEDURE IsLeapYear(year: INTEGER): BOOLEAN;
BEGIN
IF year MOD 4 # 0 THEN
RETURN FALSE
ELSE
IF year MOD 100 = 0 THEN
IF year MOD 400 = 0 THEN RETURN TRUE ELSE RETURN FALSE END
ELSE
RETURN TRUE
END
END
END IsLeapYear;
PROCEDURE Do*;
VAR
p: Arg... |
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... | #11l | 11l | V p = [1 = 0]
V lvl = [[1]]
F path(n)
I !n
R [Int]()
L n !C :p
[Int] q
L(x) :lvl[0]
L(y) path(x)
I !(x + y C :p)
:p[x + y] = x
q.append(x + y)
:lvl[0] = q
R path(:p[n]) [+] [n]
F tree_pow(x, n)
T Ty = T(x)
V (r, p) = ([0 = T... |
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 ... | #Ada | Ada | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Kronecker_Product is
type Matrix is array (Positive range <>, Positive range <>) of Integer;
function "*"(Left, Right : in Matrix) return Matrix is
result : Matrix
(1 .. Left'Length(1) * Right'Length(1),
1 .. Left'Length(2) * Right'L... |
http://rosettacode.org/wiki/Kosaraju | Kosaraju |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin... | #Go | Go | package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
// 1. For each vertex u of the graph, mark u as unvisited. Let L be emp... |
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 ... | #Action.21 | Action! | SET EndProg=* |
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 ... | #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
with SDL.Events.Mice;
procedure Kronecker_Fractals is
Width : constant := 800;
Height : constant := 800;
Order : constant := 6;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
... |
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.2B.2B | C++ | #include <iostream>
#include <vector>
using Sequence = std::vector<int>;
std::ostream& operator<<(std::ostream& os, const Sequence& v) {
os << "[ ";
for (const auto& e : v) {
std::cout << e << ", ";
}
os << "]";
return os;
}
int next_in_cycle(const Sequence& s, size_t i) {
return s[i % s.size()];
... |
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... | #AutoHotkey | AutoHotkey | if 1 = ; no parameter passed
{
InputBox, 1, Last Fridays of year, Enter a year:, , , , , , , , %A_YYYY%
If ErrorLevel
ExitApp
}
YYYY = %1% ; retrieve command line parameter
Stmp = %YYYY%0101000000
count= 0
While count < 12
{
FormatTime, ddd, %stmp%, ddd
FormatTime, M, %stmp%, M
If (ddd = "Fri"){
if (M-1 = ... |
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.2B.2B | C++ | // Reference: https://en.wikipedia.org/wiki/Lah_number#Identities_and_relations
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class unsigned_lah_numbers {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, in... |
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... | #Erlang | Erlang |
-module( last_letter_first_letter ).
-export( [solve/1, task/0] ).
solve( Names ) ->
Dict = lists:foldl( fun dict_append/2, dict:new(), Names ),
Chains = construct_chains_in_parallel( Dict ),
% Chains = [construct_chain_from_key(Dict, X) || X <- dict:fetch_keys(Dict)],
lists:foldl( fun construct_ch... |
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,... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int catcmp(const void *a, const void *b)
{
char ab[32], ba[32];
sprintf(ab, "%d%d", *(int*)a, *(int*)b);
sprintf(ba, "%d%d", *(int*)b, *(int*)a);
return strcmp(ba, ab);
}
void maxcat(int *a, int len)
{
int i;
qsort(a, len, sizeof(int), catcmp);
for (... |
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... | #Factor | Factor | USING: io kernel math math.combinatorics math.parser math.ranges
sequences tools.time ;
IN: rosetta-code.largest-divisible
: all-div? ( seq -- ? )
[ string>number ] [ string>digits ] bi [ mod ] with map
sum 0 = ;
: n-digit-all-div ( n -- seq )
"12346789" swap <combinations>
[ [ all-div? ] filter-per... |
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... | #FreeBASIC | FreeBASIC |
For n As Integer = 9867000 To 9867400
Dim As Integer numbers(9)
For t As Byte = 1 To 9
numbers(t) = 0
Next t
Dim As Boolean flag = true, flag2 = true, flag3 = true
Dim As String cadena = Str(n)
For m As Byte = 1 To Len(cadena)
If Val(Mid(cadena,m,1)) > 0 Then
num... |
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 .
| #J | J | lpd =: (1 |.!.1 ])&.q: |
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 .
| #jq | jq | # (1|largestpd) is 1 as per the task definition
def largestpd:
if . == 1 then 1
else . as $n
| first( range( ($n - ($n % 2)) /2; 0; -1) | (select($n % . == 0) ))
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 .
| #Julia | Julia | largestpd(n) = (for i in n÷2:-1:1 (n % i == 0) && return i; end; 1)
foreach(n -> print(rpad(largestpd(n), 3), n % 10 == 0 ? "\n" : ""), 1:100)
|
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 .
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N)
ENTRY TO LPD.
WHENEVER N.LE.1, FUNCTION RETURN 1
THROUGH TEST, FOR D=N-1, -1, D.L.1
TEST WHENEVER N/D*D.E.N, FUNCTION RETURN D
END OF FUNCTION
THROUGH SHOW, FOR I=1, 10, I.GE.100
SH... |
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... | #C | C | #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 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... | #C.23 | C# | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + 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... | #Ruby | Ruby | def printSquare(a)
for row in a
print row, "\n"
end
print "\n"
end
def dList(n, start)
start = start - 1 # use 0 based indexing
a = Array.new(n) {|i| i}
a[0], a[start] = a[start], a[0]
a[1..] = a[1..].sort
first = a[1]
r = []
recurse = lambda {|last|
if last =... |
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 ... | #Python | Python | N = 13
def method1(N=N):
squares = [x**2 for x in range(0, N+1)]
sqrset = set(squares)
tri90, tri60, tri120 = (set() for _ in range(3))
for a in range(1, N+1):
a2 = squares[a]
for b in range(1, a + 1):
b2 = squares[b]
c2 = a2 + b2
if c2 in sqrset:
... |
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 ... | #Erlang | Erlang |
-module(levenshtein).
-compile(export_all).
distance_cached(S,T) ->
{L,_} = ld(S,T,dict:new()),
L.
distance(S,T) ->
ld(S,T).
ld([],T) ->
length(T);
ld(S,[]) ->
length(S);
ld([X|S],[X|T]) ->
ld(S,T);
ld([_SH|ST]=S,[_TH|TT]=T) ->
1 + lists:min([ld(S,TT),ld(ST,T),ld(ST,TT)]).
ld([]=S,... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
include "file.coh";
# Get filename from command line
ArgvInit();
var file := ArgvNext();
if file == (0 as [uint8]) then
print("error: no file name\n");
ExitWithError();
end if;
# Open the file
var fcb: FCB;
if FCBOpenIn(&fcb, file) != 0 then
print("error: cann... |
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... | #Run_BASIC | Run BASIC | for x = 1 to 20
for y = x to 20
for z = y to 20
if x^2 + y^2 = z^2 then print "[";x;",";y;",";z;"]"
next z
next y
next x |
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... | #Rust | Rust | fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> {
(1..=n).flat_map(move |x| {
(x..=n).flat_map(move |y| {
(y..=n).filter_map(move |z| {
if x.pow(2) + y.pow(2) == z.pow(2) {
Some([x, y, z])
} else {
None
}
... |
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... | #PowerShell | PowerShell |
function left-factorial ([BigInt]$n) {
[BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One)
[BigInt]$lfact = ([BigInt]::Zero)
while($k -lt $n){
if($k -gt ([BigInt]::Zero)) {
$fact = [BigInt]::Multiply($fact, $k)
$lfact = [BigInt]::Add($lfact, $fact)
... |
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
... | #Logo | Logo | ; Configuration parameters for Microsoft and BSD implementations
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
; Default seed is 0
make "_lcg_value 0
; set the seed
to lcg_seed :seed
make "_lcg_value :seed
end
; generate the next number in the series using the give... |
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
... | #Lua | Lua | local RNG = {
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
local state = 0
self.rnd = function()
state = (a * state + c) % m
return rand and rand(state) or state
end
self.seed = function(new_seed)
state = new_seed % m
end
return self
end
}... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Crystal | Crystal | p Time.leap_year?(2020)
p Time.leap_year?(2021)
p Time.leap_year?(2022) |
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)
| #D | D | import std.algorithm;
bool leapYear(in uint y) pure nothrow {
return (y % 4) == 0 && (y % 100 || (y % 400) == 0);
}
void main() {
auto good = [1600, 1660, 1724, 1788, 1848, 1912, 1972, 2032,
2092, 2156, 2220, 2280, 2344, 2348];
auto bad = [1698, 1699, 1700, 1750, 1800, 1810, 1900, 1901... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE MAXSIZE="20"
INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234... |
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... | #11l | 11l | T S_of_n_creator
Int n
i = 0
[Int] sample
F (n)
.n = n
F ()(item)
.i++
I .i <= .n
.sample.append(item)
E I random:(.i) < .n
.sample[random:(.n)] = item
V binarr = [0] * 10
V items = Array(0..9)
print(‘Single run samples for n = 3:’)
V s_of_n = S_of_n_creato... |
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... | #Ada | Ada | with Ada.Containers.Ordered_Maps;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Text_IO; use Ada.Text_IO;
procedure Power_Tree is
Debug_On : constant Boolean := False;
generic
type Result_Type is private;
Base : Result_Type;
Identity : Result_Type;
with function "*" (Lef... |
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 ... | #ALGOL_68 | ALGOL 68 | BEGIN
# multiplies in-place the elements of the matrix a by the scaler b #
OP *:= = ( REF[,]INT a, INT b )REF[,]INT:
BEGIN
FOR i FROM 1 LWB a TO 1 UPB a DO
FOR j FROM 2 LWB a TO 2 UPB a DO
a[ i, j ] *:= b
OD
OD;
a
END # *:= # ;
# return... |
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... | #J | J | visit=: {{
if.y{unvisited do.
unvisited=: 0 y} unvisited
visit y{::out
L=: y,L
end.
}}"0
assign=: {{
if._1=y{assigned do.
assigned=: x y} assigned
x&assign y{::in
end.
}}"0
kosaraju=: {{
out=: y
in=: <@I.|:y e.S:0~i.#y
unvisited=: 1#~#y
assigned=: _1#~#y
L=: i.0
visit"0 i.#y
... |
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... | #Java | Java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
... |
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 ... | #C | C |
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int row, col;
}cell;
int ROW,COL,SUM=0;
unsigned long raiseTo(int base,int power){
if(power==0)
return 1;
else
return base*raiseTo(base,power-1);
}
cell* kroneckerProduct(char* inputFile,int power){
FILE*... |
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... | #D | D | import std.stdio;
void repeat(int count, void delegate(int) action) {
for (int i=0; i<count; i++) {
action(i);
}
}
T nextInCycle(T)(T[] self, int index) {
return self[index % self.length];
}
T[] kolakoski(T)(T[] self, int len) {
T[] s;
s.length = len;
int i;
int k;
while (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... | #AutoIt | AutoIt |
#include <Date.au3>
$iYear = InputBox('Last Friday in each month', 'Please input the year:')
_GetLastFridays($iYear)
Func _GetLastFridays($_iYear)
Local $sResult = 'last fridays in ' & $_iYear & @LF, $iDay
Local $aDaysInMonth[12] = [31,28,31,30,31,30,31,31,30,31,30,31]
If _DateIsLeapYear($_iYear) Then $aDays... |
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... | #D | D | import std.algorithm : map;
import std.bigint;
import std.range;
import std.stdio;
BigInt factorial(BigInt n) {
if (n == 0) return BigInt(1);
BigInt res = 1;
while (n > 0) {
res *= n--;
}
return res;
}
BigInt lah(BigInt n, BigInt k) {
if (k == 1) return factorial(n);
if (k == 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... | #Go | Go | package main
import (
"fmt"
"strings"
)
var pokemon = `audino bagon baltoy...67 names omitted...`
func main() {
// split text into slice representing directed graph
var d []string
for _, l := range strings.Split(pokemon, "\n") {
d = append(d, strings.Fields(l)...)
}
fmt.Println... |
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,... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var source1 = new int[] { 1, 34, 3, 98, 9, 76, 45, 4 };
var source2 = new int[] { 54, 546, 548, 60 };
var largest1 = LargestPossibleSequence(source1);
var larg... |
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... | #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * 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 .
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Last[Prepend[DeleteCases[Divisors[#], #], 1]] & /@ Range[100] |
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 .
| #Modula-2 | Modula-2 | MODULE LargestProperDivisor;
FROM InOut IMPORT WriteCard, WriteLn;
VAR i: CARDINAL;
PROCEDURE lpd(n: CARDINAL): CARDINAL;
VAR i: CARDINAL;
BEGIN
IF n=1 THEN
RETURN 1;
END;
FOR i := n DIV 2 TO 1 BY -1 DO
IF n MOD i = 0 THEN
RETURN i;
END;
END;
END lpd;
BEG... |
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 .
| #Nim | Nim | import math, strutils
func largestProperDivisor(n: Positive): int =
for d in 2..sqrt(float(n)).int:
if n mod d == 0: return n div d
result = 1
for n in 1..100:
stdout.write ($n.largestProperDivisor).align(2), if n mod 10 == 0: '\n' else: ' ' |
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... | #C.2B.2B | C++ | #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 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... | #Clojure | Clojure | (defn gcd
[a b]
(if (zero? b)
a
(recur b, (mod a b))))
(defn lcm
[a b]
(/ (* a b) (gcd a b)))
;; to calculate the lcm for a variable number of arguments
(defn lcmv [& v] (reduce lcm v))
|
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... | #Visual_Basic_.NET | Visual Basic .NET | Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
... |
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 ... | #R | R | inputs <- cbind(combn(1:13, 2), rbind(seq_len(13), seq_len(13)))
inputs <- cbind(A = inputs[1, ], B = inputs[2, ])[sort.list(inputs[1, ]),]
Pythagoras <- inputs[, "A"]^2 + inputs[, "B"]^2
AtimesB <- inputs[, "A"] * inputs[, "B"]
CValues <- sqrt(cbind("C (90º)" = Pythagoras,
"C (60º)" = Pythagoras ... |
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 ... | #ERRE | ERRE |
PROGRAM LEVENSHTEIN
!$DYNAMIC
DIM D%[0,0]
PROCEDURE LEVENSHTEIN(S$,T$->RES%)
LOCAL I%,J%,M%
FOR I%=0 TO LEN(S$) DO
D%[I%,0]=I%
END FOR
FOR J%=0 TO LEN(T$) DO
D%[0,J%]=J%
END FOR
FOR J%=1 TO LEN(T$) DO
FOR I%=1 TO LEN(S$) DO
IF MID$(S$,I%,1)=M... |
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... | #D | D | void main() {
import std.stdio, std.ascii, std.algorithm, std.range;
uint[26] frequency;
foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15))
foreach (immutable c; buffer.filter!isAlpha)
frequency[c.toLower - 'a']++;
writefln("%(%(%s, %),\n%)", frequency[].chunks(10));
... |
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... | #Scala | Scala | def pythagoranTriangles(n: Int) = for {
x <- 1 to 21
y <- x to 21
z <- y to 21
if x * x + y * y == z * z
} yield (x, y, z) |
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... | #Scheme | Scheme |
(list-ec (:range x 1 21)
(:range y x 21)
(:range z y 21)
(if (= (* z z) (+ (* x x) (* y y))))
(list x y 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... | #Prolog | Prolog | leftfact(N):-
leftfact(N, 0, 0, 1).
leftfact(N, N, _, _):-
!.
leftfact(N, M, L, F):-
((M =< 10 ; (M =< 110, 0 is M mod 10)) ->
writef("!%w = %w\n", [M, L])
;
(0 is M mod 1000 ->
number_string(L, S),
string_length(S, Len),
writef("length of !%w is... |
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
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | BSDrand[x_] := Mod[x*1103515245 + 12345, 2147483648]
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
-> {0, 38, 7719, 21238, 2437... |
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
... | #Maxima | Maxima | seed: 0$
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
[38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612, 5853, 28100, 1142, 281,
20537, 15921, 8945, 26285, 2997, 14680]
seed: 0$
bsd_rand() := seed: mod(11035152... |
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)
| #Dart | Dart | class Leap {
bool leapYear(num year) {
return (year % 400 == 0) || (( year % 100 != 0) && (year % 4 == 0));
bool isLeapYear(int year) =>
(year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
// Source: https://api.flutter.dev/flutter/quiver.time/isLeapYear.html
}
} |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Ada | Ada | with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
with PDF_Out;
procedure Koch_Curve is
package Real_Math is
new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real);
use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO;
subtype Angle_Deg is Real;
type... |
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... | #Ada | Ada | generic
Sample_Size: Positive;
type Item_Type is private;
package S_Of_N_Creator is
subtype Index_Type is Positive range 1 .. Sample_Size;
type Item_Array is array (Index_Type) of Item_Type;
procedure Update(New_Item: Item_Type);
function Result return Item_Array;
end S_Of_N_Creator; |
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... | #BBC_BASIC | BBC BASIC | HIMEM = PAGE + 20000000
PRINT "Single run samples for n = 3:"
SofN% = FNs_of_n_creator(3)
FOR I% = 0 TO 9
!^a%() = FN(SofN%)(I%)
PRINT " For item " ; I% " sample(s) = " FNshowarray(a%(), I%+1)
NEXT
DIM cnt%(9)
PRINT '"Digit counts after 100000 runs:"
F... |
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... | #11l | 11l | T.enum Dir
UP
RIGHT
DOWN
LEFT
-V color_WHITE = Char(‘ ’)
-V color_BLACK = Char(‘#’)
F invert_color(&grid, x, y)
‘Invert the color of grid at x, y coordinate.’
I grid[y][x] == :color_BLACK
grid[y][x] = :color_WHITE
E
grid[y][x] = :color_BLACK
F next_direction(grid, x, y, =direction... |
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... | #EchoLisp | EchoLisp |
(lib 'tree)
;; displays a chain hit
(define (power-hit target chain)
(vector-push chain target)
(printf "L(%d) = %d - chain:%a "
target (1- (vector-length chain)) chain)
(vector-pop chain))
;; build the power-tree : add 1 level of leaf nodes
;; display all chains which lead to target
(define (add-level nod... |
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 ... | #APL | APL | kprod ← ⊃ (,/ (⍪⌿ (⊂[3 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 ... | #AppleScript | AppleScript | ------------ KRONECKER PRODUCT OF TWO MATRICES -------------
-- kprod :: [[Num]] -> [[Num]] -> [[Num]]
on kprod(xs, ys)
script concatTranspose
on |λ|(m)
map(my concat, my transpose(m))
end |λ|
end script
script
-- Multiplication by N over a list of lists
-... |
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... | #jq | jq |
# Fill an array of the specified length with the input value
def dimension($n): . as $in | [range(0;$n) | $in];
# $graph should be an adjacency-list graph with IO==0
def korasaju($graph):
($graph|length) as $length
| def init: {
vis: (false | dimension($length)), # visited
L: [], ... |
http://rosettacode.org/wiki/Kosaraju | Kosaraju |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin... | #Julia | Julia | function korasaju(g::Vector{Vector{T}}) where T<:Integer
# 1. For each vertex u of the graph, mark u as unvisited. Let L be empty.
vis = falses(length(g))
L = Vector{T}(length(g))
x = length(L) + 1
t = collect(T[] for _ in eachindex(g))
# Recursive
function visit(u::T)
if !vi... |
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... | #Kotlin | Kotlin | // version 1.1.3
/* the list index is the first vertex in the edge(s) */
val g = listOf(
intArrayOf(1), // 0
intArrayOf(2), // 1
intArrayOf(0), // 2
intArrayOf(1, 2, 4), // 3
intArrayOf(3, 5), // 4
intArrayOf(2, 6), // 5
intArrayOf(5), // 6
intArray... |
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 ... | #C.2B.2B | C++ | #include <cassert>
#include <vector>
#include <QImage>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_li... |
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... | #Go | Go | package main
import "fmt"
func nextInCycle(c []int, index int) int {
return c[index % len(c)]
}
func kolakoski(c []int, slen int) []int {
s := make([]int, slen)
i, k := 0, 0
for {
s[i] = nextInCycle(c, k)
if s[k] > 1 {
for j := 1; j < s[k]; j++ {
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... | #AWK | AWK |
# syntax: GAWK -f LAST_FRIDAY_OF_EACH_MONTH.AWK year
# converted from Fortran
BEGIN {
split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year
year = ARGV[1]
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
daynum_array[2] = 29
}
y = year - ... |
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... | #Dyalect | Dyalect | func fact(n) =>
n is 0 ? 1 : (n^-1..<0).Fold(1, (acc, val) => acc * val)
func lah(n, k) {
return fact(n) when k is 1
return 1 when k == n
return 0 when k > n || k < 1 || n < 1
(fact(n) * fact(n - 1)) / (fact(k) * fact(k - 1)) / fact(n - k)
}
print("Unsigned Lah numbers: L(n, k):");
print("n/k ",... |
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... | #Factor | Factor | USING: combinators combinators.short-circuit formatting infix io
kernel locals math math.factorials math.ranges prettyprint
sequences ;
IN: rosetta-code.lah-numbers
! Yes, Factor can do infix arithmetic with local variables!
! This is a good use case for it.
INFIX:: (lah) ( n k -- m )
( factorial(n) * factorial... |
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... | #FreeBASIC | FreeBASIC | function factorial( n as uinteger ) as ulongint
if n = 0 then return 1
return n*factorial(n-1)
end function
function s_Lah( n as uinteger, k as uinteger ) as ulongint
if n = k then return 1
if n = 0 orelse k = 0 then return 0
if k = 1 then return factorial(n)
return ((-1)^n)*(factorial(n)*fact... |
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... | #Haskell | Haskell | import Data.List
import qualified Data.ByteString.Char8 as B
allPokemon :: [B.ByteString]
allPokemon = map B.pack $ words
"audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon \
\cresselia croagunk darmanitan deino emboar emolga exeggcute gabite \
\girafarig gulpin haxorus heatmor he... |
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,... | #C.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
std::string findLargestConcat ( std::vector< int > & mynumbers ) {
std::vector<std::string> concatnumbers ;
std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ;
do {
std::ostringstream numberstream ;
... |
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... | #Haskell | Haskell | import Data.List (maximumBy, permutations, delete)
import Data.Ord (comparing)
import Data.Bool (bool)
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
ds :: [Int]
ds = [1, 2, 3, 4, 6, 7, 8, 9] -- 0 (and thus 5) are both unworkable
lcmDigits :: Int
lcmDigits = foldr1 lcm ds -- 504
sevenDigits :: [[Int... |
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 .
| #Pascal | Pascal |
program LarPropDiv;
function LargestProperDivisor(n:NativeInt):NativeInt;
//searching upwards to save time for example 100
//2..sqrt(n) aka 1..10 instead downwards n..sqrt(n) 100..10
var
i,j: NativeInt;
Begin
i := 2;
repeat
If n Mod i = 0 then
Begin
LargestProperDivisor := n DIV i;
EXIT;
... |
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 .
| #Perl | Perl | use strict;
use warnings;
use ntheory 'divisors';
use List::AllUtils <max natatime>;
sub proper_divisors {
my $n = shift;
return 1 if $n == 0;
my @d = divisors($n);
pop @d;
@d;
}
my @range = 1 .. 100;
print "GPD for $range[0] through $range[-1]:\n";
my $iter = natatime 10, @range;
while( my @batch = $iter... |
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... | #CLU | CLU | gcd = proc (m, n: int) returns (int)
m, n := int$abs(m), int$abs(n)
while n ~= 0 do m, n := n, m // n end
return(m)
end gcd
lcm = proc (m, n: int) returns (int)
if m=0 cor n=0
then return(0)
else return(int$abs(m*n) / gcd(m,n))
end
end lcm
start_up = proc ()
po: stream := st... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. show-lcm.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION lcm
.
PROCEDURE DIVISION.
DISPLAY "lcm(35, 21) = " FUNCTION lcm(35, 21)
GOBACK
.
END PROGRAM show-lcm... |
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... | #Wren | Wren | import "/sort" for Sort
import "/math" for Int
import "/fmt" for Fmt
// generate derangements of first n numbers, with 'start' in first place.
var dList = Fn.new { |n, start|
var r = []
start = start - 1 // use 0 basing
var a = [0] * n
for (i in 1...n) a[i] = i
a[start] = a[0]
a[0] = start
... |
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 ... | #Raku | Raku | multi triples (60, $n) {
my %sq = (1..$n).map: { .² => $_ };
my atomicint $i = 0;
my @triples[2*$n];
(1..^$n).race(:8degree).map: -> $a {
for $a^..$n -> $b {
my $cos = $a * $a + $b * $b - $a * $b;
@triples[$i⚛++] = $a, %sq{$cos}, $b if %sq{$cos}:exists;
}
}
... |
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 ... | #Euphoria | Euphoria | function min(sequence s)
atom m
m = s[1]
for i = 2 to length(s) do
if s[i] < m then
m = s[i]
end if
end for
return m
end function
function levenshtein(sequence s1, sequence s2)
integer n, m
sequence d
n = length(s1) + 1
m = length(s2) + 1
if n = 1 ... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Delphi | Delphi | proc nonrec main() void:
file() infile;
[256] char linebuf;
[256] word count;
*char line;
char c;
byte i;
word n;
channel input text filech;
channel input text linech;
for i from 0 upto 255 do count[i] := 0 od;
line := &linebuf[0];
open(filech, infile, "unixdict.txt")... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Sidef | Sidef | var n = 20
say gather {
for x in (1 .. n) {
for y in (x .. n) {
for z in (y .. n) {
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... | #Python | Python | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 1... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Nim | Nim | proc bsdRand(seed: int): iterator: int =
var state = seed
result = iterator: int =
while true:
state = (1_103_515_245 * state + 12_345) and 0x7fffffff
yield state
proc msvcrtRand(seed: int): iterator: int =
var state = seed
result = iterator: int =
while true:
state = (214_013 * stat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.