task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Kronecker_product_based_fractals | Kronecker product based fractals | This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the matrix (filled with 0/1) we ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type matrix [][]int
func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
m := len(m1)
n := len(m1[0])
p := len(m2)
q := len(m2[0])
rtn := m * p
ctn := n * q
r := make(matrix, rtn)
for i := range r {
r[i] = make([]int, ctn) // all elements zero by ... |
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... | #Lua | Lua | function next_in_cycle(c,length,index)
local pos = index % length
return c[pos]
end
function kolakoski(c,s,clen,slen)
local i = 0
local k = 0
while true do
s[i] = next_in_cycle(c,clen,k)
if s[k] > 1 then
for j=1,s[k]-1 do
i = i + 1
if i... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #C.2B.2B | C++ | #include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <cstdlib>
int main( int argc , char* argv[ ] ) {
using namespace boost::gregorian ;
greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul ,
Aug , Sep , Oct , Nov , Dec } ;
greg_year gy = atoi( argv[ 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... | #J | J |
NB. use: k lah n
lah=: ! :(!&<: * %&!~)&x: NB. `%~' is shorter than `*inv'
NB. wory_lah translates lah to algebraic English.
Monad =: :[: NB. permit only a y argument
Dyad =: [: : NB. require x and y arguments
but_1st =: &
decrement =: <: Monad
NB. ! means either factorial or combinations (just as - means 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... | #Java | Java |
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class LahNumbers {
public static void main(String[] args) {
System.out.println("Show the unsigned Lah numbers up to n = 12:");
for ( int n = 0 ; n <= 12 ; n++ ) {
System.out.printf("%5s", 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... | #JavaScript | JavaScript | /**
* Find the letter the word ends on
* @param {string} word
* @returns {string}
*/
const endsWith = word => word[word.length - 1];
/**
* Remove the used elements from the candidate elements
* @param {Array<string>} words Candidate words
* @param {Array<string>} used Used words
* @returns {*}
*/
const getCa... |
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,... | #Delphi | Delphi | defmodule RC do
def largest_int(list) do
sorted = Enum.sort(list, fn x,y -> "#{x}#{y}" >= "#{y}#{x}" end)
Enum.join(sorted)
end
end
IO.inspect RC.largest_int [1, 34, 3, 98, 9, 76, 45, 4]
IO.inspect RC.largest_int [54, 546, 548, 60] |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Elixir | Elixir | defmodule RC do
def largest_int(list) do
sorted = Enum.sort(list, fn x,y -> "#{x}#{y}" >= "#{y}#{x}" end)
Enum.join(sorted)
end
end
IO.inspect RC.largest_int [1, 34, 3, 98, 9, 76, 45, 4]
IO.inspect RC.largest_int [54, 546, 548, 60] |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Kotlin | Kotlin | // version 1.1.4-3
fun Int.divByAll(digits: List<Char>) = digits.all { this % (it - '0') == 0 }
fun main(args: Array<String>) {
val magic = 9 * 8 * 7
val high = 9876432 / magic * magic
for (i in high downTo magic step magic) {
if (i % 10 == 0) continue // can't end in '0'
val ... |
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... | #Lua | Lua | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
en... |
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 .
| #Quackery | Quackery | ' [ 1 ] 99 times
[ i^ 2 + factors
-2 peek join ]
echo |
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 .
| #R | R | largest_proper_divisor <- function(n){
if(n == 1) return(1)
lpd = 1
for(i in seq(1, n-1, 1)){
if(n %% i == 0)
lpd = i
}
message(paste0("The largest proper divisor of ", n, " is ", lpd))
return(lpd)
}
#Verify
for (i in 1:100){ #about 10 seconds to calculate until 10000
largest_prope... |
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 .
| #Raku | Raku | use Prime::Factor;
for 0, 2**67 - 1 -> $add {
my $start = now;
my $range = $add + 1 .. $add + 100;
say "GPD for {$range.min} through {$range.max}:";
say ( $range.hyper(:14batch).map: {$_ == 1 ?? 1 !! $_ %% 2 ?? $_ / 2 !! .&proper-divisors.max} )\
.batch(10)».fmt("%{$add.chars + 1}d").joi... |
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... | #DWScript | DWScript | PrintLn(Lcm(12, 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... | #Draco | Draco | proc gcd(word m, n) word:
word t;
while n /= 0 do
t := m;
m := n;
n := t % n
od;
m
corp
proc lcm(word m, n) word:
if m=0 or n=0
then 0
else m*n / gcd(m,n)
fi
corp
proc main() void:
writeln(lcm(12, 18))
corp |
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 ... | #Fortran | Fortran |
program demo_edit_distance
character(len=:),allocatable :: sources(:),targets(:)
integer,allocatable :: answers(:),expected(:)
sources=[character(len=20) :: "kitten", "rosettacode", "Saturday", "sleep", "qwerty", "Fortran" ]
targets=[character(len=20) :: "sitting", "raisethysword", "Sunday", "f... |
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... | #Elixir | Elixir | file = hd(System.argv)
File.read!(file)
|> String.upcase
|> String.graphemes
|> Enum.filter(fn c -> c =~ ~r/[A-Z]/ end)
|> Enum.reduce(Map.new, fn c,acc -> Map.update(acc, c, 1, &(&1+1)) end)
|> Enum.sort_by(fn {_k,v} -> -v end)
|> Enum.each(fn {k,v} -> IO.puts "#{k} #{v}" end) |
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... | #TI-89_BASIC | TI-89 BASIC | {1, 2, 3, 4} → a
seq(a[i]^2, i, 1, dim(a)) |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
... |
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... | #Ring | Ring |
a = leftFact(0,10,1)
see "" + a + nl
func leftFact f,t,s
see "------ From " + f + " --To -> " + t +" Step " + s + " -------" + nl
for i = f to t step s
leftFact = 1
fct = 1
for j = 1 to i - 1
fct = fct * j
leftFact = leftFact + fct
next
... |
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... | #Ruby | Ruby | left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf #yield left_factorial
lf += f
f *= n
end
end |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Phix | Phix | with javascript_semantics
atom seed
include builtins/mpfr.e
function BSDrnd()
-- oh dear, native only works on 64-bit,
-- as per ERRE and UCBLogo above on 32-bit...
-- seed = remainder(1103515245 * seed + 12345, #8000_0000)
-- so, resort to gmp, with the added twist than both
-- 1103515245 and #8... |
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)
| #Emacs_Lisp | Emacs Lisp | (defun leap-year-p (year)
(apply (lambda (a b c) (or a (and (not b) c)))
(mapcar (lambda (n) (zerop (mod year n)))
'(400 100 4)))) |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Factor | Factor | USING: accessors images images.testing images.viewer kernel
literals math math.constants math.functions sequences ;
IN: rosetta-code.koch-curve
CONSTANT: order 17
CONSTANT: theta 1.047197551196598 ! 60 degrees in radians
CONSTANT: move-distance 0.25
CONSTANT: dim { 600 400 }
CONSTANT: offset-x 500
CONSTANT: offs... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Forth | Forth | include lib/graphics.4th
include lib/math.4th
include lib/enter.4th
: (p3&p5) 2* + 3 / ; ( n1 n2 -- n2+n2+n1/3)
: (p3) rot (p3&p5) >r swap (p3&p5) r> ;
: (p5) rot swap (p3&p5) >r (p3&p5) r> ;
: (*/10K) * 10K 2 / + 10K / ; ( n1 n2 -- n1*n2/10000)
: koch ( x1... |
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... | #D | D | import std.stdio, std.random;
auto sofN_creator(in int n) {
size_t i;
int[] sample;
return (in int item) {
i++;
if (i <= n)
sample ~= item;
else if (uniform01 < (double(n) / i))
sample[uniform(0, n)] = item;
return sample;
};
}
void main() {
... |
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... | #Elena | Elena | import system'dynamic;
import extensions;
import system'routines;
import system'collections;
extension algorithmOp
{
s_of_n()
{
var counter := new Integer();
var n := self;
^ new ArrayList().mixInto(new
{
eval(i)
{
counter.append:1;
... |
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... | #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
; Directions
Directions := {0: "North", 1: "East", 2: "South", 3: "West"}
; Initialize the plane (set all cells to white)
White := 0xFFFFFF
Plane := []
PW := PH := 100
loop, % PH {
I := A_Index
loop, % PW
Plane[I, A_Index] := White
}
; Let it run
DI := D := 0 ; initial 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... | #J | J | knuth_power_tree=:3 :0
L=: P=: %(1+y){._ 1
findpath=: ]
while. _ e.P do.
for_n.(/: findpath&>)I.L=>./L-._ do.
for_a. findpath n do.
j=. n+a
l=. 1+n{L
if. j>y do. break. end.
if. l>:j{ L do. continue. end.
L=: l j} L
P=: n j} P
end.
findpa... |
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... | #Java | Java | import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PowerTree {
private static Map<Integer, Integer> p = new HashMap<>();
private static List<List<Integer>> lvl = new ArrayList<>();
static {
p.put(1, 0);
... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #C.2B.2B | C++ | #include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
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<... |
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... | #Raku | Raku | sub kosaraju (%k) {
my %g = %k.keys.sort Z=> flat ^%k;
my %h = %g.invert;
my %visited;
my @stack;
my @transpose;
my @connected;
sub visit ($u) {
unless %visited{$u} {
%visited{$u} = True;
for |%k{$u} -> $v {
visit($v);
@transp... |
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 ... | #Go | Go | package main
import "fmt"
type matrix [][]int
func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
m := len(m1)
n := len(m1[0])
p := len(m2)
q := len(m2[0])
rtn := m * p
ctn := n * q
r := make(matrix, rtn)
for i := range r {
r[i] = make([]int, ctn) // all elements zero by ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[KolakoskiGen]
KolakoskiGen[start_List, its_Integer] := Module[{c, s, k, cnext, sk},
s = {};
k = 1;
c = start;
Do[
cnext = First[c];
c = RotateLeft[c];
AppendTo[s, cnext];
sk = s[[k]];
If[sk > 1,
s = Join[s, ConstantArray[cnext, sk - 1]]
];
k += 1;
,
{its}
];
s
]
... |
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... | #Nim | Nim | template nextInCycle(a: openArray[int]; index: Natural): int =
a[index mod a.len]
#---------------------------------------------------------------------------------------------------
func kolakoski(a: openArray[int]; length: Positive): seq[int] =
result.setLen(length)
var i, k = 0
while true:
result... |
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... | #Perl | Perl | sub kolakoski {
my($terms,@seed) = @_;
my @k;
my $k = $seed[0] == 1 ? 1 : 0;
if ($k == 1) { @k = (1, split //, (($seed[1]) x $seed[1])) }
else { @k = ($seed[0]) x $seed[0] }
do {
$k++;
push @k, ($seed[$k % @seed]) x $k[$k];
} until $terms <= @k;
@k[0..$terms-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... | #Clojure | Clojure | (use '[clj-time.core :only [last-day-of-the-month day-of-week minus days]]
'[clj-time.format :only [unparse formatters]])
(defn last-fridays [year]
(let [last-days (map #(last-day-of-the-month year %) (range 1 13 1))
dow (map day-of-week last-days)
relation (zipmap last-days dow)]
(map ... |
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... | #jq | jq | ## Generic functions
def factorial: reduce range(2;.+1) as $i (1; . * $i);
# nCk assuming n >= k
def binomial($n; $k):
if $k > $n / 2 then binomial($n; $n-$k)
else (reduce range($k+1; $n+1) as $i (1; . * $i)) as $numerator
| reduce range(1;1+$n-$k) as $i ($numerator; . / $i)
end;
def lpad($len): tostring... |
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... | #Julia | Julia | using Combinatorics
function lah(n::Integer, k::Integer, signed=false)
if n == 0 || k == 0 || k > n
return zero(n)
elseif n == k
return one(n)
elseif k == 1
return factorial(n)
else
unsignedvalue = binomial(n, k) * binomial(n - 1, k - 1) * factorial(n - k)
if si... |
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... | #jq | jq | # convert a list of unique words to a dictionary
def dictionary:
reduce .[] as $word ({}; .[$word[0:1]] += [$word]) ;
# remove "word" from the input dictionary assuming the key is already there:
def remove(word):
.[word[0:1]] -= [word]; |
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... | #Julia | Julia | using IterTools.groupby
orderwords(words::Vector) = Dict(w[1][1] => Set(w) for w in groupby(first, words))
longest(a, b) = ifelse(length(a) > length(b), a, b)
function linkfirst(byfirst::Dict, sofar::Vector)
@assert(!isempty(sofar))
chmatch = sofar[end][end]
if ! haskey(byfirst, chmatch) return sofar end
... |
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,... | #Erlang | Erlang |
-module( largest_int_from_concatenated ).
-export( [ints/1, task/0] ).
ints( Ints ) ->
Int_strings = [erlang:integer_to_list(X) || X <- Ints],
Pad_ints = [{X ++ X, X} || X <- Int_strings],
erlang:list_to_integer( lists:append([Int || {_Pad, Int} <- lists:reverse(lists:sort(Pad_ints))]) ).
task() ->
[io:fwri... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Max@Select[FromDigits/@Rest@Flatten[Permutations/@Subsets[Range@9,9],1],And@@IntegerQ/@(#/IntegerDigits@#)&] |
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... | #Nanoquery | Nanoquery | s = ""
def uniqueDigits(i)
global s
// returns true, if unique digits, false otherwise
for k in range(0, len(s) - 2)
for l in range(k + 1, len(s) - 1)
if (s[l] = "0") || (s[l] = "5")
//0 or 5 digit
... |
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 .
| #REXX | REXX | /*REXX program finds the largest proper divisors of all numbers (up to a given limit). */
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 101 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 ... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #Ring | Ring | ? "working..."
limit = 100
? "Largest proper divisor up to " + limit + " are:"
see " 1 "
col = 1
for n = 2 to limit
for m = 1 to n >> 1
if n % m = 0 div = m ok
next
if div < 10 see " " ok
see "" + div + " "
if col++ % 10 = 0 ? "" ok
next
? "done..." |
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... | #EchoLisp | EchoLisp |
(lcm 0 9) → 0
(lcm 444 888)→ 888
(lcm 888 999) → 7992
(define (lcm* list) (foldl lcm (first list) list)) → lcm*
(lcm* '(444 888 999)) → 7992
|
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... | #Elena | Elena | import extensions;
import system'math;
gcd = (m,n => (n == 0) ? (m.Absolute) : (gcd(n,n.mod:m)));
lcm = (m,n => (m * n).Absolute / gcd(m,n));
public program()
{
console.printLine("lcm(12,18)=",lcm(12,18))
} |
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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Uses the "iterative with two matrix rows" algorithm
' referred to in the Wikipedia article.
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
Function levenshtein(s As String, t As String) As Integer
' degenerate cases
If s = t Then Return 0
... |
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... | #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(letter_frequency).
-export([main/0, letter_freq/1]).
main() ->
case file:read_file("file.txt") of
{ok, FileData} ->
letter_freq(binary_to_list(FileData));
_FileNotExist ->
io:format("File do not exist~n")
end.
letter_freq(Data) ->
lists:foreach(fun(Char) ->
Let... |
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... | #Visual_Prolog | Visual Prolog |
implement main
open core, std
domains
pythtrip = pt(integer, integer, integer).
class predicates
pythTrips : (integer) -> pythtrip nondeterm (i).
clauses
pythTrips(Limit) = pt(X,Y,Z) :-
X = fromTo(1,Limit),
Y = fromTo(X,Limit),
Z = fromTo(Y,Limit),
Z^2 = X^2 + Y^2... |
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... | #Run_BASIC | Run BASIC | a = lftFct(0,10,1)
a = lftFct(20,110,10)
a = lftFct(1000,10000,1000)
function lftFct(f,t,s)
print :print "------ From ";f;" --To-> ";t;" Step ";s;" -------"
for i = f to t step s
lftFct = 1
fct = 1
for j = 1 to i-1
fct = fct * j
lftFct = lftFct + fct
next j
if i >= 1000 then
print i;" ";len(str$(lftFct));"... |
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... | #Rust | Rust |
#[cfg(target_pointer_width = "64")]
type USingle = u32;
#[cfg(target_pointer_width = "64")]
type UDouble = u64;
#[cfg(target_pointer_width = "64")]
const WORD_LEN: i32 = 32;
#[cfg(not(target_pointer_width = "64"))]
type USingle = u16;
#[cfg(not(target_pointer_width = "64"))]
type UDouble = u32;
#[cfg(not(target_poi... |
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
... | #PHP | PHP | <?php
function bsd_rand($seed) {
return function() use (&$seed) {
return $seed = (1103515245 * $seed + 12345) % (1 << 31);
};
}
function msvcrt_rand($seed) {
return function() use (&$seed) {
return ($seed = (214013 * $seed + 2531011) % (1 << 31)) >> 16;
};
}
$lcg = bsd_rand(0);
echo ... |
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)
| #Erlang | Erlang |
-module(gregorian).
-export([leap/1]).
leap( Year ) -> calendar:is_leap_year( Year ).
|
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #FreeBASIC | FreeBASIC |
Const Pi = 4 * Atn(1)
Const RtoD = 180 / Pi
Const DtoR = Pi / 180
Dim Shared As Single posX = 260, posY = 90, angulo = 0
Screen 19 : Color 0,15
Sub kochLado(longitud As Integer, fondo As Integer)
Dim As Single dx, dy
If fondo = 0 Then
dx = Cos(angulo*DtoR) * longitud
dy = Sin(angulo*DtoR... |
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... | #Elixir | Elixir |
defmodule Knuth do
def s_of_n_creator(n), do: {n, 1, []}
def s_of_n({n, i, ys}, x) do
cond do
i <= n -> {n, i+1, [x|ys]}
:rand.uniform(i) <= n ->
{n, i+1, List.replace_at(ys, :rand.uniform(n)-1, x)}
true -> {n, i+1, ys}
end
end
end
results = Enum.reduce(1..100000, %{}, ... |
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... | #F.23 | F# |
let N=System.Random 23 //Nigel Galloway: August 7th., 2018
let s_of_n_creator i = fun g->Seq.fold(fun (n:_[]) g->if N.Next()%(g+1)>i-1 then n else n.[N.Next()%i]<-g;n) (Array.ofSeq (Seq.take i g)) (Seq.skip i g)
let s_of_n<'n> = s_of_n_creator 3
printfn "using an input array -> %A" (List.init 100000 (fun _->s_of_n [|... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #AutoIt | AutoIt |
Global $iCountMax = 100000
Global $aFields[100][100][2]
Global $iDelayStep = 10 ; stop between steps in msec
Global $aDirection[4][4] = [ _ ; [ direction 0-3 ][ left change x, y, right change x, y ]
[-1, 0, +1, 0], _ ; == direction 0
[ 0, -1, 0, +1], _ ; == direction 1
[+1, 0, -1, 0], _ ; == direction 2... |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #jq | jq | # Input: {p, lvl, path}
def kpath($n):
if $n == 0 then .path=[]
else until( .p[$n|tostring];
.q = []
| reduce .lvl[0][] as $x (.;
kpath($x)
| label $out
| foreach (.path[], null) as $y (.;
if $y == null then .
else (($x + $y)|tos... |
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... | #Julia | Julia | module KnuthPowerTree
const p = Dict(1 => 0)
const lvl = [[1]]
function path(n)
global p, lvl
iszero(n) && return Int[]
while n ∉ keys(p)
q = Int[]
for x in lvl[1], y in path(x)
if (x + y) ∉ keys(p)
p[x + y] = x
push!(q, x + y)
end
... |
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 ... | #D | D |
import std.stdio, std.outbuffer;
alias Matrix = uint[][];
string toString(Matrix m) {
auto ob = new OutBuffer();
foreach(row; m) {
//The format specifier inside the %(...%) is
//automatically applied to each element of a range
//Thus prints each line flanked by |
ob.writef... |
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... | #Sidef | Sidef | func korasaju(Array g) {
# 1. For each vertex u of the graph, mark u as unvisited. Let L be empty.
var vis = g.len.of(false)
var L = []
var x = g.end
var t = g.len.of { [] }
# Recursive
func visit(u) {
if (!vis[u]) {
vis[u] = true
g[u].each {|v|
... |
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... | #Standard_ML | Standard ML | datatype 'a node = Node of 'a * bool ref * 'a node list ref * 'a node list ref
fun node x = Node (x, ref false, ref nil, ref nil)
fun mark (Node (_, r, _, _)) = !r before r := true
fun unmark (Node (_, r, _, _)) = !r before r := false
fun value (Node (x, _, _, _)) = x
fun sources (Node (_, _, ref xs, _)) = xs
fun t... |
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 ... | #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
import Reflex
import Reflex.Dom
import Data.Map as DM (Map, fromList)
import Data.Text (Text, pack)
import Data.List (transpose)
-- Show Vicsek and Sierpinski Carpet fractals
main :: IO ()
main = mainWidget $ do
elAttr "h1" ("style" =: "color:black") $ text "Kroneker Product Base... |
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... | #Phix | Phix | with javascript_semantics
function kolakoski(sequence cycle, integer n)
sequence s = {}
integer k = 1
while length(s)<n do
integer c = cycle[mod(k-1,length(cycle))+1]
s &= repeat(c,iff(k>length(s)?c:s[k]))
k += 1
end while
s = s[1..n]
return s
end function
function poss... |
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... | #COBOL | COBOL |
program-id. last-fri.
data division.
working-storage section.
1 wk-date.
2 yr pic 9999.
2 mo pic 99 value 1.
2 da pic 99 value 1.
1 rd-date redefines wk-date pic 9(8).
1 binary.
2 int-date pic 9(8).
2 dow pic 9(4).
2 friday pic ... |
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... | #Kotlin | Kotlin | import java.math.BigInteger
fun factorial(n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) return BigInteger.ONE
if (n == BigInteger.ONE) return BigInteger.ONE
var prod = BigInteger.ONE
var num = n
while (num > BigInteger.ONE) {
prod *= num
num--
}
return prod
}
fun... |
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... | #Kotlin | Kotlin | // version 1.1.2
var maxPathLength = 0
var maxPathLengthCount = 0
val maxPathExample = StringBuilder(500)
val names = arrayOf(
"audino", "bagon", "baltoy", "banette", "bidoof",
"braviary", "bronzor", "carracosta", "charmeleon", "cresselia",
"croagunk", "darmanitan", "deino", "emboar", "emolga",
"... |
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,... | #F.23 | F# |
// Form largest integer which is a permutation from a list of integers. Nigel Galloway: March 21st., 2018
let fN g = List.map (string) g |> List.sortWith(fun n g->if n+g<g+n then 1 else -1) |> System.String.Concat
|
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,... | #Factor | Factor | USING: assocs io kernel math qw sequences sorting ;
IN: rosetta-code.largest-int
: pad ( target seq -- padded )
2dup length / swap <repetition> concat swap head ;
: largest-int ( seq -- )
dup dup [ length ] map supremum ! find longest length so we know how much to pad
[ swap pad ] curry map ... |
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... | #Nim | Nim | type Digit = range[0..9]
iterator digits(n: int64): Digit =
var n = n
while true:
yield n mod 10
n = n div 10
if n == 0: break
func isLynchBell(num: int64): bool =
var hSet: set[Digit]
for d in num.digits:
if d == 0 or num mod d != 0 or d in hSet:
return false
hSet.incl(d)
return... |
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... | #Perl | Perl | my $step = 9 * 8 * 7; # 504, interval between tests
my $initial = int(9876432 / $step) * $step; # largest 7 digit multiple of 504 < 9876432
for($test = $initial; $test > 0 ; $test -= $step) { # decrement by 504
next if $test =~ /[05]/; # skip numbers ... |
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 .
| #Ruby | Ruby | require 'prime'
def a(n)
return 1 if n == 1 || n.prime?
(n/2).downto(1).detect{|d| n.remainder(d) == 0}
end
(1..100).map{|n| a(n).to_s.rjust(3)}.each_slice(10){|slice| puts slice.join}
|
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 .
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: largestProperDivisor (in integer: number) is func
result
var integer: divisor is 0;
begin
if not odd(number) then
divisor := number >> 1;
else
divisor := number div 3 - 1;
if odd(divisor) then
divisor +:= 2;
else
inc... |
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 .
| #Swift | Swift | import Foundation
func largestProperDivisor(_ n : Int) -> Int? {
guard n > 0 else {
return nil
}
if (n & 1) == 0 {
return n >> 1
}
var p = 3
while p * p <= n {
if n % p == 0 {
return n / p
}
p += 2
}
return 1
}
for n in (1..<101) {
... |
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... | #Elixir | Elixir | defmodule RC do
def gcd(a,0), do: abs(a)
def gcd(a,b), do: gcd(b, rem(a,b))
def lcm(a,b), do: div(abs(a*b), gcd(a,b))
end
IO.puts RC.lcm(-12,15) |
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... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(lcm).
-export([main/0]).
main() ->
lcm(-3,4).
gcd(A, 0) ->
A;
gcd(A, B) ->
gcd(B, A rem B).
lcm(A,B) ->
abs(A*B div gcd(A,B)). |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Frink | Frink | println[editDistance["kitten","sitting"]] |
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... | #ERRE | ERRE | PROGRAM LETTER
DIM CNT[255]
BEGIN
OPEN("I",1,"f:\errev30\erre.hlp")
REPEAT
GET(#1,A$)
L%=LEN(A$)
IF L%>0 THEN
FOR I%=1 TO L% DO
A%=ASC(MID$(A$,I%))
CNT[A%]+=1
END FOR
END IF
UNTIL EOF(1)
CLOSE(1)
FOR 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... | #Wrapl | Wrapl | ALL WITH x <- 1:to(n), y <- x:to(n), z <- y:to(n) DO (x^2 + y^2 = z^2) & [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... | #Wren | Wren | var pythTriples = Fiber.new { |n|
(1..n-2).each { |x|
(x+1..n-1).each { |y|
(y+1..n).each { |z| (x*x + y*y == z*z) && Fiber.yield([x, y, z]) }
}
}
}
var n = 20
while (!pythTriples.isDone) {
var res = pythTriples.call(n)
res && System.print(res)
} |
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... | #Scala | Scala | object LeftFactorial extends App {
// this part isn't really necessary, it just shows off Scala's ability
// to match the mathematical syntax: !n
implicit class RichInt(n:Int) {
def unary_!() = factorial.take(n).sum
}
val factorial: Stream[BigInt] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * ... |
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
... | #Picat | Picat | go =>
% BSD
println(bsd=[bsd() : _ in 1..10]),
bsd_seed(1),
println(bsd2=[bsd() : _ in 1..10]),
% MS
println(ms=[ms() : _ in 1..10]),
ms_seed(1),
println(ms2=[ms() : _ in 1..10]),
nl.
% BSD
bsd_seed(Seed) =>
get_global_map().put(bsd_state, Seed).
bsd = Rand =>
M = get_global_map(),
See... |
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)
| #ERRE | ERRE | PROGRAM LEAP_YEAR
FUNCTION LEAP(YR%)
LEAP=(YR% MOD 4=0) AND ((YR% MOD 400=0) OR (YR% MOD 100<>0))
END FUNCTION
BEGIN
LOOP
INPUT("Enter a year: ",year%)
EXIT IF YEAR%=0
IF LEAP(year%) THEN
PRINT(year%;" is a leap year")
ELSE
PRINT(year%;" is not a l... |
http://rosettacode.org/wiki/Koch_curve | Koch curve | Draw a Koch curve. See details: Koch curve
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3 // 60 degrees
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*math.... |
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... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
... |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #AWK | AWK |
# usage: awk -v debug=0 -f langton.awk
# Simulates the cellular automaton "Langton's ant",
# see http://en.wikipedia.org/wiki/Langton%27s_ant
function turnRight() {
dir++
if( dir>4 ) { dir=1 }
}
function turnLeft() {
dir--
if( dir<1 ) { dir=4 }
}
function move() {
if (dir==1) { y--; z="^" }
if (dir==3) { ... |
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... | #Kotlin | Kotlin | // version 1.1.3
import java.math.BigDecimal
var p = mutableMapOf(1 to 0)
var lvl = mutableListOf(listOf(1))
fun path(n: Int): List<Int> {
if (n == 0) return emptyList<Int>()
while (n !in p) {
val q = mutableListOf<Int>()
for (x in lvl[0]) {
for (y in path(x)) {
... |
http://rosettacode.org/wiki/Kronecker_product | Kronecker product | Kronecker product
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement the Kronecker product of two matrices (arbitrary sized) resulting in a block matrix.
Test cases
Show results for each of the following two samples:
Sample 1 (from ... | #Factor | Factor | USING: kernel math.matrices.extras prettyprint ;
{ { 1 2 } { 3 4 } }
{ { 0 5 } { 6 7 } }
{ { 0 1 0 } { 1 1 1 } { 0 1 0 } }
{ { 1 1 1 1 } { 1 0 0 1 } { 1 1 1 1 } }
[ kronecker-product . ] 2bi@ |
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 ... | #Fortran | Fortran | MODULE ARRAYMUSH !A rather small collection.
CONTAINS !For the specific problem only.
SUBROUTINE KPRODUCT(A,B,AB) !AB = Kronecker product of A and B, both two-dimensional arrays.
Considers the arrays to be addressed as A(row,column), despite any storage order arrangements. .
Creating array ... |
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... | #Swift | Swift | func kosaraju(graph: [[Int]]) -> [Int] {
let size = graph.count
var x = size
var vis = [Bool](repeating: false, count: size)
var l = [Int](repeating: 0, count: size)
var c = [Int](repeating: 0, count: size)
var t = [[Int]](repeating: [], count: size)
func visit(_ u: Int) {
guard !vis[u] else {
... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Inte... |
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 ... | #J | J | V=: -.0 2 6 8 e.~i.3 3
S=: 4 ~:i.3 3
KP=: 1 3 ,/"2@(,/)@|: */
ascii_art=: ' *'{~]
KPfractal=:dyad def 'x&KP^:y,.1' |
http://rosettacode.org/wiki/Kronecker_product_based_fractals | Kronecker product based fractals | This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the matrix (filled with 0/1) we ... | #Java | Java |
package kronecker;
/**
* Uses the Kronecker product powers of two rectangular matrices
* to generate fractals and tests it with three examples.
*/
public class ProductFractals {
/**
* Find the Kronecker product of the arguments.
* @param a The first matrix to multiply.
* @param b The second matrix to ... |
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... | #Python | Python | import itertools
def cycler(start_items):
return itertools.cycle(start_items).__next__
def _kolakoski_gen(start_items):
s, k = [], 0
c = cycler(start_items)
while True:
c_next = c()
s.append(c_next)
sk = s[k]
yield sk
if sk > 1:
s += [c_next] * (sk - ... |
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... | #CoffeeScript | CoffeeScript |
last_friday_of_month = (year, month) ->
# month is 1-based, JS API is 0-based, then we use
# non-positive indexes to work backward relative to the
# first day of the next month
i = 0
while true
last_day = new Date(year, month, i)
if last_day.getDay() == 5
return last_day.toDateString()
i ... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Lah]
Lah[n_?Positive, 0] := 0
Lah[0, k_?Positive] := 0
Lah[n_, n_] := 1
Lah[n_, 1] := n!
Lah[n_, k_] := (-1)^n (n! ((n - 1)!))/((k! ((k - 1)!)) ((n - k)!))
Table[Lah[i, j], {i, 0, 12}, {j, 0, 12}] // Grid
Max[Lah[100, Range[0, 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... | #Nim | Nim | import math, strutils
import bignum
func lah[T: int | Int](n, k: T; signed = false): T =
if n == 0 or k == 0 or k > n: return when T is int: 0 else: newInt(0)
if n == k: return when T is int: 1 else: newInt(1)
if k == 1: return fac(n)
result = binom(n, k) * binom(n - 1, k - 1) * fac(n - k)
if signed and (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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
use List::Util qw(max);
sub Lah {
my($n, $k) = @_;
return factorial($n) if $k == 1;
return 1 if $k == $n;
return 0 if $k > $n;
return 0 if $k < 1 or $n < 1;
(factorial($n) * factorial($n - 1)) / (factorial($k) * factorial(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.