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/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Vedit_macro_language | Vedit macro language | for (#1 = 1; #1 <= 5; #1++) {
for (#2 = 1; #2 <= #1; #2++) {
Type_Char('*')
}
Type_Newline
} |
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... | #Fortran | Fortran | MODULE LAIROTCAF !Calculates "left factorials".
CONTAINS !The usual suspects.
INTEGER*8 FUNCTION FACT(N) !Factorial, the ordinary.
INTEGER N !The number won't ever get far.
INTEGER I !The stepper.
FACT = 1 !Here we go.
DO I = 2,N !Does nothing for 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
... | #Delphi | Delphi |
program Linear_congruential_generator;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Winapi.Windows;
type
TRandom = record
private
FSeed: Cardinal;
FBsdCurrent: Cardinal;
FMsvcrtCurrent: Cardinal;
class function Next(seed, a, b: Cardinal): Cardinal; static;
public
constructor... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Plain_English | Plain English | To run:
Start up.
Write "First 25 Leonardo numbers:" on the console.
Show 25 of the Leonardo numbers starting with 1 and 1 and using 1 for the add number.
Write "First 25 Leonardo numbers with L(0)=0, L(1)=1, add=0:" on the console.
Show 25 of the Leonardo numbers starting with 0 and 1 and using 0 for the add number.
W... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #PureBasic | PureBasic |
EnableExplicit
#N = 25
Procedure leon_R(a.i, b.i, s.i = 1, n.i = #N)
If n>2
Print(Space(1) + Str(a + b + s))
ProcedureReturn leon_R(b, a + b + s, s, n-1)
EndIf
EndProcedure
If OpenConsole()
Define r$
Print("Enter first two Leonardo numbers and increment step (separated by space) : ... |
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)
| #ALGOL_W | ALGOL W | begin
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
logical procedure isLeapYear ( integer value year ) ;
year rem 400 = 0 or ( year rem 4 = 0 and year rem 100 not = 0 );
% some test cases ... |
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)
| #ALGOL-M | ALGOL-M |
BEGIN
% COMPUTE P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN 1 IF Y IS A LEAP YEAR, OTHERWISE 0 %
INTEGER FUNCTION ISLEAP(Y);
INTEGER Y;
BEGIN
IF MOD(Y,4) <> 0 THEN % QUICK EXIT IN MOST CASES %
ISLEAP := 0
ELSE IF MOD(Y,400) = 0 THEN
ISLEAP := ... |
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... | #Action.21 | Action! | CARD FUNC Lcm(CARD a,b)
CARD tmp,c
IF a=0 OR b=0 THEN
RETURN (0)
FI
IF a<b THEN
tmp=a a=b b=tmp
FI
c=0
DO
c==+1
UNTIL a*c MOD b=0
OD
RETURN(a*c)
PROC Test(CARD a,b)
CARD res
res=Lcm(a,b)
PrintF("LCM of %I and %I is %I%E",a,b,res)
RETURN
PROC Main()
Test(4,6)
Test(120,7... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Lcm_Test is
function Gcd (A, B : Integer) return Integer is
M : Integer := A;
N : Integer := B;
T : Integer;
begin
while N /= 0 loop
T := M;
M := N;
N := T mod N;
end loop;
return M;
end Gcd;
func... |
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 ... | #C | C | /*
* RossetaCode: Law of cosines - triples
*
* An quick and dirty brute force solutions with O(N^3) cost.
* Anyway it is possible set MAX_SIDE_LENGTH equal to 10000
* and use fast computer to obtain the "extra credit" badge.
*
* Obviously, there are better algorithms.
*/
#include <stdio.h>
#include <math.h>
... |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form/Randomizing_using_Jacobson_and_Matthews%E2%80%99_Technique | Latin Squares in reduced form/Randomizing using Jacobson and Matthews’ Technique | Section 3.3 of [Generalised 2-designs with Block Size 3(Andy L. Drizen)] describes a method of generating Latin Squares of order n attributed to Jacobson and Matthews. The purpose of this task is to produce a function which given a valid Latin Square transforms it to another using this method.
part 1
Use one of the 4 ... | #Raku | Raku | # 20210729 Raku programming solution
#!/usr/bin/env raku
sub makeCube(\from, Int \n) {
my @c = [[[ 0 xx n ] xx n ] xx n ];
from.Bool ?? do race for ^n X ^n -> (\i,\j) { @c[i;j; { from[i;j]-1 } ] = 1 }
!! do race for ^n X ^n -> (\i,\j) { @c[i;j; { (i+j)%n } ] = 1 }
return @c ... |
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 ... | #C | C | #include <stdio.h>
#include <string.h>
/* s, t: two strings; ls, lt: their respective length */
int levenshtein(const char *s, int ls, const char *t, int lt)
{
int a, b, c;
/* if either string is empty, difference is inserting all chars
* from the other
*/
if (!ls) return ... |
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... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
on letterFrequencyinFile(theFile)
-- Read the file as an NSString, letting the system guess the encoding.
set fileText to current application's class "NSString"'s stringWithContentsOfFile:(POSIX ... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Z80_Assembly | Z80 Assembly | org &1000
ld b,3
ld ix,array1
loop:
ld a,(ix)
call &bb5a ;prints character to screen
ld a,(ix+3)
call &bb5a
ld a,(ix+6)
call &bb5a
ld a,13
call &bb5a
ld a,10
call &bb5a
inc ix
djnz loop
ret
array1:
db "abc"
array2:
db "ABC"
array3:
db "123" |
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... | #Mercury | Mercury |
:- module pythtrip.
:- interface.
:- import_module io.
:- import_module int.
:- type triple ---> triple(int, int, int).
:- pred pythTrip(int::in,triple::out) is nondet.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list.
:- import_module solutions.
:- import_module math.
pythTrip(Li... |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Verilog | Verilog |
module main;
integer i, j;
initial begin
for(i = 1; i <= 5; i = i + 1) begin
for(j = 1; j <= i; j = j + 1) $write("*");
$display("");
end
$finish ;
end
endmodule
|
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#include "gmp.bi"
Sub leftFactorial(rop As __mpz_struct, op As ULong)
Dim As __mpz_struct t1
mpz_init_set_ui(@t1, 1)
mpz_set_ui(@rop, 0)
For i As ULong = 1 To op
mpz_add(@rop, @rop, @t1)
mpz_mul_ui(@t1, @t1, i)
Next
mpz_clear(@t1)
End Sub
Function digitCount(op As __mpz_struc... |
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
... | #EDSAC_order_code | EDSAC order code |
[Linear congruential generators for pseudo-random numbers.
EDSAC program, Initial Orders 2.]
[Library subroutine R9, to read integer constants at load time.
See Wilkes, Wheeler & Gill, 1951 edition, pages 98 & 148.]
..PK
T 56 K [must be loaded at 56]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Python | Python | def Leonardo(L_Zero, L_One, Add, Amount):
terms = [L_Zero,L_One]
while len(terms) < Amount:
new = terms[-1] + terms[-2]
new += Add
terms.append(new)
return terms
out = ""
print "First 25 Leonardo numbers:"
for term in Leonardo(1,1,1,25):
out += str(term) + " "
print out
out =... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Quackery | Quackery | [ 1 1 1 ] is leo ( --> n n n )
[ 0 1 0 ] is fibo ( --> n n n )
[ 2 1 0 ] is lucaso ( --> n n n )
[ temp put
rot times
[ tuck +
temp share + ]
temp release drop ] is nardo ( n n n n --> n )
say "Leonardo num... |
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)
| #APL | APL |
∇ z←Leap year
Z←(0=4|year)∧(0=400|year)∨~0=100|year
∇
|
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #AppleScript | AppleScript | on leap_year(y)
return y mod 4 is equal to 0 and (y mod 100 is not equal to 0 or y mod 400 is equal to 0)
end leap_year
leap_year(1900) |
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... | #ALGOL_68 | ALGOL 68 |
BEGIN
PROC gcd = (INT m, n) INT :
BEGIN
INT a := ABS m, b := ABS n;
IF a=0 OR b=0 THEN 0 ELSE
WHILE b /= 0 DO INT t = b; b := a MOD b; a := t OD;
a
FI
END;
PROC lcm = (INT m, n) INT : ( m*n = 0 | 0 | ABS (m*n) % gcd (m, n));
INT m=12, n=18;
printf (($gxg(0)3(xgxg(0))l$,
"T... |
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... | #11l | 11l | F dList(n, =start)
start--
V a = Array(0 .< n)
a[start] = a[0]
a[0] = start
a.sort_range(1..)
V first = a[1]
[[Int]] r
F recurse(Int last) -> N
I (last == @first)
L(v) @a[1..]
I L.index + 1 == v
R
V b = @a.map(x -> x + 1)
@r.append(b)
... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #C.2B.2B | C++ | #include <cmath>
#include <iostream>
#include <tuple>
#include <vector>
using triple = std::tuple<int, int, int>;
void print_triple(std::ostream& out, const triple& t) {
out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')';
}
void print_vector(std::ostream& out, const std::vec... |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form/Randomizing_using_Jacobson_and_Matthews%E2%80%99_Technique | Latin Squares in reduced form/Randomizing using Jacobson and Matthews’ Technique | Section 3.3 of [Generalised 2-designs with Block Size 3(Andy L. Drizen)] describes a method of generating Latin Squares of order n attributed to Jacobson and Matthews. The purpose of this task is to produce a function which given a valid Latin Square transforms it to another using this method.
part 1
Use one of the 4 ... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
import "/seq" for Lst
var rand = Random.new()
var toReduced = Fn.new { |m|
var n = m.count
var r = List.filled(n, null)
for (i in 0...n) r[i] = m[i].toList
for (j in 0...n-1) {
if (r[0][j] != j) {
for (k in j+1...n) {
... |
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 ... | #C.23 | C# | using System;
namespace LevenshteinDistance
{
class Program
{
static int LevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
if (n == 0)
{
return m;
}
if (m == 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... | #Arturo | Arturo | source: {
The Red Death had long devastated the country.
No pestilence had ever been so fatal, or so hideous.
Blood was its Avator and its seal—the redness and the horror of blood.
There were sharp pains, and sudden dizziness,
and then profuse bleeding at the pores, with dissolution.
The scarlet stains upon the bo... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #zkl | zkl | foreach a,b,c in (["a".."c"].zip(T("A","B","C"),[1..])){ println(a,b,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... | #Nemerle | Nemerle | using System;
using System.Console;
using System.Collections.Generic;
module Program
{
PythTriples(n : int) : list[int * int * int]
{
$[ (x, y, z) | x in [1..n], y in [x..n], z in [y..n], ((x**2) + (y**2)) == (z**2) ]
}
GetPythTriples(n : int) : IEnumerable[int * int * int]
{
f... |
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... | #Nim | Nim | import sugar, math
let n = 20
let triplets = collect(newSeq):
for x in 1..n:
for y in x..n:
for z in y..n:
if x^2 + y^2 == z^2:
(x,y,z)
echo triplets |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Vlang | Vlang | fn main() {
for i in 1..6 {
for _ in 1..i+1 {
print("*")
}
print("\n")
}
} |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | leftFactorial[n] :=
{
sum = 0
for k = 0 to n-1
sum = sum + k!
return sum
}
println["Zero through ten"]
for n = 0 to 10
println["$n\t" + leftFactorial[n]]
println["\n20 through 110"]
for n = 20 to 110 step 10
println["$n\t" + leftFactorial[n]]
println["\nlength of 1000 through 10000"]
for n ... |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Frink | Frink | leftFactorial[n] :=
{
sum = 0
for k = 0 to n-1
sum = sum + k!
return sum
}
println["Zero through ten"]
for n = 0 to 10
println["$n\t" + leftFactorial[n]]
println["\n20 through 110"]
for n = 20 to 110 step 10
println["$n\t" + leftFactorial[n]]
println["\nlength of 1000 through 10000"]
for n ... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Elixir | Elixir | defmodule LCG do
def ms_seed(seed) do
Process.put(:ms_state, seed)
ms_rand
Process.put(:ms_seed, seed)
end
def ms_rand do
state = Process.get(:ms_state)
state2 = rem(214013 * state + 2531011, 2147483648)
Process.put(:ms_state, state2)
div(state, 65536)
end
def bsd_seed(seed) do... |
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
... | #Erlang | Erlang | -module(lcg).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
bsd_seed(Seed) -> put(bsd_state, Seed).
ms_seed(Seed) -> put(ms_state, Seed).
bsd_rand() ->
State = (get(bsd_state) * 1103515245 + 12345) rem 2147483648,
put(bsd_state,State),
State.
ms_rand() ->
State = (get(ms_state) * 214013 + 25... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #R | R |
leonardo_numbers <- function(add = 1, l0 = 1, l1 = 1, how_many = 25) {
result <- c(l0, l1)
for (i in 3:how_many)
result <- append(result, result[[i - 1]] + result[[i - 2]] + add)
result
}
cat("First 25 Leonardo numbers\n")
cat(leonardo_numbers(), "\n")
cat("First 25 Leonardo numbers from 0, 1 with add number ... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Racket | Racket | #lang racket
(define (Leonardo n #:L0 (L0 1) #:L1 (L1 1) #:1+ (1+ 1))
(cond [(= n 0) L0]
[(= n 1) L1]
[else
(let inr ((n (- n 2)) (L_n-2 L0) (L_n-1 L1))
(let ((L_n (+ L_n-1 L_n-2 1+)))
(if (zero? n) L_n (inr (sub1 n) L_n-1 L_n))))]))
(module+ main
(map Leonardo (ra... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Arc | Arc |
(= leap? (fn (year)
(if (and (is 0 (mod year 4)) (isnt 0 (mod year 100))) year
(unless (< 0 (+ (mod year 100) (mod year 400))) year))))
|
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Arturo | Arturo | years: [
1600 1660 1724 1788 1848 1912 1972
2032 2092 2156 2220 2280 2344 2348
1698 1699 1700 1750 1800 1810 1900
1901 1973 2100 2107 2200 2203 2289
]
print select years => leap? |
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... | #11l | 11l | F order_words(words)
DefaultDict[Char, Set[String]] byfirst
L(word) words
byfirst[word[0]].add(word)
R byfirst
F linkfirst(&byfirst; sofar)
assert(!sofar.empty)
V chmatch = sofar.last.last
V options = byfirst[chmatch] - Set(sofar)
I options.empty
R sofar
E
V alternatives = ... |
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 .
| #11l | 11l | F lpd(n)
L(i) (n - 1 .< 0).step(-1)
I n % i == 0
R i
R 1
L(i) 1..100
print(‘#3’.format(lpd(i)), end' I i % 10 == 0 {"\n"} E ‘’) |
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... | #ALGOL_W | ALGOL W | begin
integer procedure gcd ( integer value a, b ) ;
if b = 0 then a else gcd( b, a rem abs(b) );
integer procedure lcm( integer value a, b ) ;
abs( a * b ) div gcd( a, b );
write( lcm( 15, 20 ) );
end. |
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... | #APL | APL | 12^18
36 |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int 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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class LawOfCosinesTriples
{
public static void Main2() {
PrintTriples(60, 13);
PrintTriples(90, 13);
PrintTriples(120, 13);
PrintTriples(60, 10_000, true, false);
}
private ... |
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 ... | #C.2B.2B | C++ | #include <string>
#include <iostream>
using namespace std;
// Compute Levenshtein Distance
// Martin Ettl, 2012-10-05
size_t uiLevenshteinDistance(const string &s1, const string &s2)
{
const size_t
m(s1.size()),
n(s2.size());
if( m==0 ) return n;
if( n==0 ) return m;
// allocation below is not I... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #AutoHotkey | AutoHotkey | LetterFreq(Var) {
Loop, 26
{
StrReplace(Var, Chr(96+A_Index), , Count)
if Count
out .= Chr(96+A_Index) ": " Count "`n"
}
return out
}
var := "The dog jumped over the lazy fox"
var2 := "foo bar"
Msgbox, % LetterFreq(var)
Msgbox, % LetterFreq(var2) |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Zig | Zig | const std = @import("std");
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
const a2: []const u8 = &[_]u8{ 'A', 'B', 'C' };
const a3: []const u8 = &[_]u8{ '1', '2', '3' };
pub fn main() !void {
for (a1) |_, i|
try std.io.getStdOut().writer().print("{c} {c} {d}\n", .{ a1[i], a2[i], a3[i] });
} |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #OCaml | OCaml | # [? 2 * x | x <- 0 -- max_int ; x * x > 3];;
- : int Enum.t = <abstr> |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Wart | Wart | for i 1 (i <= 5) ++i
for j 0 (j < i) ++j
pr "*"
(prn) |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Print("!0 through !10: 0")
one := big.NewInt(1)
n := big.NewInt(1)
f := big.NewInt(1)
l := big.NewInt(1)
next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
for ; ; next() {
fmt.Print(" ", l)
if n.I... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #ERRE | ERRE | PROGRAM RNG
!$DOUBLE
DIM CARDS%[52]
PROCEDURE XRANDOM(SEED->XRND)
POW31=2^31
POW16=2^16
SEED=SEED*214013+2531011
SEED=SEED-POW31*INT(SEED/POW31)
XRND=INT(SEED/POW16)
END PROCEDURE
PROCEDURE YRANDOM(SEED->YRND)
POW31=2^31
SEED=SEED*1103515245+12345
SEED=SEED-POW31*INT(SEED/POW31)
YRND=... |
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
... | #F.23 | F# | module lcg =
let bsd seed =
let state = ref seed
(fun (_:unit) ->
state := (1103515245 * !state + 12345) &&& System.Int32.MaxValue
!state)
let ms seed =
let state = ref seed
(fun (_:unit) ->
state := (214013 * !state + 2531011) &&& System.Int... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Raku | Raku | sub 𝑳 ( $𝑳0 = 1, $𝑳1 = 1, $𝑳add = 1 ) { $𝑳0, $𝑳1, { $^n2 + $^n1 + $𝑳add } ... * }
# Part 1
say "The first 25 Leonardo numbers:";
put 𝑳()[^25];
# Part 2
say "\nThe first 25 numbers using 𝑳0 of 0, 𝑳1 of 1, and adder of 0:";
put 𝑳( 0, 1, 0 )[^25]; |
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)
| #AutoHotkey | AutoHotkey | leapyear(year)
{
if (Mod(year, 100) = 0)
return (Mod(year, 400) = 0)
return (Mod(year, 4) = 0)
}
MsgBox, % leapyear(1604) |
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... | #Ada | Ada | with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
procedure Lalefile is
package Word_Vec is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
use type Word_Vec.Vector, Ada.Containers.Count_Type;
type Words_Type is array (Character) of Word_Vec.Vecto... |
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 .
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
subtype param_type is Integer range 1 .. 100;
function lpd (n : in param_type) return param_type is
result : param_type := 1;
begin
for divisor in reverse 1 .. n / 2 loop
if n ... |
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... | #AppleScript | AppleScript | ------------------ LEAST COMMON MULTIPLE -----------------
-- lcm :: Integral a => a -> a -> a
on lcm(x, y)
if 0 = x or 0 = y then
0
else
abs(x div (gcd(x, y)) * y)
end if
end lcm
--------------------------- TEST -------------------------
on run
lcm(12, 18)
--> 36
end run
... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--; // use 0 basing
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
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 ... | #Factor | Factor | USING: backtrack formatting kernel locals math math.ranges
sequences sets sorting ;
IN: rosetta-code.law-of-cosines
:: triples ( quot -- seq )
[
V{ } clone :> seen
13 [1,b] dup dup [ amb-lazy ] tri@ :> ( a b c )
a sq b sq + a b quot call( x x x -- x ) c sq =
{ b a c } seen ... |
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 ... | #Fortran | Fortran | MODULE LAW_OF_COSINES
IMPLICIT NONE
CONTAINS
! Calculate the third side of a triangle using the cosine rule
REAL FUNCTION COSINE_SIDE(SIDE_A, SIDE_B, ANGLE)
INTEGER, INTENT(IN) :: SIDE_A, SIDE_B
REAL(8), INTENT(IN) :: ANGLE
COSINE_SIDE = SIDE_A**2 + SIDE_B**2 - 2*SIDE_A*SID... |
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 ... | #Clojure | Clojure | (defn levenshtein [str1 str2]
(let [len1 (count str1)
len2 (count str2)]
(cond (zero? len1) len2
(zero? len2) len1
:else
(let [cost (if (= (first str1) (first str2)) 0 1)]
(min (inc (levenshtein (rest str1) str2))
(inc (levenshtein str1 (rest str2... |
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... | #AutoIt | AutoIt |
Func _Letter_frequency($Path, $fcase = True, $fspecial_chars = True)
Local $hFile, $sRead, $iupto, $iStart, $iCount
If Not $fcase Then $fcase = False
If Not $fspecial_chars Then
$iStart = 64
If Not $fcase Then
$iupto = 26
Else
$iupto = 58
EndIf
Else
$iStart = 31
$iupto = 224
EndIf
$hFile = Fil... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET sza = 3: REM size of a
20 LET szb = 3: REM size of b
30 LET szc = 3: REM size of c
40 DIM a$(sza): DIM b$(szb): DIM c$(szc)
50 LET max = sza: REM assume a is the biggest
60 IF szb > max THEN LET max = szb: REM now try b
70 IF szc > max THEN LET max = szc: REM or c
80 REM populate our arrays, and as a bonus we al... |
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... | #Oz | Oz | functor
import
LazyList
Application
System
define
fun {Pyth N}
<<list [X Y Z] with
X <- {List.number 1 N 1}
Y <- {List.number X N 1}
Z <- {List.number Y N 1}
where X*X + Y*Y == Z*Z
>>
end
{ForAll {Pyth 20} System.show}
{Application.exit 0}
end |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Wee_Basic | Wee Basic | for y=0 to 4
print 1 ""
for x=0 to y
print 1 at x,y "*"
next
next
end |
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... | #Haskell | Haskell | leftFact :: [Integer]
leftFact = scanl (+) 0 fact
fact :: [Integer]
fact = scanl (*) 1 [1 ..]
main :: IO ()
main =
mapM_
putStrLn
[ "0 ~ 10:"
, show $ (leftFact !!) <$> [0 .. 10]
, ""
, "20 ~ 110 by tens:"
, unlines $ show . (leftFact !!) <$> [20,30 .. 110]
, ""
, "length of 1,000 ... |
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
... | #Factor | Factor | USING: fry io kernel lists lists.lazy math prettyprint ;
: lcg ( seed a c m quot: ( state -- rand ) -- list )
[ '[ _ * _ + _ mod ] lfrom-by ] [ lmap-lazy cdr ] bi* ; inline
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
[ 10 swap ltake [ . ] leach nl ]... |
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
... | #Forth | Forth | 1 31 lshift 1- constant MAX-RAND-BSD
1 15 lshift 1- constant MAX-RAND-MS
variable seed \ seed variable
: (random) seed @ * + dup seed ! ; ( -- n)
: BSDrandom MAX-RAND-BSD 12345 1103515245 (random) and ;
: MSrandom MAX-RAND-MS 2531011 214013 (random) 16 rshift and ;
: test-random
1 see... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #REXX | REXX | /*REXX pgm computes Leonardo numbers, allowing the specification of L(0), L(1), and ADD#*/
numeric digits 500 /*just in case the user gets ka-razy. */
@.=1 /*define the default for the @. array.*/
parse arg N L0 L1 a# . ... |
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)
| #AutoIt | AutoIt | ; AutoIt Version: 3.3.8.1
$Year = 2012
$sNot = " not"
If IsLeapYear($Year) Then $sNot = ""
ConsoleWrite ($Year & " is" & $sNot & " a leap year." & @LF)
Func IsLeapYear($_year)
Return Not Mod($_year, 4) And (Mod($_year, 100) Or Not Mod($_year, 400))
EndFunc
; == But it exists the standard UDF "Date.au3" with this... |
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... | #BaCon | BaCon | all$ = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon " \
"cresselia croagunk darmanitan deino emboar emolga exeggcute gabite " \
"girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan " \
"kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamosw... |
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 .
| #ALGOL_68 | ALGOL 68 | FOR n TO 100 DO # show the largest proper divisors for n = 1..100 #
INT largest proper divisor := 1;
FOR j FROM ( n OVER 2 ) BY -1 TO 2 WHILE largest proper divisor = 1 DO
IF n MOD j = 0 THEN
largest proper divisor := j
FI
OD;
print( ( whole( largest proper divisor, -3 ) ) );... |
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 .
| #ALGOL_W | ALGOL W | for n := 1 until 100 do begin % show the largest proper divisors for n = 1..100 %
for j := n div 2 step -1 until 2 do begin
if n rem j = 0 then begin
writeon( i_w := 3, s_w := 0, j );
goto foundLargestProperDivisor
end if_n_rem_j_eq_0
end for_j;
writeon( i_w := 3, s_w... |
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... | #Arendelle | Arendelle | < a , b >
( return ,
abs ( @a * @b ) /
!gcd( @a , @b )
) |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Arturo | Arturo | lcm: function [x,y][
x * y / gcd @[x y]
]
print 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... | #D | D | import std.algorithm;
import std.array;
import std.range;
import std.stdio;
alias matrix = int[][];
auto dList(int n, int start) {
start--; // use 0 basing
auto a = iota(0, n).array;
a[start] = a[0];
a[0] = start;
sort(a[1..$]);
auto first = a[1];
// recursive closure permutes a[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 ... | #FreeBASIC | FreeBASIC | ' version 03-03-2019
' compile with: fbc -s console
#Define max 13
#Define Format(_x) Right(" " + Str(_x), 4)
Dim As UInteger a, b, c, a2, b2, c2, c60 , c90, c120
Dim As String s60, s90, s120
For a = 1 To max
a2 = a * a
For b = a To max
b2 = b * b
' 60 degrees
c2 = a2 + b * b... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #CLU | CLU | min = proc [T: type] (a, b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a<b
then return(a)
else return(b)
end
end min
levenshtein = proc (s, t: string) returns (int)
ai = array[int]
aai = array[array[int]]
m: int := string$size(s)
n: int := string$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... | #AWK | AWK |
# usage: awk -f letters.awk HolyBible.txt
BEGIN { FS="" }
{ for(i=1;i<=NF;i++) m[$i]++}
END { for(i in m) printf("%9d %-14s\n", m[i],i) }
|
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #PARI.2FGP | PARI/GP | f(n)=[v|v<-vector(n^3,i,vector(3,j,i\n^(j-1)%n)),norml2(v)==2*v[3]^2] |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Wren | Wren | for (i in 1..5) {
for (j in 1..i) System.write("*")
System.print()
} |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every writes(lfact(0 | !10)," ")
write()
write()
every write(lfact(20 to 110 by 10))
write()
every writes(*lfact(1000 to 10000 by 1000)," ")
write()
end
procedure lfact(n)
r := 0
f := 1
every (i := !n, r +:= .f, f *:= .i)
return r
end |
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... | #J | J | leftFact=: +/@:!@i."0 |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Fortran | Fortran | module lcgs
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer, parameter :: a1 = 1103515245, a2 = 214013
integer, parameter :: c1 = 12345, c2 = 2531011
integer, parameter :: div = 65536
integer(i64), parameter :: m = 2147483648_i64 ! need to go to 64 bits because
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Ring | Ring |
# Project : Leanardo numbers
n0 = 1
n1 = 1
add = 1
see "First 25 Leonardo numbers:" + nl
leonardo()
n0 = 1
n1 = 1
add = 0
see "First 25 Leonardo numbers with L(0) = 0, L(1) = 1, step = 0 (fibonacci numbers):" + nl
see "" + add + " "
leonardo()
func leonardo()
see "" + n0 + " " + n1
for i=3 to 25
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Ruby | Ruby | def leonardo(l0=1, l1=1, add=1)
return to_enum(__method__,l0,l1,add) unless block_given?
loop do
yield l0
l0, l1 = l1, l0+l1+add
end
end
p leonardo.take(25)
p leonardo(0,1,0).take(25)
|
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)
| #AWK | AWK | function leapyear( year )
{
if ( year % 100 == 0 )
return ( year % 400 == 0 )
else
return ( year % 4 == 0 )
} |
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... | #BASIC256 | BASIC256 | dim names$(1)
names$ = { "audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan... |
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... | #11l | 11l | F check_dec(num)
Set[Int] st
L(c) String(num)
V d = Int(c)
I d == 0 | num % d != 0 | d C st
R 0B
st.add(d)
R 1B
L(i) (98764321 .< 0).step(-1)
I check_dec(i)
print(i)
L.break |
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 .
| #APL | APL | (⌈/1,(⍸0=¯1↓⍳|⊢))¨10 10⍴⍳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 .
| #AppleScript | AppleScript | on largestProperDivisor(n)
if (n mod 2 = 0) then return n div 2
if (n mod 3 = 0) then return n div 3
if (n < 5) then return missing value
repeat with i from 5 to (n ^ 0.5 div 1) by 6
if (n mod i = 0) then return n div i
if (n mod (i + 2) = 0) then return n div (i + 2)
end repeat
... |
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... | #Assembly | Assembly |
; lcm.asm: calculates the least common multiple
; of two positive integers
;
; nasm x86_64 assembly (linux) with libc
; assemble: nasm -felf64 lcm.asm; gcc lcm.o
; usage: ./a.out [number1] [number2]
global main
extern printf ; c function: prints formatted output
extern strtol ; c function: converts stri... |
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... | #F.23 | F# |
// Generate Latin Squares in reduced form. Nigel Galloway: July 10th., 2019
let normLS α=
let N=derange α|>List.ofSeq|>List.groupBy(fun n->n.[0])|>List.sortBy(fun(n,_)->n)|>List.map(fun(_,n)->n)|>Array.ofList
let rec fG n g=match n with h::t->fG t (g|>List.filter(fun g->Array.forall2((<>)) h g )) |_->g
let rec ... |
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 ... | #Go | Go | package main
import "fmt"
type triple struct{ a, b, c int }
var squares13 = make(map[int]int, 13)
var squares10000 = make(map[int]int, 10000)
func init() {
for i := 1; i <= 13; i++ {
squares13[i*i] = i
}
for i := 1; i <= 10000; i++ {
squares10000[i*i] = i
}
}
func solve(angle, ... |
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 ... | #COBOL | COBOL |
identification division.
program-id. Levenshtein.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
77 string-a pic x(255).
77 string-b pic... |
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... | #BaCon | BaCon | txt$ = LOAD$("bible.txt")
FOR x = 97 TO 122
PRINT CHR$(x-32), " ", CHR$(x), " : ", COUNT(txt$, x-32), " - ", COUNT(txt$, x)
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... | #Perl | Perl | sub triples ($) {
my ($n) = @_;
map { my $x = $_; map { my $y = $_; map { [$x, $y, $_] } grep { $x**2 + $y**2 == $_**2 } 1..$n } 1..$n } 1..$n;
} |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #x86_Assembly | x86 Assembly | loops: mov bx, 1 ; outer loop counter
outerloop: mov cx, bx ; inner loop counter
mov dl, 42 ; '*' character
innerloop: mov ah, 6
int 21h ; print
dec cx
jcxz innerdone
jm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.