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/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_Io;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Strings.Fixed;
procedure Cartesian is
type Element_Type is new Long_Integer;
package Lists is
new Ada.Containers.Doubly_Linked_Lists (Element_Type);
package List_Lists is
new Ada.Containers.Doubly_Linked_Lists (Lists.List, Lists."=");
subtype List is Lists.List;
subtype List_List is List_Lists.List;
function "*" (Left, Right : List) return List_List is
Result : List_List;
Sub : List;
begin
for Outer of Left loop
for Inner of Right loop
Sub.Clear;
Sub.Append (Outer);
Sub.Append (Inner);
Result.Append (Sub);
end loop;
end loop;
return Result;
end "*";
function "*" (Left : List_List;
Right : List) return List_List
is
Result : List_List;
Sub : List;
begin
for Outer of Left loop
for Inner of Right loop
Sub := Outer;
Sub.Append (Inner);
Result.Append (Sub);
end loop;
end loop;
return Result;
end "*";
procedure Put (L : List) is
use Ada.Strings;
First : Boolean := True;
begin
Put ("(");
for E of L loop
if not First then
Put (",");
end if;
Put (Fixed.Trim (E'Image, Left));
First := False;
end loop;
Put (")");
end Put;
procedure Put (LL : List_List) is
First : Boolean := True;
begin
Put ("{");
for E of LL loop
if not First then
Put (",");
end if;
Put (E);
First := False;
end loop;
Put ("}");
end Put;
function "&" (Left : List; Right : Element_Type) return List is
Result : List := Left;
begin
Result.Append (Right);
return Result;
end "&";
Nil : List renames Lists.Empty_List;
List_1_2 : constant List := Nil & 1 & 2;
List_3_4 : constant List := Nil & 3 & 4;
List_Empty : constant List := Nil;
List_1_2_3 : constant List := Nil & 1 & 2 & 3;
begin
Put (List_1_2 * List_3_4); New_Line;
Put (List_3_4 * List_1_2); New_Line;
Put (List_Empty * List_1_2); New_Line;
Put (List_1_2 * List_Empty); New_Line;
Put (List'(Nil & 1776 & 1789) * List'(Nil & 7 & 12) *
List'(Nil & 4 & 14 & 23) * List'(Nil & 0 & 1)); New_Line;
Put (List_1_2_3 * List'(Nil & 30) * List'(Nil & 500 & 100)); New_Line;
Put (List_1_2_3 * List_Empty * List'(Nil & 500 & 100)); New_Line;
end Cartesian; |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #11l | 11l | F CastOut(Base, Start, End)
V ran = (0 .< Base - 1).filter(y -> y % (@Base - 1) == (y * y) % (@Base - 1))
V (x, y) = divmod(Start, Base - 1)
[Int] r
L
L(n) ran
V k = (Base - 1) * x + n
I k < Start
L.continue
I k > End
R r
r.append(k)
x++
L(v) CastOut(Base' 16, Start' 1, End' 255)
print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 10, Start' 1, End' 99)
print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 17, Start' 1, End' 288)
print(v, end' ‘ ’)
print() |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Arturo | Arturo | ; find the sum, with seed:0 (default)
print fold [1 2 3 4] => (+)
; find the product, with seed:1
print fold [1 2 3 4] .seed:1 => (*) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #J | J | reset =: verb define
LEFT =: 'HXUCZVAMDSLKPEFJRIGTWOBNYQ'
RIGHT =: 'PTLNBQDEOYSFAVZKGJRIHWXUMC'
)
enc =: verb define
z =. LEFT {~ i =. RIGHT i. y
permute {. i
z
)
dec =: verb define
z =. RIGHT {~ i =. LEFT i. y
permute {. i
z
)
permute =: verb define
LEFT =: LEFT |.~ - y
LEFT =: (1 |. 13 {. LEFT) , 13 }. LEFT
RIGHT =: RIGHT |.~ - y + 1
RIGHT =: ({. RIGHT) , (1 |. RIGHT {~ 2+i.12) , 13 }. RIGHT
)
chao =: enc :. dec
reset ''
smoutput E =. chao 'WELLDONEISBETTERTHANWELLSAID'
reset ''
smoutput D =. chao^:_1 E |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #ERRE | ERRE |
PROGRAM CATALAN
!$DOUBLE
DIM CATALAN[50]
FUNCTION ODD(X)
ODD=FRC(X/2)<>0
END FUNCTION
PROCEDURE GETCATALAN(L)
LOCAL J,K,W
LOCAL DIM PASTRI[100]
L=L*2
PASTRI[0]=1
J=0
WHILE J<L DO
J+=1
K=INT((J+1)/2)
PASTRI[K]=PASTRI[K-1]
FOR W=K TO 1 STEP -1 DO
PASTRI[W]+=PASTRI[W-1]
END FOR
IF NOT(ODD(J)) THEN
K=INT(J/2)
CATALAN[K]=PASTRI[K]-PASTRI[K-1]
END IF
END WHILE
END PROCEDURE
BEGIN
LL=15
GETCATALAN(LL)
FOR I=1 TO LL DO
WRITE("### ####################";I;CATALAN[I])
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #F.23 | F# |
let mutable nm=uint64(1)
let mutable dm=uint64(1)
let mutable a=uint64(1)
printf "1, "
for i = 2 to 15 do
nm<-uint64(1)
dm<-uint64(1)
for k = 2 to i do
nm <-uint64( uint64(nm) * (uint64(i)+uint64(k)))
dm <-uint64( uint64(dm) * uint64(k))
let a = uint64(uint64(nm)/uint64(dm))
printf "%u"a
if(i<>15) then
printf ", "
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #D | D | import std.stdio;
void main() {
string dog = "Benjamin";
// identifiers that start with capital letters are type names
string Dog = "Samba";
string DOG = "Bernie";
writefln("There are three dogs named ",
dog, ", ", Dog, ", and ", DOG, "'");
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #dc | dc | [Benjamin]sd
[Samba]sD
[The two dogs are named ]P ldP [ and ]P lDP [.
]P |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #APL | APL | cart ← ,∘., |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #360_Assembly | 360 Assembly | * Casting out nines 08/02/2017
CASTOUT CSECT
USING CASTOUT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
L R1,LOW low
XDECO R1,XDEC edit low
MVC PGT+4(4),XDEC+8 output low
L R1,HIGH high
XDECO R1,XDEC edit high
MVC PGT+12(4),XDEC+8 output low
L R1,BASE base
XDECO R1,XDEC edit base
MVC PGT+24(4),XDEC+8 output base
XPRNT PGT,L'PGT print buffer
L R2,BASE base
BCTR R2,0 -1
ST R2,RM rm=base-1
LA R8,PG ipg=0
SR R7,R7 j=0
L R6,LOW i=low
DO WHILE=(C,R6,LE,HIGH) do i=low to high
LR R5,R6 i
SR R4,R4 clear for div
D R4,RM /rm
LR R2,R4 r2=i mod rm
LR R5,R6 i
MR R4,R6 i*i
SR R4,R4 clear for div
D R4,RM /rm
IF CR,R2,EQ,R4 THEN if (i//rm)=(i*i//rm) then
LA R7,1(R7) j=j+1
XDECO R6,XDEC edit i
MVC 0(4,R8),XDEC+8 output i
LA R8,4(R8) ipg=ipg+4
IF C,R7,EQ,=F'20' THEN if j=20 then
XPRNT PG,L'PG print buffer
LA R8,PG ipg=0
SR R7,R7 j=0
MVC PG,=CL80' ' clear buffer
ENDIF , end if
ENDIF , end if
LA R6,1(R6) i=i+1
ENDDO , end do i
IF LTR,R7,NE,R7 THEN if j<>0 then
XPRNT PG,L'PG print buffer
ENDIF , end if
L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
LOW DC F'1' low
HIGH DC F'500' high
BASE DC F'10' base
RM DS F rm
PGT DC CL80'for ... to ... base ...' buffer
PG DC CL80' ' buffer
XDEC DS CL12 temp for xdeco
YREGS
END CASTOUT |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #BASIC | BASIC | arraybase 1
global n
dim n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print " +: "; " "; cat(10, "+")
print " -: "; " "; cat(10, "-")
print " *: "; " "; cat(10, "*")
print " /: "; " "; cat(10, "/")
print " ^: "; " "; cat(10, "^")
print "max: "; " "; cat(10, "max")
print "min: "; " "; cat(10, "min")
print "avg: "; " "; cat(10, "avg")
print "cat: "; " "; cat(10, "cat")
end
function min(a, b)
if a < b then return a else return b
end function
function max(a, b)
if a > b then return a else return b
end function
function cat(cont, op$)
temp = n[1]
temp$ = ""
for i = 2 to cont
if op$ = "+" then temp += n[i]
if op$ = "-" then temp -= n[i]
if op$ = "*" then temp *= n[i]
if op$ = "/" then temp /= n[i]
if op$ = "^" then temp = temp ^ n[i]
if op$ = "max" then temp = max(temp, n[i])
if op$ = "min" then temp = min(temp, n[i])
if op$ = "avg" then temp += n[i]
if op$ = "cat" then temp$ += string(n[i])
next i
if op$ = "avg" then temp /= cont
if op$ = "cat" then temp = int(string(n[1]) + temp$)
return temp
end function |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #JavaScript | JavaScript | const L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ENCRYPT = 0;
const DECRYPT = 1;
function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function chao(text, mode, show_steps) {
var left = L_ALPHABET;
var right = R_ALPHABET;
var out = text;
var temp = "01234567890123456789012345";
var i = 0;
var index, j, store;
if (show_steps) {
console.log("The left and right alphabets after each permutation during encryption are :");
}
while (i < text.length) {
if (show_steps) {
console.log(left + " " + right);
}
if (mode == ENCRYPT) {
index = right.indexOf(text[i]);
out = setCharAt(out, i, left[index]);
} else {
index = left.indexOf(text[i]);
out = setCharAt(out, i, right[index]);
}
if (i == text.length - 1) {
break;
}
//permute left
j = index;
while (j < 26) {
temp = setCharAt(temp, j - index, left[j])
j += 1;
}
j = 0;
while (j < index) {
temp = setCharAt(temp, 26 - index + j, left[j]);
j += 1;
}
store = temp[1];
j = 2;
while (j < 14) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 13, store);
left = temp;
//permute right
j = index;
while (j < 26) {
temp = setCharAt(temp, j - index, right[j]);
j += 1;
}
j = 0;
while (j < index) {
temp = setCharAt(temp, 26 - index + j, right[j]);
j += 1;
}
store = temp[0];
j = 1;
while (j < 26) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 25, store);
store = temp[2];
j = 3;
while (j < 14) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 13, store);
right = temp;
i += 1;
}
return out;
}
function main() {
var out = document.getElementById("content");
const plain_text = "WELLDONEISBETTERTHANWELLSAID";
out.innerHTML = "<p>The original plaintext is : " + plain_text + "</p>";
var cipher_text = chao(plain_text, ENCRYPT, true);
out.innerHTML += "<p>The ciphertext is : " + cipher_text + "</p>";
var decipher_text = chao(cipher_text, DECRYPT, false);
out.innerHTML += "<p>The recovered plaintext is : " + decipher_text + "</p>";
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Factor | Factor | USING: arrays grouping io kernel math prettyprint sequences ;
IN: rosetta-code.catalan-pascal
: next-row ( seq -- seq' )
2 clump [ sum ] map 1 prefix 1 suffix ;
: pascal ( n -- seq )
1 - { { 1 } } swap [ dup last next-row suffix ] times ;
15 2 * pascal [ length odd? ] filter [
dup length 1 = [ 1 ]
[ dup midpoint@ dup 1 + 2array swap nths first2 - ] if
pprint bl
] each drop |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Delphi | Delphi | program CaseSensitiveIdentifiers;
{$APPTYPE CONSOLE}
var
dog: string;
begin
dog := 'Benjamin';
Dog := 'Samba';
DOG := 'Bernie';
Writeln('There is just one dog named ' + dog);
end. |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #DWScript | DWScript |
var dog : String;
dog := 'Benjamin';
Dog := 'Samba';
DOG := 'Bernie';
PrintLn('There is just one dog named ' + dog); |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #AppleScript | AppleScript | -- CARTESIAN PRODUCTS ---------------------------------------------------------
-- Two lists:
-- cartProd :: [a] -> [b] -> [(a, b)]
on cartProd(xs, ys)
script
on |λ|(x)
script
on |λ|(y)
[[x, y]]
end |λ|
end script
concatMap(result, ys)
end |λ|
end script
concatMap(result, xs)
end cartProd
-- N-ary – a function over a list of lists:
-- cartProdNary :: [[a]] -> [[a]]
on cartProdNary(xss)
script
on |λ|(accs, xs)
script
on |λ|(x)
script
on |λ|(a)
{x & a}
end |λ|
end script
concatMap(result, accs)
end |λ|
end script
concatMap(result, xs)
end |λ|
end script
foldr(result, {{}}, xss)
end cartProdNary
-- TESTS ----------------------------------------------------------------------
on run
set baseExamples to unlines(map(show, ¬
[cartProd({1, 2}, {3, 4}), ¬
cartProd({3, 4}, {1, 2}), ¬
cartProd({1, 2}, {}), ¬
cartProd({}, {1, 2})]))
set naryA to unlines(map(show, ¬
cartProdNary([{1776, 1789}, {7, 12}, {4, 14, 23}, {0, 1}])))
set naryB to show(cartProdNary([{1, 2, 3}, {30}, {500, 100}]))
set naryC to show(cartProdNary([{1, 2, 3}, {}, {500, 100}]))
intercalate(linefeed & linefeed, {baseExamples, naryA, naryB, naryC})
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lst to {}
set lng to length of xs
tell mReturn(f)
repeat with i from 1 to lng
set lst to (lst & |λ|(item i of xs, i, xs))
end repeat
end tell
return lst
end concatMap
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
script serialized
on |λ|(v)
show(v)
end |λ|
end script
"[" & intercalate(", ", map(serialized, e)) & "]"
else if c = record then
script showField
on |λ|(kv)
set {k, ev} to kv
"\"" & k & "\":" & show(ev)
end |λ|
end script
"{" & intercalate(", ", ¬
map(showField, zip(allKeys(e), allValues(e)))) & "}"
else if c = date then
"\"" & iso8601Z(e) & "\""
else if c = text then
"\"" & e & "\""
else if (c = integer or c = real) then
e as text
else if c = class then
"null"
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #11l | 11l | V c = 1
L(n) 1..15
print(c)
c = 2 * (2 * n - 1) * c I/ (n + 1) |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Action.21 | Action! | INT FUNC Power(INT a,b)
INT i,res
res=1
FOR i=1 TO b
DO
res==*a
OD
RETURN (res)
PROC Main()
DEFINE BASE="10"
DEFINE N="2"
INT i,max,count,total,perc
max=Power(BASE,N)
count=0 total=0
FOR i=1 TO max
DO
total==+1
IF i MOD (BASE-1)=(i*i) MOD (BASE-1) THEN
count==+1
PrintI(i) Put(32)
FI
OD
perc=100-100*count/total
PrintF("%E%ETrying %I numbers instead of %I numbers saves %I%%",count,total,perc)
RETURN |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #BBC_BASIC | BBC BASIC |
DIM a(4)
a() = 1, 2, 3, 4, 5
PRINT FNreduce(a(), "+")
PRINT FNreduce(a(), "-")
PRINT FNreduce(a(), "*")
END
DEF FNreduce(arr(), op$)
REM!Keep tmp, arr()
LOCAL I%, tmp
tmp = arr(0)
FOR I% = 1 TO DIM(arr(), 1)
tmp = EVAL("tmp " + op$ + " arr(I%)")
NEXT
= tmp
|
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Julia | Julia | const leftalphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
const rightalphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
function chacocoding(text, encoding, verbose=false)
left, right = Vector{Char}(leftalphabet), Vector{Char}(rightalphabet)
len, coded = length(text), similar(Vector{Char}(text))
for i in 1:len
verbose && println(String(left), " ", String(right))
n = indexin(text[i], encoding ? right : left)[1]
coded[i] = encoding ? left[n] : right[n]
if i < len
left .= circshift(left, -n + 1)
left[2:14] .= circshift(left[2:14], -1)
right .= circshift(right, -n)
right[3:14] .= circshift(right[3:14], -1)
end
end
String(coded)
end
function testchacocipher(txt)
println("The original plaintext is: $txt")
println("\nThe left and right alphabets for each character during encryption are:")
encoded = chacocoding(txt, true, true)
println("\nThe encoded ciphertext is: $encoded")
decoded = chacocoding(encoded, false)
println("\nDecoded, the recovered plaintext is: $decoded")
end
testchacocipher("WELLDONEISBETTERTHANWELLSAID")
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #FreeBASIC | FreeBASIC | ' version 15-09-2015
' compile with: fbc -s console
#Define size 31 ' (N * 2 + 1)
Sub pascal_triangle(rows As Integer, Pas_tri() As ULongInt)
Dim As Integer x, y
For x = 1 To rows
Pas_tri(1,x) = 1
Pas_tri(x,1) = 1
Next
For x = 2 To rows
For y = 2 To rows + 1 - x
Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)
Next
Next
End Sub
' ------=< MAIN >=------
Dim As Integer count, row
Dim As ULongInt triangle(1 To size, 1 To size)
pascal_triangle(size, triangle())
' 1 1 1 1 1 1
' 1 2 3 4 5 6
' 1 3 6 10 15 21
' 1 4 10 20 35 56
' 1 5 15 35 70 126
' 1 6 21 56 126 252
' The Pascal triangle is rotated 45 deg.
' to find the Catalan number we need to follow the diagonal
' for top left to bottom right
' take the number on diagonal and subtract the number in de cell
' one up and one to right
' 1 (2 - 1), 2 (6 - 4), 5 (20 - 15) ...
Print "The first 15 Catalan numbers are" : print
count = 1 : row = 2
Do
Print Using "###: #########"; count; triangle(row, row) - triangle(row +1, row -1)
row = row + 1
count = count + 1
Loop Until count > 15
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :dog "Benjamin"
local :Dog "Samba"
local :DOG "Bernie"
!print( "There are three dogs named " dog ", " Dog " and " DOG "." ) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #EchoLisp | EchoLisp |
(define dog "Benjamin")
(define Dog "Samba")
(define DOG "Bernie")
(printf "The three dogs are named %a, %a and %a. " dog Dog DOG)
The three dogs are named Benjamin, Samba and Bernie.
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Arturo | Arturo | loop [
[[1 2][3 4]]
[[3 4][1 2]]
[[1 2][]]
[[][1 2]]
[[1776 1789][7 12][4 14 23][0 1]]
[[1 2 3][30][500 100]]
[[1 2 3][][500 100]]
] 'lst [
print as.code product.cartesian lst
] |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #360_Assembly | 360 Assembly | CATALAN CSECT 08/09/2015
USING CATALAN,R15
LA R7,1 c=1
LA R6,1 i=1
LOOPI CH R6,=H'15' do i=1 to 15
BH ELOOPI
XDECO R6,PG edit i
LR R5,R6 i
SLA R5,1 *2
BCTR R5,0 -1
SLA R5,1 *2
MR R4,R7 *c
LA R6,1(R6) i=i+1
DR R4,R6 /i
LR R7,R5 c=2*(2*i-1)*c/(i+1)
XDECO R7,PG+12 edit c
XPRNT PG,24 print
B LOOPI next i
ELOOPI BR R14
PG DS CL24
YREGS
END CATALAN |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #ALGOL_68 | ALGOL 68 | BEGIN # casting out nines - translated from the Action! sample #
INT base = 10;
INT n = 2;
INT count := 0;
INT total := 0;
FOR i TO base ^ n DO
total +:= 1;
IF i MOD ( base - 1 ) = ( i * i ) MOD ( base - 1 ) THEN
count +:= 1;
print( ( whole( i, 0 ), " " ) )
FI
OD;
print( ( newline, newline, "Trying ", whole( count, 0 )
, " numbers instead of ", whole( total, 0 )
, " numbers saves ", fixed( 100 - ( ( 100 * count ) / total ), -6, 2 )
, "%", newline
)
)
END |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #BCPL | BCPL | get "libhdr"
let reduce(f, v, len, seed) =
len = 0 -> seed,
reduce(f, v+1, len-1, f(!v, seed))
let start() be
$( let add(x, y) = x+y
let mul(x, y) = x*y
let nums = table 1,2,3,4,5,6,7
writef("%N*N", reduce(add, nums, 7, 0))
writef("%N*N", reduce(mul, nums, 7, 1))
$) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Kotlin | Kotlin | // Version 1.2.40
enum class Mode { ENCRYPT, DECRYPT }
object Chao {
private val lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
private val rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
fun exec(text: String, mode: Mode, showSteps: Boolean = false): String {
var left = lAlphabet
var right = rAlphabet
val eText = CharArray(text.length)
val temp = CharArray(26)
for (i in 0 until text.length) {
if (showSteps) println("$left $right")
var index: Int
if (mode == Mode.ENCRYPT) {
index = right.indexOf(text[i])
eText[i] = left[index]
}
else {
index = left.indexOf(text[i])
eText[i] = right[index]
}
if (i == text.length - 1) break
// permute left
for (j in index..25) temp[j - index] = left[j]
for (j in 0 until index) temp[26 - index + j] = left[j]
var store = temp[1]
for (j in 2..13) temp[j - 1] = temp[j]
temp[13] = store
left = String(temp)
// permute right
for (j in index..25) temp[j - index] = right[j]
for (j in 0 until index) temp[26 - index + j] = right[j]
store = temp[0]
for (j in 1..25) temp[j - 1] = temp[j]
temp[25] = store
store = temp[2]
for (j in 3..13) temp[j - 1] = temp[j]
temp[13] = store
right = String(temp)
}
return String(eText)
}
}
fun main(args: Array<String>) {
val plainText = "WELLDONEISBETTERTHANWELLSAID"
println("The original plaintext is : $plainText")
println("\nThe left and right alphabets after each permutation" +
" during encryption are :\n")
val cipherText = Chao.exec(plainText, Mode.ENCRYPT, true)
println("\nThe ciphertext is : $cipherText")
val plainText2 = Chao.exec(cipherText, Mode.DECRYPT)
println("\nThe recovered plaintext is : $plainText2")
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Go | Go | package main
import "fmt"
func main() {
const n = 15
t := [n + 2]uint64{0, 1}
for i := 1; i <= n; i++ {
for j := i; j > 1; j-- {
t[j] += t[j-1]
}
t[i+1] = t[i]
for j := i + 1; j > 1; j-- {
t[j] += t[j-1]
}
fmt.Printf("%2d : %d\n", i, t[i+1]-t[i])
}
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Elena | Elena | import extensions;
public program()
{
var dog := "Benjamin";
var Dog := "Samba";
var DOG := "Bernie";
console.printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG)
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Elixir | Elixir | dog = "Benjamin"
doG = "Samba"
dOG = "Bernie"
IO.puts "The three dogs are named #{dog}, #{doG} and #{dOG}." |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Bracmat | Bracmat | ( ( mul
= R a b A B
. :?R
& !arg:(.?A) (.?B)
& ( !A
: ?
( %@?a
& !B
: ?
( (%@?b|(.?b))
& !R (.!a !b):?R
& ~
)
?
)
?
| (.!R)
)
)
& ( cartprod
= a
. !arg:%?a %?arg&mul$(!a cartprod$!arg)
| !arg
)
& out
$ ( cartprod
$ ( (.1776 1789)
(.7 12)
(.4 14 23)
(.0 1)
)
)
& out$(cartprod$((.1 2 3) (.30) (.500 100)))
& out$(cartprod$((.1 2 3) (.) (.500 100)))
) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #ABAP | ABAP |
report z_catalan_numbers.
class catalan_numbers definition.
public section.
class-methods:
get_nth_number
importing
i_n type int4
returning
value(r_catalan_number) type int4.
endclass.
class catalan_numbers implementation.
method get_nth_number.
r_catalan_number = cond int4(
when i_n eq 0
then 1
else reduce int4(
init
result = 1
index = 1
for position = 1 while position <= i_n
next
result = result * 2 * ( 2 * index - 1 ) div ( index + 1 )
index = index + 1 ) ).
endmethod.
endclass.
start-of-selection.
do 15 times.
write / |C({ sy-index - 1 }) = { catalan_numbers=>get_nth_number( sy-index - 1 ) }|.
enddo.
|
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Arturo | Arturo | N: 2
base: 10
c1: 0
c2: 0
loop 1..(base^N)-1 'k [
c1: c1 + 1
if (k%base-1)= (k*k)%base-1 [
c2: c2 + 1
prints ~"|k| "
]
]
print ""
print ["Trying" c2 "numbers instead of" c1 "numbers saves" 100.0 - 100.0*c2//c1 "%"] |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #BQN | BQN | •Show +´ 30‿1‿20‿2‿10
•Show +˝ 30‿1‿20‿2‿10
•Show tab ← (2+↕5) |⌜ 9+↕3
•Show +˝ tab |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Lua | Lua | -- Chaocipher, in Lua, 6/19/2020 db
local Chaocipher = {
ct = "HXUCZVAMDSLKPEFJRIGTWOBNYQ",
pt = "PTLNBQDEOYSFAVZKGJRIHWXUMC",
encrypt = function(self, text) return self:_encdec(text, true) end,
decrypt = function(self, text) return self:_encdec(text, false) end,
_encdec = function(self, text, encflag)
local ct, pt, s = self.ct, self.pt, ""
local cshl = function(s,i) return s:sub(i) .. s:sub(1,i-1) end
local sshl = function(s,i) return s:sub(1,i-1) .. s:sub(i+1,14) .. s:sub(i,i) .. s:sub(15) end
for ch in text:gmatch(".") do
local i = (encflag and pt or ct):find(ch)
s = s .. (encflag and ct or pt):sub(i,i)
if encflag then print(ct, pt, ct:sub(i,i), pt:sub(i,i)) end
ct, pt = sshl(cshl(ct, i), 2), sshl(cshl(pt, i+1), 3)
end
return s
end,
}
local plainText = "WELLDONEISBETTERTHANWELLSAID"
local encryptText = Chaocipher:encrypt(plainText)
local decryptText = Chaocipher:decrypt(encryptText)
print()
print("The original text was: " .. plainText)
print("The encrypted text is: " .. encryptText)
print("The decrypted text is: " .. decryptText) |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Groovy | Groovy |
class Catalan
{
public static void main(String[] args)
{
BigInteger N = 15;
BigInteger k,n,num,den;
BigInteger catalan;
print(1);
for(n=2;n<=N;n++)
{
num = 1;
den = 1;
for(k=2;k<=n;k++)
{
num = num*(n+k);
den = den*k;
catalan = num/den;
}
print(" " + catalan);
}
}
}
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Erlang | Erlang |
-module( case_sensitivity_of_identifiers ).
-export( [task/0] ).
task() ->
catch dog = "Benjamin", % Function will crash without catch
Dog = "Samba",
DOG = "Bernie",
io:fwrite( "The three dogs are named ~s, ~s and ~s~n", [dog, Dog, DOG] ).
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Euphoria | Euphoria | -- These variables are all different
sequence dog = "Benjamin"
sequence Dog = "Samba"
sequence DOG = "Bernie"
printf( 1, "The three dogs are named %s, %s and %s\n", {dog, Dog, DOG} ) |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #C | C |
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Ki
PROC Main()
REAL c,rnom,rden
BYTE n,nom,den
Put(125) PutE() ;clear the screen
IntToReal(1,c)
FOR n=1 TO 15
DO
nom=(n LSH 1-1) LSH 1
den=n+1
IntToReal(nom,rnom)
IntToReal(den,rden)
RealMult(c,rnom,c)
RealDiv(c,rden,c)
PrintF("C(%B)=",n) PrintRE(c)
OD
RETURN |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #AWK | AWK |
# syntax: GAWK -f CASTING_OUT_NINES.AWK
# converted from C
BEGIN {
base = 10
for (k=1; k<=base^2; k++) {
c1++
if (k % (base-1) == (k*k) % (base-1)) {
c2++
printf("%d ",k)
}
}
printf("\nTrying %d numbers instead of %d numbers saves %.2f%%\n",c2,c1,100-(100*c2/c1))
exit(0)
}
|
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #C | C | vertex face_point(face f)
{
int i;
vertex v;
if (!f->avg) {
f->avg = vertex_new();
foreach(i, v, f->v)
if (!i) f->avg->pos = v->pos;
else vadd(f->avg->pos, v->pos);
vdiv(f->avg->pos, len(f->v));
}
return f->avg;
}
#define hole_edge(e) (len(e->f)==1)
vertex edge_point(edge e)
{
int i;
face f;
if (!e->e_pt) {
e->e_pt = vertex_new();
e->avg = e->v[0]->pos;
vadd(e->avg, e->v[1]->pos);
e->e_pt->pos = e->avg;
if (!hole_edge(e)) {
foreach (i, f, e->f)
vadd(e->e_pt->pos, face_point(f)->pos);
vdiv(e->e_pt->pos, 4);
} else
vdiv(e->e_pt->pos, 2);
vdiv(e->avg, 2);
}
return e->e_pt;
}
#define hole_vertex(v) (len((v)->f) != len((v)->e))
vertex updated_point(vertex v)
{
int i, n = 0;
edge e;
face f;
coord_t sum = {0, 0, 0};
if (v->v_new) return v->v_new;
v->v_new = vertex_new();
if (hole_vertex(v)) {
v->v_new->pos = v->pos;
foreach(i, e, v->e) {
if (!hole_edge(e)) continue;
vadd(v->v_new->pos, edge_point(e)->pos);
n++;
}
vdiv(v->v_new->pos, n + 1);
} else {
n = len(v->f);
foreach(i, f, v->f)
vadd(sum, face_point(f)->pos);
foreach(i, e, v->e)
vmadd(sum, edge_point(e)->pos, 2, sum);
vdiv(sum, n);
vmadd(sum, v->pos, n - 3, sum);
vdiv(sum, n);
v->v_new->pos = sum;
}
return v->v_new;
}
model catmull(model m)
{
int i, j, a, b, c, d;
face f;
vertex v, x;
model nm = model_new();
foreach (i, f, m->f) {
foreach(j, v, f->v) {
_get_idx(a, updated_point(v));
_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));
_get_idx(c, face_point(f));
_get_idx(d, edge_point(elem(f->e, j)));
model_add_face(nm, 4, a, b, c, d);
}
}
return nm;
} |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #11l | 11l | F mod_(n, m)
R ((n % m) + m) % m
F is_prime(n)
I n C (2, 3)
R 1B
E I n < 2 | n % 2 == 0 | n % 3 == 0
R 0B
V div = 5
V inc = 2
L div ^ 2 <= n
I n % div == 0
R 0B
div += inc
inc = 6 - inc
R 1B
L(p) 2 .< 62
I !is_prime(p)
L.continue
L(h3) 2 .< p
V g = h3 + p
L(d) 1 .< g
I (g * (p - 1)) % d != 0 | mod_(-p * p, h3) != d % h3
L.continue;
V q = 1 + (p - 1) * g I/ d;
I !is_prime(q)
L.continue
V r = 1 + (p * q I/ h3)
I !is_prime(r) | (q * r) % (p - 1) != 1
L.continue
print(p‘ x ’q‘ x ’r) |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Bracmat | Bracmat | ( ( fold
= f xs init first rest
. !arg:(?f.?xs.?init)
& ( !xs:&!init
| !xs:%?first ?rest
& !f$(!first.fold$(!f.!rest.!init))
)
)
& out
$ ( fold
$ ( (=a b.!arg:(?a.?b)&!a+!b)
. 1 2 3 4 5
. 0
)
)
& (product=a b.!arg:(?a.?b)&!a*!b)
& out$(fold$(product.1 2 3 4 5.1))
); |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ichaoalphabet, iMoveToFront, ChaoCipher]
ichaoalphabet = CharacterRange["A", "Z"];
iMoveToFront[l_List, sel_] := Module[{p},
p = FirstPosition[l, sel];
RotateLeft[l, p - 1]
]
ChaoCipher::wrongcipheralpha =
"The cipher alphabet `1` is not a permutation of \
\"A\"\[LongDash]\"Z\".";
ChaoCipher::wrongplainalpha =
"The plain alphabet `1` is not a permutation of \"A\"\[LongDash]\"Z\
\".";
ChaoCipher[str_String, {plainalpha_List, cipheralpha_List}] :=
Module[{pa, ca, plain, new, papermute, capermute, out},
ca = ToUpperCase[cipheralpha];
pa = ToUpperCase[plainalpha];
If[Sort[ca] =!= Sort[ichaoalphabet],
Message[ChaoCipher::wrongcipheralpha, ca];
$Failed
,
If[Sort[pa] =!= Sort[ichaoalphabet],
Message[ChaoCipher::wrongplainalpha, pa];
$Failed
,
capermute = SubsetMap[RotateLeft, Range[26], Range[2, 14]];
papermute =
SubsetMap[RotateLeft, RotateLeft[Range[26], 1], Range[3, 14]];
plain =
Select[Characters[ToUpperCase[str]], MemberQ[ichaoalphabet, #] &];
out = Table[
new = Association[Thread[pa -> ca]][p];
pa = iMoveToFront[pa, p];
ca = iMoveToFront[ca, new];
pa = pa[[papermute]];
ca = ca[[capermute]];
new
,
{p, plain}
];
StringJoin[out]
]
]
]
ChaoCipher["WELLDONEISBETTERTHANWELLSAID",{Characters@"PTLNBQDEOYSFAVZKGJRIHWXUMC",Characters@"HXUCZVAMDSLKPEFJRIGTWOBNYQ"}]
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Haskell | Haskell | import System.Environment (getArgs)
-- Pascal's triangle.
pascal :: [[Integer]]
pascal = [1] : map (\row -> 1 : zipWith (+) row (tail row) ++ [1]) pascal
-- The Catalan numbers from Pascal's triangle. This uses a method from
-- http://www.cut-the-knot.org/arithmetic/algebra/CatalanInPascal.shtml
-- (see "Grimaldi").
catalan :: [Integer]
catalan = map (diff . uncurry drop) $ zip [0..] (alt pascal)
where alt (x:_:zs) = x : alt zs -- every other element of an infinite list
diff (x:y:_) = x - y
diff (x:_) = x
main :: IO ()
main = do
ns <- fmap (map read) getArgs :: IO [Int]
mapM_ (print . flip take catalan) ns |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #F.23 | F# | let dog = "Benjamin"
let Dog = "Samba"
let DOG = "Bernie"
printfn "There are three dogs named %s, %s and %s" dog Dog DOG |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Factor | Factor | USING: formatting locals ;
IN: scratchpad
[let
"Benjamin" :> dog
"Samba" :> Dog
"Bernie" :> DOG
{ dog Dog DOG } "There are three dogs named %s, %s, and %s." vprintf
] |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #C.23 | C# | using System;
public class Program
{
public static void Main()
{
int[] empty = new int[0];
int[] list1 = { 1, 2 };
int[] list2 = { 3, 4 };
int[] list3 = { 1776, 1789 };
int[] list4 = { 7, 12 };
int[] list5 = { 4, 14, 23 };
int[] list6 = { 0, 1 };
int[] list7 = { 1, 2, 3 };
int[] list8 = { 30 };
int[] list9 = { 500, 100 };
foreach (var sequenceList in new [] {
new [] { list1, list2 },
new [] { list2, list1 },
new [] { list1, empty },
new [] { empty, list1 },
new [] { list3, list4, list5, list6 },
new [] { list7, list8, list9 },
new [] { list7, empty, list9 }
}) {
var cart = sequenceList.CartesianProduct()
.Select(tuple => $"({string.Join(", ", tuple)})");
Console.WriteLine($"{{{string.Join(", ", cart)}}}");
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
} |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Catalan is
function Catalan (N : Natural) return Natural is
Result : Positive := 1;
begin
for I in 1..N loop
Result := Result * 2 * (2 * I - 1) / (I + 1);
end loop;
return Result;
end Catalan;
begin
for N in 0..15 loop
Put_Line (Integer'Image (N) & " =" & Integer'Image (Catalan (N)));
end loop;
end Test_Catalan; |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #C | C | #include <stdio.h>
#include <math.h>
int main() {
const int N = 2;
int base = 10;
int c1 = 0;
int c2 = 0;
int k;
for (k = 1; k < pow(base, N); k++) {
c1++;
if (k % (base - 1) == (k * k) % (base - 1)) {
c2++;
printf("%d ", k);
}
}
printf("\nTring %d numbers instead of %d numbers saves %f%%\n", c2, c1, 100.0 - 100.0 * c2 / c1);
return 0;
} |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Go | Go | package main
import (
"fmt"
"sort"
)
type (
Point [3]float64
Face []int
Edge struct {
pn1 int // point number 1
pn2 int // point number 2
fn1 int // face number 1
fn2 int // face number 2
cp Point // center point
}
PointEx struct {
p Point
n int
}
)
func sumPoint(p1, p2 Point) Point {
sp := Point{}
for i := 0; i < 3; i++ {
sp[i] = p1[i] + p2[i]
}
return sp
}
func mulPoint(p Point, m float64) Point {
mp := Point{}
for i := 0; i < 3; i++ {
mp[i] = p[i] * m
}
return mp
}
func divPoint(p Point, d float64) Point {
return mulPoint(p, 1.0/d)
}
func centerPoint(p1, p2 Point) Point {
return divPoint(sumPoint(p1, p2), 2)
}
func getFacePoints(inputPoints []Point, inputFaces []Face) []Point {
facePoints := make([]Point, len(inputFaces))
for i, currFace := range inputFaces {
facePoint := Point{}
for _, cpi := range currFace {
currPoint := inputPoints[cpi]
facePoint = sumPoint(facePoint, currPoint)
}
facePoint = divPoint(facePoint, float64(len(currFace)))
facePoints[i] = facePoint
}
return facePoints
}
func getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {
var edges [][3]int
for faceNum, face := range inputFaces {
numPoints := len(face)
for pointIndex := 0; pointIndex < numPoints; pointIndex++ {
pointNum1 := face[pointIndex]
var pointNum2 int
if pointIndex < numPoints-1 {
pointNum2 = face[pointIndex+1]
} else {
pointNum2 = face[0]
}
if pointNum1 > pointNum2 {
pointNum1, pointNum2 = pointNum2, pointNum1
}
edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})
}
}
sort.Slice(edges, func(i, j int) bool {
if edges[i][0] == edges[j][0] {
if edges[i][1] == edges[j][1] {
return edges[i][2] < edges[j][2]
}
return edges[i][1] < edges[j][1]
}
return edges[i][0] < edges[j][0]
})
numEdges := len(edges)
eIndex := 0
var mergedEdges [][4]int
for eIndex < numEdges {
e1 := edges[eIndex]
if eIndex < numEdges-1 {
e2 := edges[eIndex+1]
if e1[0] == e2[0] && e1[1] == e2[1] {
mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})
eIndex += 2
} else {
mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})
eIndex++
}
} else {
mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})
eIndex++
}
}
var edgesCenters []Edge
for _, me := range mergedEdges {
p1 := inputPoints[me[0]]
p2 := inputPoints[me[1]]
cp := centerPoint(p1, p2)
edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})
}
return edgesCenters
}
func getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {
edgePoints := make([]Point, len(edgesFaces))
for i, edge := range edgesFaces {
cp := edge.cp
fp1 := facePoints[edge.fn1]
var fp2 Point
if edge.fn2 == -1 {
fp2 = fp1
} else {
fp2 = facePoints[edge.fn2]
}
cfp := centerPoint(fp1, fp2)
edgePoints[i] = centerPoint(cp, cfp)
}
return edgePoints
}
func getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {
numPoints := len(inputPoints)
tempPoints := make([]PointEx, numPoints)
for faceNum := range inputFaces {
fp := facePoints[faceNum]
for _, pointNum := range inputFaces[faceNum] {
tp := tempPoints[pointNum].p
tempPoints[pointNum].p = sumPoint(tp, fp)
tempPoints[pointNum].n++
}
}
avgFacePoints := make([]Point, numPoints)
for i, tp := range tempPoints {
avgFacePoints[i] = divPoint(tp.p, float64(tp.n))
}
return avgFacePoints
}
func getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {
numPoints := len(inputPoints)
tempPoints := make([]PointEx, numPoints)
for _, edge := range edgesFaces {
cp := edge.cp
for _, pointNum := range []int{edge.pn1, edge.pn2} {
tp := tempPoints[pointNum].p
tempPoints[pointNum].p = sumPoint(tp, cp)
tempPoints[pointNum].n++
}
}
avgMidEdges := make([]Point, len(tempPoints))
for i, tp := range tempPoints {
avgMidEdges[i] = divPoint(tp.p, float64(tp.n))
}
return avgMidEdges
}
func getPointsFaces(inputPoints []Point, inputFaces []Face) []int {
numPoints := len(inputPoints)
pointsFaces := make([]int, numPoints)
for faceNum := range inputFaces {
for _, pointNum := range inputFaces[faceNum] {
pointsFaces[pointNum]++
}
}
return pointsFaces
}
func getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {
newPoints := make([]Point, len(inputPoints))
for pointNum := range inputPoints {
n := float64(pointsFaces[pointNum])
m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n
oldCoords := inputPoints[pointNum]
p1 := mulPoint(oldCoords, m1)
afp := avgFacePoints[pointNum]
p2 := mulPoint(afp, m2)
ame := avgMidEdges[pointNum]
p3 := mulPoint(ame, m3)
p4 := sumPoint(p1, p2)
newPoints[pointNum] = sumPoint(p4, p3)
}
return newPoints
}
func switchNums(pointNums [2]int) [2]int {
if pointNums[0] < pointNums[1] {
return pointNums
}
return [2]int{pointNums[1], pointNums[0]}
}
func cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {
facePoints := getFacePoints(inputPoints, inputFaces)
edgesFaces := getEdgesFaces(inputPoints, inputFaces)
edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)
avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)
avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)
pointsFaces := getPointsFaces(inputPoints, inputFaces)
newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)
var facePointNums []int
nextPointNum := len(newPoints)
for _, facePoint := range facePoints {
newPoints = append(newPoints, facePoint)
facePointNums = append(facePointNums, nextPointNum)
nextPointNum++
}
edgePointNums := make(map[[2]int]int)
for edgeNum := range edgesFaces {
pointNum1 := edgesFaces[edgeNum].pn1
pointNum2 := edgesFaces[edgeNum].pn2
edgePoint := edgePoints[edgeNum]
newPoints = append(newPoints, edgePoint)
edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum
nextPointNum++
}
var newFaces []Face
for oldFaceNum, oldFace := range inputFaces {
if len(oldFace) == 4 {
a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]
facePointAbcd := facePointNums[oldFaceNum]
edgePointAb := edgePointNums[switchNums([2]int{a, b})]
edgePointDa := edgePointNums[switchNums([2]int{d, a})]
edgePointBc := edgePointNums[switchNums([2]int{b, c})]
edgePointCd := edgePointNums[switchNums([2]int{c, d})]
newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})
newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})
newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})
newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})
}
}
return newPoints, newFaces
}
func main() {
inputPoints := []Point{
{-1.0, 1.0, 1.0},
{-1.0, -1.0, 1.0},
{1.0, -1.0, 1.0},
{1.0, 1.0, 1.0},
{1.0, -1.0, -1.0},
{1.0, 1.0, -1.0},
{-1.0, -1.0, -1.0},
{-1.0, 1.0, -1.0},
}
inputFaces := []Face{
{0, 1, 2, 3},
{3, 2, 4, 5},
{5, 4, 6, 7},
{7, 0, 3, 5},
{7, 6, 1, 0},
{6, 1, 2, 4},
}
outputPoints := make([]Point, len(inputPoints))
outputFaces := make([]Face, len(inputFaces))
copy(outputPoints, inputPoints)
copy(outputFaces, inputFaces)
iterations := 1
for i := 0; i < iterations; i++ {
outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)
}
for _, p := range outputPoints {
fmt.Printf("% .4f\n", p)
}
fmt.Println()
for _, f := range outputFaces {
fmt.Printf("%2d\n", f)
}
} |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #Ada | Ada | with Ada.Text_IO, Miller_Rabin;
procedure Nemesis is
type Number is range 0 .. 2**40-1; -- sufficiently large for the task
function Is_Prime(N: Number) return Boolean is
package MR is new Miller_Rabin(Number); use MR;
begin
return MR.Is_Prime(N) = Probably_Prime;
end Is_Prime;
begin
for P1 in Number(2) .. 61 loop
if Is_Prime(P1) then
for H3 in Number(1) .. P1 loop
declare
G: Number := H3 + P1;
P2, P3: Number;
begin
Inner:
for D in 1 .. G-1 loop
if ((H3+P1) * (P1-1)) mod D = 0 and then
(-(P1 * P1)) mod H3 = D mod H3
then
P2 := 1 + ((P1-1) * G / D);
P3 := 1 +(P1*P2/H3);
if Is_Prime(P2) and then Is_Prime(P3)
and then (P2*P3) mod (P1-1) = 1
then
Ada.Text_IO.Put_Line
( Number'Image(P1) & " *" & Number'Image(P2) & " *" &
Number'Image(P3) & " = " & Number'Image(P1*P2*P3) );
end if;
end if;
end loop Inner;
end;
end loop;
end if;
end loop;
end Nemesis; |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #C | C | #include <stdio.h>
typedef int (*intFn)(int, int);
int reduce(intFn fn, int size, int *elms)
{
int i, val = *elms;
for (i = 1; i < size; ++i)
val = fn(val, elms[i]);
return val;
}
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int main(void)
{
int nums[] = {1, 2, 3, 4, 5};
printf("%d\n", reduce(add, 5, nums));
printf("%d\n", reduce(sub, 5, nums));
printf("%d\n", reduce(mul, 5, nums));
return 0;
} |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Nim | Nim | import strformat
type
Mode = enum
Encrypt
Decrypt
const lAlphabet: string = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
const rAlphabet: string = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
proc chao(text: string, mode: Mode, verbose: bool = false): string =
var left = lAlphabet
var right = rAlphabet
var eText = newSeq[char](text.len)
var temp: array[26, char]
for i in 0..<text.len:
if verbose:
echo &"{left} {right}"
var index: int
if mode == Encrypt:
index = right.find(text[i])
eText[i] = left[index]
else:
index = left.find(text[i])
eText[i] = right[index]
if (i == text.len - 1):
break
# permute left
for j in index..25:
temp[j - index] = left[j]
for j in 0..<index:
temp[26 - index + j] = left[j]
var store = temp[1]
for j in 2..13:
temp[j - 1] = temp[j]
temp[13] = store
left = ""
for i in temp:
left &= $i
# permute right
for j in index..25:
temp[j - index] = right[j]
for j in 0..<index:
temp[26 - index + j] = right[j]
store = temp[0]
for j in 1..25:
temp[j - 1] = temp[j]
temp[25] = store
store = temp[2]
for j in 3..13:
temp[j - 1] = temp[j]
temp[13] = store
right = ""
for i in temp:
right &= $i
for i in eText:
result &= $i
var plainText = "WELLDONEISBETTERTHANWELLSAID"
echo &"The original plaintext is: {plainText}"
echo "\nThe left and right alphabets after each permutation during encryption are:\n"
var cipherText = chao(plainText, Encrypt, true)
echo &"\nThe ciphertext is: {cipherText}"
var plainText2 = chao(cipherText, Decrypt, false)
echo &"\nThe recovered plaintext is: {plainText2}" |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Icon_and_Unicon | Icon and Unicon | link math
procedure main(A)
limit := (integer(A[1])|15)+1
every write(right(binocoef(i := 2*seq(0)\limit,i/2)-binocoef(i,i/2+1),30))
end |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Forth | Forth | : DOG ." Benjamin" ;
: Dog ." Samba" ;
: dog ." Bernie" ;
: HOWMANYDOGS ." There is just one dog named " DOG ;
HOWMANYDOGS |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Fortran | Fortran | program Example
implicit none
character(8) :: dog, Dog, DOG
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
if (dog == DOG) then
write(*,*) "There is just one dog named ", dog
else
write(*,*) "The three dogs are named ", dog, Dog, " and ", DOG
end if
end program Example |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #C.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
} |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #ALGOL_68 | ALGOL 68 | # calculate the first few catalan numbers, using LONG INT values #
# (64-bit quantities in Algol 68G which can handle up to C23) #
# returns n!/k! #
PROC factorial over factorial = ( INT n, k )LONG INT:
IF k > n THEN 0
ELIF k = n THEN 1
ELSE # k < n #
LONG INT f := 1;
FOR i FROM k + 1 TO n DO f *:= i OD;
f
FI # factorial over factorial # ;
# returns n! #
PROC factorial = ( INT n )LONG INT:
BEGIN
LONG INT f := 1;
FOR i FROM 2 TO n DO f *:= i OD;
f
END # factorial # ;
# returnss the nth Catalan number using binomial coefficeients #
# uses the factorial over factorial procedure for a slight optimisation #
# note: Cn = 1/(n+1)(2n n) #
# = (2n)!/((n+1)!n!) #
# = factorial over factorial( 2n, n+1 )/n! #
PROC catalan = ( INT n )LONG INT: IF n < 2 THEN 1 ELSE factorial over factorial( n + n, n + 1 ) OVER factorial( n ) FI;
# show the first few catalan numbers #
FOR i FROM 0 TO 15 DO
print( ( whole( i, -2 ), ": ", whole( catalan( i ), 0 ), newline ) )
OD |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #11l | 11l | F cidr_parse(str)
V (addr_str, m_str) = str.split(‘/’)
V (a, b, c, d) = addr_str.split(‘.’).map(Int)
V m = Int(m_str)
I m < 1 | m > 32
| a < 0 | a > 255
| b < 0 | b > 255
| c < 0 | c > 255
| d < 0 | d > 255
R (0, 0)
V mask = (-)((1 << (32 - m)) - 1)
V address = (a << 24) + (b << 16) + (c << 8) + d
address [&]= mask
R (address, m)
F cidr_format(=address, mask_length)
V d = address [&] F'F
address >>= 8
V c = address [&] F'F
address >>= 8
V b = address [&] F'F
address >>= 8
V a = address [&] F'F
R a‘.’b‘.’c‘.’d‘/’mask_length
L(test) [‘87.70.141.1/22’,
‘36.18.154.103/12’,
‘62.62.197.11/29’,
‘67.137.119.181/4’,
‘161.214.74.21/24’,
‘184.232.176.184/18’]
V (address, mask_length) = cidr_parse(test)
print(‘#<18 -> #.’.format(test, cidr_format(address, mask_length))) |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #C.2B.2B | C++ | // Casting Out Nines
//
// Nigel Galloway. June 24th., 2012
//
#include <iostream>
int main() {
int Base = 10;
const int N = 2;
int c1 = 0;
int c2 = 0;
for (int k=1; k<pow((double)Base,N); k++){
c1++;
if (k%(Base-1) == (k*k)%(Base-1)){
c2++;
std::cout << k << " ";
}
}
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl;
return 0;
} |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Haskell | Haskell | {-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Array
import Data.Foldable (length, concat, sum)
import Data.List (genericLength)
import Data.Maybe (mapMaybe)
import Prelude hiding (length, concat, sum)
import qualified Data.Map.Strict as Map
{-
A SimpleMesh consists of only vertices and faces that refer to them.
A Mesh extends the SimpleMesh to contain edges as well as references to
adjoining mesh components for each other component, such as a vertex
also contains what faces it belongs to.
An isolated edge can be represented as a degenerate face with 2 vertices.
Faces with 0 or 1 vertices can be thrown out, as they do not contribute to
the result (they can also propagate NaNs).
-}
newtype VertexId = VertexId { getVertexId :: Int } deriving (Ix, Ord, Eq, Show)
newtype EdgeId = EdgeId { getEdgeId :: Int } deriving (Ix, Ord, Eq, Show)
newtype FaceId = FaceId { getFaceId :: Int } deriving (Ix, Ord, Eq, Show)
data Vertex a = Vertex
{ vertexPoint :: a
, vertexEdges :: [EdgeId]
, vertexFaces :: [FaceId]
} deriving Show
data Edge = Edge
{ edgeVertexA :: VertexId
, edgeVertexB :: VertexId
, edgeFaces :: [FaceId]
} deriving Show
data Face = Face
{ faceVertices :: [VertexId]
, faceEdges :: [EdgeId]
} deriving Show
type VertexArray a = Array VertexId (Vertex a)
type EdgeArray = Array EdgeId Edge
type FaceArray = Array FaceId Face
data Mesh a = Mesh
{ meshVertices :: VertexArray a
, meshEdges :: EdgeArray
, meshFaces :: FaceArray
} deriving Show
data SimpleVertex a = SimpleVertex { sVertexPoint :: a } deriving Show
data SimpleFace = SimpleFace { sFaceVertices :: [VertexId] } deriving Show
type SimpleVertexArray a = Array VertexId (SimpleVertex a)
type SimpleFaceArray = Array FaceId SimpleFace
data SimpleMesh a = SimpleMesh
{ sMeshVertices :: SimpleVertexArray a
, sMeshFaces :: SimpleFaceArray
} deriving Show
-- Generic helpers.
fmap1 :: Functor f => (t -> a -> b) -> (t -> f a) -> t -> f b
fmap1 g h x = fmap (g x) (h x)
aZipWith :: Ix i1 => (a -> b -> e) -> Array i1 a -> Array i b -> Array i1 e
aZipWith f a b = listArray (bounds a) $ zipWith f (elems a) (elems b)
average :: (Foldable f, Fractional a) => f a -> a
average xs = (sum xs) / (fromIntegral $ length xs)
-- Intermediary point types for ultimately converting into a point `a`.
newtype FacePoint a = FacePoint { getFacePoint :: a } deriving Show
newtype EdgeCenterPoint a = EdgeCenterPoint { getEdgeCenterPoint :: a } deriving Show
newtype EdgePoint a = EdgePoint { getEdgePoint :: a } deriving Show
newtype VertexPoint a = VertexPoint { getVertexPoint :: a } deriving Show
type FacePointArray a = Array FaceId (FacePoint a)
type EdgePointArray a = Array EdgeId (EdgePoint a)
type EdgeCenterPointArray a = Array EdgeId (EdgeCenterPoint a)
type IsEdgeHoleArray = Array EdgeId Bool
type VertexPointArray a = Array VertexId (VertexPoint a)
-- Subdivision helpers.
facePoint :: Fractional a => Mesh a -> Face -> FacePoint a
facePoint mesh = FacePoint . average . (fmap $ vertexPointById mesh) . faceVertices
allFacePoints :: Fractional a => Mesh a -> FacePointArray a
allFacePoints = fmap1 facePoint meshFaces
vertexPointById :: Mesh a -> VertexId -> a
vertexPointById mesh = vertexPoint . (meshVertices mesh !)
edgeCenterPoint :: Fractional a => Mesh a -> Edge -> EdgeCenterPoint a
edgeCenterPoint mesh (Edge ea eb _)
= EdgeCenterPoint . average $ fmap (vertexPointById mesh) [ea, eb]
allEdgeCenterPoints :: Fractional a => Mesh a -> EdgeCenterPointArray a
allEdgeCenterPoints = fmap1 edgeCenterPoint meshEdges
allIsEdgeHoles :: Mesh a -> IsEdgeHoleArray
allIsEdgeHoles = fmap ((< 2) . length . edgeFaces) . meshEdges
edgePoint :: Fractional a => Edge -> FacePointArray a -> EdgeCenterPoint a -> EdgePoint a
edgePoint (Edge _ _ [_]) _ (EdgeCenterPoint ecp) = EdgePoint ecp
edgePoint (Edge _ _ faceIds) facePoints (EdgeCenterPoint ecp)
= EdgePoint $ average [ecp, average $ fmap (getFacePoint . (facePoints !)) faceIds]
allEdgePoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> EdgePointArray a
allEdgePoints mesh fps ecps = aZipWith (\e ecp -> edgePoint e fps ecp) (meshEdges mesh) ecps
vertexPoint' :: Fractional a => Vertex a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPoint a
vertexPoint' vertex facePoints ecps iehs
| length faceIds == length edgeIds = VertexPoint newCoords
| otherwise = VertexPoint avgHoleEcps
where
newCoords = (oldCoords * m1) + (avgFacePoints * m2) + (avgMidEdges * m3)
oldCoords = vertexPoint vertex
avgFacePoints = average $ fmap (getFacePoint . (facePoints !)) faceIds
avgMidEdges = average $ fmap (getEdgeCenterPoint . (ecps !)) edgeIds
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
n = genericLength faceIds
faceIds = vertexFaces vertex
edgeIds = vertexEdges vertex
avgHoleEcps = average . (oldCoords:) . fmap (getEdgeCenterPoint . (ecps !)) $ filter (iehs !) edgeIds
allVertexPoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPointArray a
allVertexPoints mesh fps ecps iehs = fmap (\v -> vertexPoint' v fps ecps iehs) (meshVertices mesh)
-- For each vertex in a face, generate a set of new faces from it with its vertex point,
-- neighbor edge points, and face point. The new faces will refer to vertices in the
-- combined vertex array.
newFaces :: Face -> FaceId -> Int -> Int -> [SimpleFace]
newFaces (Face vertexIds edgeIds) faceId epOffset vpOffset
= take (genericLength vertexIds)
$ zipWith3 newFace (cycle vertexIds) (cycle edgeIds) (drop 1 (cycle edgeIds))
where
f = VertexId . (+ epOffset) . getEdgeId
newFace vid epA epB = SimpleFace
[ VertexId . (+ vpOffset) $ getVertexId vid
, f epA
, VertexId $ getFaceId faceId
, f epB]
subdivide :: Fractional a => SimpleMesh a -> SimpleMesh a
subdivide simpleMesh
= SimpleMesh combinedVertices (listArray (FaceId 0, FaceId (genericLength faces - 1)) faces)
where
mesh = makeComplexMesh simpleMesh
fps = allFacePoints mesh
ecps = allEdgeCenterPoints mesh
eps = allEdgePoints mesh fps ecps
iehs = allIsEdgeHoles mesh
vps = allVertexPoints mesh fps ecps iehs
edgePointOffset = length fps
vertexPointOffset = edgePointOffset + length eps
combinedVertices
= listArray (VertexId 0, VertexId (vertexPointOffset + length vps - 1))
. fmap SimpleVertex
$ concat [ fmap getFacePoint $ elems fps
, fmap getEdgePoint $ elems eps
, fmap getVertexPoint $ elems vps]
faces
= concat $ zipWith (\face fid -> newFaces face fid edgePointOffset vertexPointOffset)
(elems $ meshFaces mesh) (fmap FaceId [0..])
-- Transform to a Mesh by filling in the missing references and generating edges.
-- Faces can be updated with their edges, but must be ordered.
-- Edge and face order does not matter for vertices.
-- TODO: Discard degenerate faces (ones with 0 to 2 vertices/edges),
-- or we could transform these into single edges or vertices.
makeComplexMesh :: forall a. SimpleMesh a -> Mesh a
makeComplexMesh (SimpleMesh sVertices sFaces) = Mesh vertices edges faces
where
makeEdgesFromFace :: SimpleFace -> FaceId -> [Edge]
makeEdgesFromFace (SimpleFace vertexIds) fid
= take (genericLength vertexIds)
$ zipWith (\a b -> Edge a b [fid]) verts (drop 1 verts)
where
verts = cycle vertexIds
edgeKey :: VertexId -> VertexId -> (VertexId, VertexId)
edgeKey a b = (min a b, max a b)
sFacesList :: [SimpleFace]
sFacesList = elems sFaces
fids :: [FaceId]
fids = fmap FaceId [0..]
eids :: [EdgeId]
eids = fmap EdgeId [0..]
faceEdges :: [[Edge]]
faceEdges = zipWith makeEdgesFromFace sFacesList fids
edgeMap :: Map.Map (VertexId, VertexId) Edge
edgeMap
= Map.fromListWith (\(Edge a b fidsA) (Edge _ _ fidsB) -> Edge a b (fidsA ++ fidsB))
. fmap (\edge@(Edge a b _) -> (edgeKey a b, edge))
$ concat faceEdges
edges :: EdgeArray
edges = listArray (EdgeId 0, EdgeId $ (Map.size edgeMap) - 1) $ Map.elems edgeMap
edgeIdMap :: Map.Map (VertexId, VertexId) EdgeId
edgeIdMap = Map.fromList $ zipWith (\(Edge a b _) eid -> ((edgeKey a b), eid)) (elems edges) eids
faceEdgeIds :: [[EdgeId]]
faceEdgeIds = fmap (mapMaybe (\(Edge a b _) -> Map.lookup (edgeKey a b) edgeIdMap)) faceEdges
faces :: FaceArray
faces
= listArray (FaceId 0, FaceId $ (length sFaces) - 1)
$ zipWith (\(SimpleFace verts) edgeIds -> Face verts edgeIds) sFacesList faceEdgeIds
vidsToFids :: Map.Map VertexId [FaceId]
vidsToFids
= Map.fromListWith (++)
. concat
$ zipWith (\(SimpleFace vertexIds) fid -> fmap (\vid -> (vid, [fid])) vertexIds) sFacesList fids
vidsToEids :: Map.Map VertexId [EdgeId]
vidsToEids
= Map.fromListWith (++)
. concat
$ zipWith (\(Edge a b _) eid -> [(a, [eid]), (b, [eid])]) (elems edges) eids
simpleToComplexVert :: SimpleVertex a -> VertexId -> Vertex a
simpleToComplexVert (SimpleVertex point) vid
= Vertex point
(Map.findWithDefault [] vid vidsToEids)
(Map.findWithDefault [] vid vidsToFids)
vertices :: VertexArray a
vertices
= listArray (bounds sVertices)
$ zipWith simpleToComplexVert (elems sVertices) (fmap VertexId [0..])
pShowSimpleMesh :: Show a => SimpleMesh a -> String
pShowSimpleMesh (SimpleMesh vertices faces)
= "Vertices:\n" ++ (arrShow vertices sVertexPoint)
++ "Faces:\n" ++ (arrShow faces (fmap getVertexId . sFaceVertices))
where
arrShow a f = concatMap ((++ "\n") . show . (\(i, e) -> (i, f e))) . zip [0 :: Int ..] $ elems a
-- Testing types.
data Point a = Point a a a deriving (Show)
instance Functor Point where
fmap f (Point x y z) = Point (f x) (f y) (f z)
zipPoint :: (a -> b -> c) -> Point a -> Point b -> Point c
zipPoint f (Point x y z) (Point x' y' z') = Point (f x x') (f y y') (f z z')
instance Num a => Num (Point a) where
(+) = zipPoint (+)
(-) = zipPoint (-)
(*) = zipPoint (*)
negate = fmap negate
abs = fmap abs
signum = fmap signum
fromInteger i = let i' = fromInteger i in Point i' i' i'
instance Fractional a => Fractional (Point a) where
recip = fmap recip
fromRational r = let r' = fromRational r in Point r' r' r'
testCube :: SimpleMesh (Point Double)
testCube = SimpleMesh vertices faces
where
vertices = listArray (VertexId 0, VertexId 7)
$ fmap SimpleVertex
[ Point (-1) (-1) (-1)
, Point (-1) (-1) 1
, Point (-1) 1 (-1)
, Point (-1) 1 1
, Point 1 (-1) (-1)
, Point 1 (-1) 1
, Point 1 1 (-1)
, Point 1 1 1]
faces = listArray (FaceId 0, FaceId 5)
$ fmap (SimpleFace . (fmap VertexId))
[ [0, 4, 5, 1]
, [4, 6, 7, 5]
, [6, 2, 3, 7]
, [2, 0, 1, 3]
, [1, 5, 7, 3]
, [0, 2, 6, 4]]
testCubeWithHole :: SimpleMesh (Point Double)
testCubeWithHole
= SimpleMesh (sMeshVertices testCube) (ixmap (FaceId 0, FaceId 4) id (sMeshFaces testCube))
testTriangle :: SimpleMesh (Point Double)
testTriangle = SimpleMesh vertices faces
where
vertices = listArray (VertexId 0, VertexId 2)
$ fmap SimpleVertex
[ Point 0 0 0
, Point 0 0 1
, Point 0 1 0]
faces = listArray (FaceId 0, FaceId 0)
$ fmap (SimpleFace . (fmap VertexId))
[ [0, 1, 2]]
main :: IO ()
main = putStr . pShowSimpleMesh $ subdivide testCube |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #ALGOL_68 | ALGOL 68 | # sieve of Eratosthene: sets s[i] to TRUE if i is prime, FALSE otherwise #
PROC sieve = ( REF[]BOOL s )VOID:
BEGIN
# start with everything flagged as prime #
FOR i TO UPB s DO s[ i ] := TRUE OD;
# sieve out the non-primes #
s[ 1 ] := FALSE;
FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO
IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI
OD
END # sieve # ;
# construct a sieve of primes up to the maximum number required for the task #
# For Prime1, we need to check numbers up to around 120 000 #
INT max number = 200 000;
[ 1 : max number ]BOOL is prime;
sieve( is prime );
# Find the Carmichael 3 Stromg Pseudoprimes for Prime1 up to 61 #
FOR prime1 FROM 2 TO 61 DO
IF is prime[ prime 1 ] THEN
FOR h3 TO prime1 - 1 DO
FOR d TO ( h3 + prime1 ) - 1 DO
IF ( h3 + prime1 ) * ( prime1 - 1 ) MOD d = 0
AND ( - ( prime1 * prime1 ) ) MOD h3 = d MOD h3
THEN
INT prime2 = 1 + ( ( prime1 - 1 ) * ( h3 + prime1 ) OVER d );
IF is prime[ prime2 ] THEN
INT prime3 = 1 + ( prime1 * prime2 OVER h3 );
IF is prime[ prime3 ] THEN
IF ( prime2 * prime3 ) MOD ( prime1 - 1 ) = 1 THEN
print( ( whole( prime1, 0 ), " ", whole( prime2, 0 ), " ", whole( prime3, 0 ), newline ) )
FI
FI
FI
FI
OD
OD
FI
OD |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #C.23 | C# | var nums = Enumerable.Range(1, 10);
int summation = nums.Aggregate((a, b) => a + b);
int product = nums.Aggregate((a, b) => a * b);
string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString());
Console.WriteLine("{0} {1} {2}", summation, product, concatenation); |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Objeck | Objeck | class Chaocipher {
L_ALPHABET : static : Char[];
R_ALPHABET : static : Char[];
function : Main(args : String[]) ~ Nil {
L_ALPHABET := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"->ToCharArray();
R_ALPHABET := "PTLNBQDEOYSFAVZKGJRIHWXUMC"->ToCharArray();
plainText := "WELLDONEISBETTERTHANWELLSAID"->ToCharArray();
System.IO.Console->Print("The original plaintext is: ")->PrintLine(plainText);
"\nThe left and right alphabets after each permutation during encryption are:\n"->PrintLine();
cipherText := Chao(plainText, Mode->ENCRYPT, true);
System.IO.Console->Print("\nThe ciphertext is: ")->PrintLine(cipherText);
plainText2 := Chao(cipherText, Mode->DECRYPT, false);
System.IO.Console->Print("The recovered plaintext is: ")->PrintLine(plainText2);
}
function : Chao(in : Char[], mode : Mode, show_steps : Bool) ~ Char[] {
i : Int; j : Int; index : Int;
store : Char;
len := in->Size();
left := Char->New[26]; right := Char->New[26]; temp := Char->New[26];
eText := Char->New[len];
Runtime->Copy(left, 0, L_ALPHABET, 0, L_ALPHABET->Size());
Runtime->Copy(right, 0, R_ALPHABET, 0, R_ALPHABET->Size());
for(i := 0; i < len; i += 1;) {
if (show_steps) {
System.IO.Console->Print(left)->Print(' ')->PrintLine(right);
};
if (mode = Mode->ENCRYPT) {
index := IndexOf(right, in[i]);
eText[i] := left[index];
}
else {
index := IndexOf(left, in[i]);
eText[i] := right[index];
};
if (i = len - 1) {
break;
};
# left
for(j := index; j < 26; j += 1;) { temp[j - index] := left[j]; };
for(j :=0; j < index; j += 1;) { temp[26 - index + j] := left[j]; };
store := temp[1];
for(j := 2; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
temp[13] := store;
Runtime->Copy(left, 0, temp, 0, temp->Size());
# right
for(j := index; j < 26; j += 1;) { temp[j - index] := right[j]; };
for(j :=0; j < index; j += 1;) { temp[26 - index + j] := right[j]; };
store := temp[0];
for(j :=1; j < 26; j += 1;) { temp[j - 1] := temp[j]; };
temp[25] := store;
store := temp[2];
for(j := 3; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
temp[13] := store;
Runtime->Copy(right, 0, temp, 0, temp->Size());
};
return eText;
}
function : IndexOf(str : Char[], c : Char) ~ Int {
for(i := 0; i < str->Size(); i += 1;) {
if(c = str[i]) {
return i;
};
};
return -1;
}
enum Mode { ENCRYPT, DECRYPT }
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #J | J | Catalan=. }:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\@]^:[ #&1)@:(2&+) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' FreeBASIC is case-insensitive
Dim dog As String
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
Print "There is just one dog, named "; dog
Sleep |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Frink | Frink | dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
println["There are three dogs named $dog, $Dog and $DOG"] |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Clojure | Clojure |
(ns clojure.examples.product
(:gen-class)
(:require [clojure.pprint :as pp]))
(defn cart [colls]
"Compute the cartesian product of list of lists"
(if (empty? colls)
'(())
(for [more (cart (rest colls))
x (first colls)]
(cons x more))))
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #ALGOL_W | ALGOL W | begin
% print the catalan numbers up to C15 %
integer Cprev;
Cprev := 1; % C0 %
write( s_w := 0, i_w := 3, 0, ": ", i_w := 9, Cprev );
for n := 1 until 15 do begin
Cprev := round( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * Cprev );
write( s_w := 0, i_w := 3, n, ": ", i_w := 9, Cprev );
end for_n
end. |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #ALGOL_68 | ALGOL 68 | BEGIN # show IPv4 addresses in CIDR notation in canonical form #
# mode to hold an IPv4 address in CIDR notation #
MODE CIDR = STRUCT( BITS address
, INT network bits
, BOOL valid
, STRING error
);
# returns a CIDR parsed from address #
OP TOCIDR = ( STRING address text )CIDR:
BEGIN
STRING addr = "." + address text + "$";
STRING error := "";
BITS address := 16r0;
INT bits count := 0;
INT dot count := 0;
INT slash count := 0;
BOOL valid := TRUE;
INT s pos := LWB addr;
INT s max = UPB addr;
WHILE s pos < s max AND valid DO
IF addr[ s pos ] = "." THEN
# must have an octet next #
dot count +:= 1;
INT octet := 0;
INT digits := 0;
WHILE CHAR c = addr[ s pos +:= 1 ];
c >= "0" AND c <= "9"
DO
octet *:= 10 +:= ( ABS c - ABS "0" );
digits +:= 1
OD;
address := ( address SHL 8 ) OR BIN ( octet MOD 256 );
valid := valid AND digits > 0 AND digits < 4 AND octet < 256;
IF NOT valid THEN error := "too many digits/octet to large" FI
ELIF addr[ s pos ] = "/" THEN
# must have the network mask length next #
slash count +:= 1;
WHILE CHAR c = addr[ s pos +:= 1 ];
c >= "0" AND c <= "9"
DO
bits count *:= 10 +:= ( ABS c - ABS "0" )
OD;
# should be "$" ( end of string marker ) next #
valid := valid AND addr[ s pos ] = "$";
IF NOT valid THEN error := "bit length not followed by end-of-string" FI
ELIF addr[ s pos ] = "$" THEN
# end of address marker - must be the final character #
valid := valid AND s pos = s max;
IF NOT valid THEN error := "Invalid character: ""$""" FI
ELSE
# invalid character #
valid := FALSE;
error := "Invalid character: """ + addr[ s pos ] + """"
FI
OD;
IF valid THEN
# address is OK so far - check it had four octets and one mask length #
valid := dot count = 4 # note a leading "." was added for parsing #
AND slash count = 1
AND bits count > 0
AND bits count < 33;
IF NOT valid THEN error := "too many dots, slashes or bits" FI
FI;
CIDR( address, bits count, valid, error )
END # TOCIDR # ;
# returns address in canonical form #
OP CANONICALISE = ( CIDR address )CIDR:
IF NOT valid OF address THEN
# invalid address #
address
ELSE
# valid address - retain the top most bits #
CIDR( address OF address AND ( 16rffffffff
SHL ( 32 - network bits OF address )
)
, network bits OF address
, TRUE
, ""
)
FI # CANONICALISE # ;
# returns a readable form of address #
OP TOSTRING = ( CIDR address )STRING:
BEGIN
[ 1 : 4 ]INT octet;
BITS addr := address OF address;
FOR o pos FROM UPB octet BY -1 TO LWB octet DO
octet[ o pos ] := ABS ( addr AND 16rff );
addr := addr SHR 8
OD;
STRING result := whole( octet[ LWB octet ], 0 );
FOR o pos FROM 1 + LWB octet TO UPB octet DO
result +:= "." + whole( octet[ o pos ], 0 )
OD;
result + "/" + whole( network bits OF address, 0 )
END # TOSTRING # ;
# task examples : input expected result #
[,]STRING test cases = ( ( "87.70.141.1/22", "87.70.140.0/22" )
, ( "36.18.154.103/12", "36.16.0.0/12" )
, ( "62.62.197.11/29", "62.62.197.8/29" )
, ( "67.137.119.181/4", "64.0.0.0/4" )
, ( "161.214.74.21/24", "161.214.74.0/24" )
, ( "184.232.176.184/18", "184.232.128.0/18" )
);
FOR t pos FROM 1 LWB test cases TO 1 UPB test cases DO
STRING addr = test cases[ t pos, 1 ];
CIDR canon = CANONICALISE TOCIDR addr;
IF NOT valid OF canon THEN
print( ( "Invalid address: """, addr, """: ", error OF canon, newline ) )
ELSE
STRING actual = TOSTRING canon;
STRING expected = test cases[ t pos, 2 ];
print( ( addr
, " -> "
, actual
, IF expected = actual THEN "" ELSE " ** EXPECTED: """ + expected + """" FI
, newline
)
)
FI
OD
END |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastingOutNines {
public static class Helper {
public static string AsString<T>(this IEnumerable<T> e) {
var it = e.GetEnumerator();
StringBuilder builder = new StringBuilder();
builder.Append("[");
if (it.MoveNext()) {
builder.Append(it.Current);
}
while (it.MoveNext()) {
builder.Append(", ");
builder.Append(it.Current);
}
builder.Append("]");
return builder.ToString();
}
}
class Program {
static List<int> CastOut(int @base, int start, int end) {
int[] ran = Enumerable
.Range(0, @base - 1)
.Where(a => a % (@base - 1) == (a * a) % (@base - 1))
.ToArray();
int x = start / (@base - 1);
List<int> result = new List<int>();
while (true) {
foreach (int n in ran) {
int k = (@base - 1) * x + n;
if (k < start) {
continue;
}
if (k > end) {
return result;
}
result.Add(k);
}
x++;
}
}
static void Main() {
Console.WriteLine(CastOut(16, 1, 255).AsString());
Console.WriteLine(CastOut(10, 1, 99).AsString());
Console.WriteLine(CastOut(17, 1, 288).AsString());
}
}
} |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #J | J | avg=: +/ % #
havePoints=: e."1/~ i.@#
catmullclark=:3 :0
'mesh points'=. y
face_point=. avg"2 mesh{points
point_face=. |: mesh havePoints points
avg_face_points=. point_face avg@#"1 2 face_point
edges=. ~.,/ meshEdges=. mesh /:~@,"+1|."1 mesh
edge_face=. *./"2 edges e."0 1/ mesh
edge_center=. avg"2 edges{points
edge_point=. (0.5*edge_center) + 0.25 * edge_face +/ .* face_point
point_edge=. |: edges havePoints points
avg_mid_edges=. point_edge avg@#"1 2 edge_center
n=. +/"1 point_edge
'm3 m2 m1'=. (2,1,:n-3)%"1 n
new_coords=. (m1 * points) + (m2 * avg_face_points) + (m3 * avg_mid_edges)
pts=. face_point,edge_point,new_coords
c0=. (#edge_point)+ e0=. #face_point
msh=. (,c0+mesh),.(,e0+edges i. meshEdges),.((#i.)~/$mesh),.,e0+_1|."1 edges i. meshEdges
msh;pts
) |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #AWK | AWK |
# syntax: GAWK -f CARMICHAEL_3_STRONG_PSEUDOPRIMES.AWK
# converted from C
BEGIN {
printf("%5s%8s%8s%13s\n","P1","P2","P3","PRODUCT")
for (p1=2; p1<62; p1++) {
if (!is_prime(p1)) { continue }
for (h3=1; h3<p1; h3++) {
for (d=1; d<h3+p1; d++) {
if ((h3+p1)*(p1-1)%d == 0 && mod(-p1*p1,h3) == d%h3) {
p2 = int(1+((p1-1)*(h3+p1)/d))
if (!is_prime(p2)) { continue }
p3 = int(1+(p1*p2/h3))
if (!is_prime(p3) || (p2*p3)%(p1-1) != 1) { continue }
printf("%5d x %5d x %5d = %10d\n",p1,p2,p3,p1*p2*p3)
count++
}
}
}
}
printf("%d numbers\n",count)
exit(0)
}
function is_prime(n, i) {
if (n <= 3) {
return(n > 1)
}
else if (!(n%2) || !(n%3)) {
return(0)
}
else {
for (i=5; i*i<=n; i+=6) {
if (!(n%i) || !(n%(i+2))) {
return(0)
}
}
return(1)
}
}
function mod(n,m) {
# the % operator actually calculates the remainder of a / b so we need a small adjustment so it works as expected for negative values
return(((n%m)+m)%m)
}
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #C.2B.2B | C++ | #include <iostream>
#include <numeric>
#include <functional>
#include <vector>
int main() {
std::vector<int> nums = { 1, 2, 3, 4, 5 };
auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
return a + 2 * b;
});
std::cout << "nums_added: " << nums_added << std::endl;
std::cout << "nums_other: " << nums_other << std::endl;
} |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Pascal | Pascal | program chaocipher(input, output);
const
{ This denotes a `set` literal: }
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
{ The `card` function is an Extended Pascal (ISO 10206) extension. }
alphabetCardinality = card(alphabet);
{ 1st character denotes “zenith”. }
zenith = 1;
{ In a 26-character alphabet the 14th character denotes “nadir”. }
nadir = alphabetCardinality div 2 + 1;
{ For simplicity use compile-time-defined maximum lengths. }
messageMaximumLength = 80;
type
{ This “discriminates” the Extended Pascal schema data type `string` to be }
{ capable of holding strings up to `alphabetCardinality` `char` values. }
map = string(alphabetCardinality);
{ Variables of this data type can only assume integer values within 1..26: }
mapCharacterIndex = 1..alphabetCardinality;
{ Later used as a buffer for the input/output. }
message = string(messageMaximumLength);
messageCharacterIndex = 1..messageMaximumLength;
{ Stores a key for the Chaocipher algorithm. }
key = record
cipherText: map;
plainText: map;
end;
{ --- auxilliary routines ---------------------------------------------- }
{
\brief verifies that a key is valid for the Chaocipher
\param sample a potential `key` for a Chaocipher
\return `true` iff \param sample is an acceptable `key`
}
{ `protected` (Extended Pascal extension) denotes an immutable parameter. }
function isValid(protected sample: key): Boolean;
{ Determines whether a `map` contains all characters of `alphabet`. }
{ Nesting this function allows for a neat expression below. }
function isComplete(protected text: map): Boolean;
var
i: integer;
{ `value []` will initialize this variable to an empty set value. }
{ This is an Extended Pascal (ISO 10206) extension. }
s: set of char value [];
begin
{ NB: In Pascal `for`-loop limits are inclusive. }
for i := 1 to length(text) do
begin
{ This adds the set containing one character to the set `s`. }
s := s + [text[i]]
end;
isComplete := card(s) = alphabetCardinality
end;
begin
{ This way `sample.cipherText` can be simply written as `cipherText`. }
with sample do
begin
{ `and_then` is an EP extension indicating “lazy evaluation”. }
isValid := (alphabetCardinality > 8) and_then
isComplete(cipherText) and_then isComplete(plainText)
end
end;
{
\brief permutes a key for the next encryption/decryption step
\param shift the index of the characters just substituted
}
{ `var` means the parameter value will be modified _at_ the call site. }
procedure permute(var state: key; protected shift: mapCharacterIndex);
begin
with state do
begin
{ Indices in `cipherText[1..pred(shift)]` _must_ be non-descending: }
if shift > 1 then
begin
cipherText := subStr(cipherText, shift) + cipherText[1..pred(shift)]
{ `subStr(str, ini)` is equivalent to `str[ini..length(str)]`. }
end;
{ Likewise, `succ(shift)` must be a valid index in `plainText`: }
if shift < alphabetCardinality then
begin
plainText := subStr(plainText, succ(shift)) + plainText[1..shift]
end;
{ If it does _not_ _alter_ the _entire_ string’s _length_, you can }
{ modify parts of a string like this (Extended Pascal extension): }
cipherText[zenith+1..nadir] := cipherText[zenith+2..nadir] + cipherText[zenith+1];
plainText[zenith+2..nadir] := plainText[zenith+3..nadir] + plainText[zenith+2]
end
end;
{ --- the core routine of the algorithm -------------------------------- }
{
\brief performs Chaocipher common steps
\param line the message to encrypt/decrypt
\param state the initial key to start encrpytion/decryption with
\param locate a function determining the 2-tuple index in the key
\param substitute the procedure substituting the correct characters
}
procedure chaocipher(
var line: message;
var state: key;
{ These are “routine parameters”. Essentially the address of a routine }
{ matching the specified routine signature is passed to `chaocipher`. }
function locate(protected i: messageCharacterIndex): mapCharacterIndex;
procedure substitute(
protected i: messageCharacterIndex;
protected z: mapCharacterIndex
)
);
var
{ For demonstration purposes: In this program }
{ `line.capacity` refers to `messageMaximumLength`. }
i: 1..line.capacity;
substitutionPairIndex: mapCharacterIndex;
begin
{ Don’t trust user input, even though this is just a RosettaCode example. }
if not isValid(state) then
begin
writeLn('Error: Key is invalid. Got:');
writeLn('Cipher text: ', state.cipherText);
writeLn(' Plain text: ', state.plainText);
halt
end;
for i := 1 to length(line) do
begin
{ We’ll better skip characters that aren’t in the `alphabet`. }
if line[i] in alphabet then
begin
{ Here you see the beauty of using routine parameters. }
{ Depending on whether we’re encrypting or decrypting, }
{ you need to find a character in the `cipherText` or }
{ `plainText` key value respectively, yet the basic order
{ of the steps are still the same. }
substitutionPairIndex := locate(i);
substitute(i, substitutionPairIndex);
permute(state, substitutionPairIndex)
end
end
end;
{ --- entry routines --------------------------------------------------- }
{
\brief encrypts a message according to Chaocipher
\param line a message to encrypt
\param state the key to begin with
\return the encrypted message \param line using the provided key
}
{ Note: without `var` or `protected` both `encrypt` and `decrypt`get }
{ and have their own independent copies of the parameter values. }
function encrypt(line: message; state: key): message;
function encryptor(protected i: messageCharacterIndex): mapCharacterIndex;
begin
encryptor := index(state.plainText, line[i])
end;
procedure substitutor(
protected i: messageCharacterIndex;
protected z: mapCharacterIndex
);
begin
line[i] := state.cipherText[z]
end;
begin
chaocipher(line, state, encryptor, substitutor);
encrypt := line
end;
{
\brief decrypts a message according to Chaocipher
\param line the encrypted message
\param state the key to begin with
\return the decrypted message \param line using the provided key
}
function decrypt(line: message; state: key): message;
function decryptor(protected i: messageCharacterIndex): mapCharacterIndex;
begin
decryptor := index(state.cipherText, line[i])
end;
procedure substitutor(
protected i: messageCharacterIndex;
protected z: mapCharacterIndex
);
begin
line[i] := state.plainText[z]
end;
begin
chaocipher(line, state, decryptor, substitutor);
decrypt := line
end;
{ === MAIN ============================================================= }
var
exampleKey: key;
line: message;
begin
{ Instead of writing `exampleKey.cipherText := '…', you can }
{ write in Extended Pascal a `record` literal like this: }
exampleKey := key[
cipherText: 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
plainText: 'PTLNBQDEOYSFAVZKGJRIHWXUMC';
];
{ `EOF` is shorthand for `EOF(input)`. }
while not EOF do
begin
{ `readLn(line)` is shorthand for `readLn(input, line)`. }
readLn(line);
line := encrypt(line, exampleKey);
writeLn(decrypt(line, exampleKey));
{ Likewise, `writeLn(line)` is short for `writeLn(output, line)`. }
writeLn(line)
end
end. |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Java | Java | public class Test {
public static void main(String[] args) {
int N = 15;
int[] t = new int[N + 2];
t[1] = 1;
for (int i = 1; i <= N; i++) {
for (int j = i; j > 1; j--)
t[j] = t[j] + t[j - 1];
t[i + 1] = t[i];
for (int j = i + 1; j > 1; j--)
t[j] = t[j] + t[j - 1];
System.out.printf("%d ", t[i + 1] - t[i]);
}
}
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Gambas | Gambas | Public Sub Main()
Dim dog As String
Dog = "Benjamin"
DOG = "Samba"
dog = "Bernie"
Print "There is just one dog, named "; dog
End |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #GAP | GAP | # GAP is case sensitive
ThreeDogs := function()
local dog, Dog, DOG;
dog := "Benjamin";
Dog := "Samba";
DOG := "Bernie";
if dog = DOG then
Print("There is just one dog named ", dog, "\n");
else
Print("The three dogs are named ", dog, ", ", Dog, " and ", DOG, "\n");
fi;
end;
ThreeDogs();
# The three dogs are named Benjamin, Samba and Bernie |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Common_Lisp | Common Lisp | (defun cartesian-product (s1 s2)
"Compute the cartesian product of two sets represented as lists"
(loop for x in s1
nconc (loop for y in s2 collect (list x y))))
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #APL | APL | {(!2×⍵)÷(!⍵+1)×!⍵}(⍳15)-1 |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #11l | 11l | V WIDTH = 81
V HEIGHT = 5
F cantor(start, len, index)
V seg = len I/ 3
I seg == 0
R
L(it) 0 .< :HEIGHT - index
V i = index + it
L(jt) 0 .< seg
V j = start + seg + jt
V pos = i * :WIDTH + j
:lines[pos] = ‘ ’
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
V lines = [‘*’] * (WIDTH * HEIGHT)
cantor(0, WIDTH, 1)
L(i) 0 .< HEIGHT
V beg = WIDTH * i
print((lines[beg .< beg + WIDTH]).join(‘’)) |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #C | C | #include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#define MAX_BRIGHTNESS 255
// C99 doesn't define M_PI (GNU-C99 does)
#define M_PI 3.14159265358979323846264338327
/*
* Loading part taken from
* http://www.vbforums.com/showthread.php?t=261522
* BMP info:
* http://en.wikipedia.org/wiki/BMP_file_format
*
* Note: the magic number has been removed from the bmpfile_header_t
* structure since it causes alignment problems
* bmpfile_magic_t should be written/read first
* followed by the
* bmpfile_header_t
* [this avoids compiler-specific alignment pragmas etc.]
*/
typedef struct {
uint8_t magic[2];
} bmpfile_magic_t;
typedef struct {
uint32_t filesz;
uint16_t creator1;
uint16_t creator2;
uint32_t bmp_offset;
} bmpfile_header_t;
typedef struct {
uint32_t header_sz;
int32_t width;
int32_t height;
uint16_t nplanes;
uint16_t bitspp;
uint32_t compress_type;
uint32_t bmp_bytesz;
int32_t hres;
int32_t vres;
uint32_t ncolors;
uint32_t nimpcolors;
} bitmap_info_header_t;
typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t nothing;
} rgb_t;
// Use short int instead `unsigned char' so that we can
// store negative values.
typedef short int pixel_t;
pixel_t *load_bmp(const char *filename,
bitmap_info_header_t *bitmapInfoHeader)
{
FILE *filePtr = fopen(filename, "rb");
if (filePtr == NULL) {
perror("fopen()");
return NULL;
}
bmpfile_magic_t mag;
if (fread(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {
fclose(filePtr);
return NULL;
}
// verify that this is a bmp file by check bitmap id
// warning: dereferencing type-punned pointer will break
// strict-aliasing rules [-Wstrict-aliasing]
if (*((uint16_t*)mag.magic) != 0x4D42) {
fprintf(stderr, "Not a BMP file: magic=%c%c\n",
mag.magic[0], mag.magic[1]);
fclose(filePtr);
return NULL;
}
bmpfile_header_t bitmapFileHeader; // our bitmap file header
// read the bitmap file header
if (fread(&bitmapFileHeader, sizeof(bmpfile_header_t),
1, filePtr) != 1) {
fclose(filePtr);
return NULL;
}
// read the bitmap info header
if (fread(bitmapInfoHeader, sizeof(bitmap_info_header_t),
1, filePtr) != 1) {
fclose(filePtr);
return NULL;
}
if (bitmapInfoHeader->compress_type != 0)
fprintf(stderr, "Warning, compression is not supported.\n");
// move file point to the beginning of bitmap data
if (fseek(filePtr, bitmapFileHeader.bmp_offset, SEEK_SET)) {
fclose(filePtr);
return NULL;
}
// allocate enough memory for the bitmap image data
pixel_t *bitmapImage = malloc(bitmapInfoHeader->bmp_bytesz *
sizeof(pixel_t));
// verify memory allocation
if (bitmapImage == NULL) {
fclose(filePtr);
return NULL;
}
// read in the bitmap image data
size_t pad, count=0;
unsigned char c;
pad = 4*ceil(bitmapInfoHeader->bitspp*bitmapInfoHeader->width/32.) - bitmapInfoHeader->width;
for(size_t i=0; i<bitmapInfoHeader->height; i++){
for(size_t j=0; j<bitmapInfoHeader->width; j++){
if (fread(&c, sizeof(unsigned char), 1, filePtr) != 1) {
fclose(filePtr);
return NULL;
}
bitmapImage[count++] = (pixel_t) c;
}
fseek(filePtr, pad, SEEK_CUR);
}
// If we were using unsigned char as pixel_t, then:
// fread(bitmapImage, 1, bitmapInfoHeader->bmp_bytesz, filePtr);
// close file and return bitmap image data
fclose(filePtr);
return bitmapImage;
}
// Return: true on error.
bool save_bmp(const char *filename, const bitmap_info_header_t *bmp_ih,
const pixel_t *data)
{
FILE* filePtr = fopen(filename, "wb");
if (filePtr == NULL)
return true;
bmpfile_magic_t mag = {{0x42, 0x4d}};
if (fwrite(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
const uint32_t offset = sizeof(bmpfile_magic_t) +
sizeof(bmpfile_header_t) +
sizeof(bitmap_info_header_t) +
((1U << bmp_ih->bitspp) * 4);
const bmpfile_header_t bmp_fh = {
.filesz = offset + bmp_ih->bmp_bytesz,
.creator1 = 0,
.creator2 = 0,
.bmp_offset = offset
};
if (fwrite(&bmp_fh, sizeof(bmpfile_header_t), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
if (fwrite(bmp_ih, sizeof(bitmap_info_header_t), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
// Palette
for (size_t i = 0; i < (1U << bmp_ih->bitspp); i++) {
const rgb_t color = {(uint8_t)i, (uint8_t)i, (uint8_t)i};
if (fwrite(&color, sizeof(rgb_t), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
}
// We use int instead of uchar, so we can't write img
// in 1 call any more.
// fwrite(data, 1, bmp_ih->bmp_bytesz, filePtr);
// Padding: http://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage
size_t pad = 4*ceil(bmp_ih->bitspp*bmp_ih->width/32.) - bmp_ih->width;
unsigned char c;
for(size_t i=0; i < bmp_ih->height; i++) {
for(size_t j=0; j < bmp_ih->width; j++) {
c = (unsigned char) data[j + bmp_ih->width*i];
if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
}
c = 0;
for(size_t j=0; j<pad; j++)
if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {
fclose(filePtr);
return true;
}
}
fclose(filePtr);
return false;
}
// if normalize is true, map pixels to range 0..MAX_BRIGHTNESS
void convolution(const pixel_t *in, pixel_t *out, const float *kernel,
const int nx, const int ny, const int kn,
const bool normalize)
{
assert(kn % 2 == 1);
assert(nx > kn && ny > kn);
const int khalf = kn / 2;
float min = FLT_MAX, max = -FLT_MAX;
if (normalize)
for (int m = khalf; m < nx - khalf; m++)
for (int n = khalf; n < ny - khalf; n++) {
float pixel = 0.0;
size_t c = 0;
for (int j = -khalf; j <= khalf; j++)
for (int i = -khalf; i <= khalf; i++) {
pixel += in[(n - j) * nx + m - i] * kernel[c];
c++;
}
if (pixel < min)
min = pixel;
if (pixel > max)
max = pixel;
}
for (int m = khalf; m < nx - khalf; m++)
for (int n = khalf; n < ny - khalf; n++) {
float pixel = 0.0;
size_t c = 0;
for (int j = -khalf; j <= khalf; j++)
for (int i = -khalf; i <= khalf; i++) {
pixel += in[(n - j) * nx + m - i] * kernel[c];
c++;
}
if (normalize)
pixel = MAX_BRIGHTNESS * (pixel - min) / (max - min);
out[n * nx + m] = (pixel_t)pixel;
}
}
/*
* gaussianFilter:
* http://www.songho.ca/dsp/cannyedge/cannyedge.html
* determine size of kernel (odd #)
* 0.0 <= sigma < 0.5 : 3
* 0.5 <= sigma < 1.0 : 5
* 1.0 <= sigma < 1.5 : 7
* 1.5 <= sigma < 2.0 : 9
* 2.0 <= sigma < 2.5 : 11
* 2.5 <= sigma < 3.0 : 13 ...
* kernelSize = 2 * int(2*sigma) + 3;
*/
void gaussian_filter(const pixel_t *in, pixel_t *out,
const int nx, const int ny, const float sigma)
{
const int n = 2 * (int)(2 * sigma) + 3;
const float mean = (float)floor(n / 2.0);
float kernel[n * n]; // variable length array
fprintf(stderr, "gaussian_filter: kernel size %d, sigma=%g\n",
n, sigma);
size_t c = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
kernel[c] = exp(-0.5 * (pow((i - mean) / sigma, 2.0) +
pow((j - mean) / sigma, 2.0)))
/ (2 * M_PI * sigma * sigma);
c++;
}
convolution(in, out, kernel, nx, ny, n, true);
}
/*
* Links:
* http://en.wikipedia.org/wiki/Canny_edge_detector
* http://www.tomgibara.com/computer-vision/CannyEdgeDetector.java
* http://fourier.eng.hmc.edu/e161/lectures/canny/node1.html
* http://www.songho.ca/dsp/cannyedge/cannyedge.html
*
* Note: T1 and T2 are lower and upper thresholds.
*/
pixel_t *canny_edge_detection(const pixel_t *in,
const bitmap_info_header_t *bmp_ih,
const int tmin, const int tmax,
const float sigma)
{
const int nx = bmp_ih->width;
const int ny = bmp_ih->height;
pixel_t *G = calloc(nx * ny * sizeof(pixel_t), 1);
pixel_t *after_Gx = calloc(nx * ny * sizeof(pixel_t), 1);
pixel_t *after_Gy = calloc(nx * ny * sizeof(pixel_t), 1);
pixel_t *nms = calloc(nx * ny * sizeof(pixel_t), 1);
pixel_t *out = malloc(bmp_ih->bmp_bytesz * sizeof(pixel_t));
if (G == NULL || after_Gx == NULL || after_Gy == NULL ||
nms == NULL || out == NULL) {
fprintf(stderr, "canny_edge_detection:"
" Failed memory allocation(s).\n");
exit(1);
}
gaussian_filter(in, out, nx, ny, sigma);
const float Gx[] = {-1, 0, 1,
-2, 0, 2,
-1, 0, 1};
convolution(out, after_Gx, Gx, nx, ny, 3, false);
const float Gy[] = { 1, 2, 1,
0, 0, 0,
-1,-2,-1};
convolution(out, after_Gy, Gy, nx, ny, 3, false);
for (int i = 1; i < nx - 1; i++)
for (int j = 1; j < ny - 1; j++) {
const int c = i + nx * j;
// G[c] = abs(after_Gx[c]) + abs(after_Gy[c]);
G[c] = (pixel_t)hypot(after_Gx[c], after_Gy[c]);
}
// Non-maximum suppression, straightforward implementation.
for (int i = 1; i < nx - 1; i++)
for (int j = 1; j < ny - 1; j++) {
const int c = i + nx * j;
const int nn = c - nx;
const int ss = c + nx;
const int ww = c + 1;
const int ee = c - 1;
const int nw = nn + 1;
const int ne = nn - 1;
const int sw = ss + 1;
const int se = ss - 1;
const float dir = (float)(fmod(atan2(after_Gy[c],
after_Gx[c]) + M_PI,
M_PI) / M_PI) * 8;
if (((dir <= 1 || dir > 7) && G[c] > G[ee] &&
G[c] > G[ww]) || // 0 deg
((dir > 1 && dir <= 3) && G[c] > G[nw] &&
G[c] > G[se]) || // 45 deg
((dir > 3 && dir <= 5) && G[c] > G[nn] &&
G[c] > G[ss]) || // 90 deg
((dir > 5 && dir <= 7) && G[c] > G[ne] &&
G[c] > G[sw])) // 135 deg
nms[c] = G[c];
else
nms[c] = 0;
}
// Reuse array
// used as a stack. nx*ny/2 elements should be enough.
int *edges = (int*) after_Gy;
memset(out, 0, sizeof(pixel_t) * nx * ny);
memset(edges, 0, sizeof(pixel_t) * nx * ny);
// Tracing edges with hysteresis . Non-recursive implementation.
size_t c = 1;
for (int j = 1; j < ny - 1; j++)
for (int i = 1; i < nx - 1; i++) {
if (nms[c] >= tmax && out[c] == 0) { // trace edges
out[c] = MAX_BRIGHTNESS;
int nedges = 1;
edges[0] = c;
do {
nedges--;
const int t = edges[nedges];
int nbs[8]; // neighbours
nbs[0] = t - nx; // nn
nbs[1] = t + nx; // ss
nbs[2] = t + 1; // ww
nbs[3] = t - 1; // ee
nbs[4] = nbs[0] + 1; // nw
nbs[5] = nbs[0] - 1; // ne
nbs[6] = nbs[1] + 1; // sw
nbs[7] = nbs[1] - 1; // se
for (int k = 0; k < 8; k++)
if (nms[nbs[k]] >= tmin && out[nbs[k]] == 0) {
out[nbs[k]] = MAX_BRIGHTNESS;
edges[nedges] = nbs[k];
nedges++;
}
} while (nedges > 0);
}
c++;
}
free(after_Gx);
free(after_Gy);
free(G);
free(nms);
return out;
}
int main(const int argc, const char ** const argv)
{
if (argc < 2) {
printf("Usage: %s image.bmp\n", argv[0]);
return 1;
}
static bitmap_info_header_t ih;
const pixel_t *in_bitmap_data = load_bmp(argv[1], &ih);
if (in_bitmap_data == NULL) {
fprintf(stderr, "main: BMP image not loaded.\n");
return 1;
}
printf("Info: %d x %d x %d\n", ih.width, ih.height, ih.bitspp);
const pixel_t *out_bitmap_data =
canny_edge_detection(in_bitmap_data, &ih, 45, 50, 1.0f);
if (out_bitmap_data == NULL) {
fprintf(stderr, "main: failed canny_edge_detection.\n");
return 1;
}
if (save_bmp("out.bmp", &ih, out_bitmap_data)) {
fprintf(stderr, "main: BMP image not saved.\n");
return 1;
}
free((pixel_t*)in_bitmap_data);
free((pixel_t*)out_bitmap_data);
return 0;
} |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef struct cidr_tag {
uint32_t address;
unsigned int mask_length;
} cidr_t;
// Convert a string in CIDR format to an IPv4 address and netmask,
// if possible. Also performs CIDR canonicalization.
bool cidr_parse(const char* str, cidr_t* cidr) {
int a, b, c, d, m;
if (sscanf(str, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m) != 5)
return false;
if (m < 1 || m > 32
|| a < 0 || a > UINT8_MAX
|| b < 0 || b > UINT8_MAX
|| c < 0 || c > UINT8_MAX
|| d < 0 || d > UINT8_MAX)
return false;
uint32_t mask = ~((1 << (32 - m)) - 1);
uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;
address &= mask;
cidr->address = address;
cidr->mask_length = m;
return true;
}
// Write a string in CIDR notation into the supplied buffer.
void cidr_format(const cidr_t* cidr, char* str, size_t size) {
uint32_t address = cidr->address;
unsigned int d = address & UINT8_MAX;
address >>= 8;
unsigned int c = address & UINT8_MAX;
address >>= 8;
unsigned int b = address & UINT8_MAX;
address >>= 8;
unsigned int a = address & UINT8_MAX;
snprintf(str, size, "%u.%u.%u.%u/%u", a, b, c, d,
cidr->mask_length);
}
int main(int argc, char** argv) {
const char* tests[] = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
cidr_t cidr;
if (cidr_parse(tests[i], &cidr)) {
char out[32];
cidr_format(&cidr, out, sizeof(out));
printf("%-18s -> %s\n", tests[i], out);
} else {
fprintf(stderr, "%s: invalid CIDR\n", tests[i]);
}
}
return 0;
} |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Common_Lisp | Common Lisp | ;;A macro was used to ensure that the filter is inlined.
;;Larry Hignight. Last updated on 7/3/2012.
(defmacro kaprekar-number-filter (n &optional (base 10))
`(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))
(defun test (&key (start 1) (stop 10000) (base 10) (collect t))
(let ((count 0)
(nums))
(loop for i from start to stop do
(when (kaprekar-number-filter i base)
(if collect (push i nums))
(incf count)))
(format t "~d potential Kaprekar numbers remain (~~~$% filtered out).~%"
count (* (/ (- stop count) stop) 100))
(if collect (reverse nums)))) |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Julia | Julia | using Makie, Statistics
# Point3f0 is a 3-tuple of 32-bit floats for 3-dimensional space, and all Points are 3D.
Point = Point3f0
# a Face is defined by the points that are its vertices, in order.
Face = Vector{Point}
# an Edge is a line segment where the points are sorted
struct Edge
p1::Point
p2::Point
Edge(a, b) = new(min(a, b), max(a, b))
end
edgemidpoint(edge) = (edge.p1 + edge.p2) / 2.0
facesforpoint(p, faces) = [f for f in faces if p in f]
facesforedge(e, faces) = [f for f in faces if (e.p1 in f) && (e.p2 in f)]
nexttohole(edge, faces) = length(facesforedge(edge, faces)) < 2
function newedgepoint(edge, faces)
f = facesforedge(edge, faces)
p1, p2, len = edge.p1, edge.p2, length(f)
if len == 2
return (p1 + p2 + mean(f[1]) + mean(f[2])) / 4.0
elseif len == 1
return (p1 + p2 + mean(f[1])) / 3.0
end
return (p1 + p2) / 2.0
end
function edgesforface(face)
ret, indices = Vector{Edge}(), collect(1:length(face))
for i in 1:length(face)-1
push!(ret, Edge(face[indices[1]], face[indices[2]]))
indices .= circshift(indices, 1)
end
ret
end
function edgesforpoint(p, faces)
f = filter(x -> p in x, faces)
return filter(e -> p == e.p1 || p == e.p2, mapreduce(edgesforface, vcat, f))
end
function adjacentpoints(point, face)
a = indexin([point], face)
if a[1] != nothing
adjacent = (a[1] == 1) ? [face[end], face[2]] :
a[1] == length(face) ? [face[end-1], face[1]] :
[face[a[1] - 1], face[a[1] + 1]]
return sort(adjacent)
else
throw("point $point not in face $face")
end
end
adjacentedges(point, face) = [Edge(point, x) for x in adjacentpoints(point, face)]
facewrapped(face) = begin f = deepcopy(face); push!(f, f[1]); f end
drawface(face, colr) = lines(facewrapped(face); color=colr)
drawface!(face, colr) = lines!(facewrapped(face); color=colr)
drawfaces!(faces, colr) = for f in faces drawface!(f, colr) end
const colors = [:red, :green, :blue, :gold]
function drawfaces(faces, colr)
scene = drawface(faces[1], colr)
if length(faces) > 1
for f in faces[2:end]
drawface!(f, colr)
end
end
scene
end
function catmullclarkstep(faces)
d, E, dprime = Set(reduce(vcat, faces)), Dict{Vector, Point}(), Dict{Point, Point}()
for face in faces, (i, p) in enumerate(face)
edge = (p == face[end]) ? Edge(p, face[1]) : Edge(p, face[i + 1])
E[[edge, face]] = newedgepoint(edge, faces)
end
for p in d
F = mean([mean(face) for face in facesforpoint(p, faces)])
pe = edgesforpoint(p, faces)
R = mean(map(edgemidpoint, pe))
n = length(pe)
dprime[p] = (F + 2 * R + p * (n - 3)) / n
end
newfaces = Vector{Face}()
for face in faces
v = mean(face)
for point in face
fp1, fp2 = map(x -> E[[x, face]], adjacentedges(point, face))
push!(newfaces, [fp1, dprime[point], fp2, v])
end
end
return newfaces
end
"""
catmullclark(faces, iters, scene)
Perform a multistep Catmull-Clark subdivision of a surface. See Wikipedia or page 53
of http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/10_Subdivision.pdf
Plots the iterations, with colors for each iteration as set in the colors array.
Uses a Makie Scene of scene to plot the iters iterations.
"""
function catmullclark(faces, iters, scene)
nextfaces = deepcopy(faces)
for i in 1:iters
nextfaces = catmullclarkstep(nextfaces)
drawfaces!(nextfaces, colors[i])
display(scene)
sleep(1)
end
end
const inputpoints = [
[-1.0, -1.0, -1.0],
[-1.0, -1.0, 1.0],
[-1.0, 1.0, -1.0],
[-1.0, 1.0, 1.0],
[1.0, -1.0, -1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, -1.0],
[1.0, 1.0, 1.0]
]
const inputfaces = [
[0, 4, 5, 1],
[4, 6, 7, 5],
[6, 2, 3, 7],
[2, 0, 1, 3],
[1, 5, 7, 3],
[0, 2, 6, 4]
]
const faces = [map(x -> Point3f0(inputpoints[x]), p .+ 1) for p in inputfaces]
scene = drawfaces(faces, :black)
display(scene)
sleep(1)
catmullclark(faces, 4, scene)
println("Press Enter to continue", readline())
|
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | subSetQ[large_,small_] := MemberQ[large,small]
subSetQ[large_,small_List] := And@@(MemberQ[large,#]&/@small)
containing[groupList_,item_]:= Flatten[Position[groupList,group_/;subSetQ[group,item]]]
ReplaceFace[face_]:=Transpose[Prepend[Transpose[{#[[1]],face,#[[2]]}&/@Transpose[Partition[face,2,1,1]//{#,RotateRight[#]}&]],face]] |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #BASIC256 | BASIC256 |
for i = 3 to max_sieve step 2
isprime[i] = 1
next i
isprime[2] = 1
for i = 3 to sqr(max_sieve) step 2
if isprime[i] = 1 then
for j = i * i to max_sieve step i * 2
isprime[j] = 0
next j
end if
next i
subroutine carmichael3(p1)
if isprime[p1] <> 0 then
for h3 = 1 to p1 -1
t1 = (h3 + p1) * (p1 -1)
t2 = (-p1 * p1) % h3
if t2 < 0 then t2 = t2 + h3
for d = 1 to h3 + p1 -1
if t1 % d = 0 and t2 = (d % h3) then
p2 = 1 + (t1 \ d)
if isprime[p2] = 0 then continue for
p3 = 1 + (p1 * p2 \ h3)
if isprime[p3] = 0 or ((p2 * p3) % (p1 -1)) <> 1 then continue for
print p1; " * "; p2; " * "; p3
end if
next d
next h3
end if
end subroutine
for i = 2 to 61
call carmichael3(i)
next i
end
|
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #C | C |
#include <stdio.h>
/* C's % operator actually calculates the remainder of a / b so we need a
* small adjustment so it works as expected for negative values */
#define mod(n,m) ((((n) % (m)) + (m)) % (m))
int is_prime(unsigned int n)
{
if (n <= 3) {
return n > 1;
}
else if (!(n % 2) || !(n % 3)) {
return 0;
}
else {
unsigned int i;
for (i = 5; i*i <= n; i += 6)
if (!(n % i) || !(n % (i + 2)))
return 0;
return 1;
}
}
void carmichael3(int p1)
{
if (!is_prime(p1)) return;
int h3, d, p2, p3;
for (h3 = 1; h3 < p1; ++h3) {
for (d = 1; d < h3 + p1; ++d) {
if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {
p2 = 1 + ((p1 - 1) * (h3 + p1)/d);
if (!is_prime(p2)) continue;
p3 = 1 + (p1 * p2 / h3);
if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;
printf("%d %d %d\n", p1, p2, p3);
}
}
}
}
int main(void)
{
int p1;
for (p1 = 2; p1 < 62; ++p1)
carmichael3(p1);
return 0;
}
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Clojure | Clojure | ; Basic usage
> (reduce * '(1 2 3 4 5))
120
; Using an initial value
> (reduce + 100 '(1 2 3 4 5))
115
|
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Perl | Perl | sub init {
@left = split '', 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
@right = split '', 'PTLNBQDEOYSFAVZKGJRIHWXUMC';
}
sub encode {
my($letter) = @_;
my $index = index join('', @right), $letter;
my $enc = $left[$index];
left_permute($index);
right_permute($index);
$enc
}
sub decode {
my($letter) = @_;
my $index = index join('', @left), $letter;
my $dec = $right[$index];
left_permute($index);
right_permute($index);
$dec
}
sub right_permute {
my($index) = @_;
rotate(\@right, $index + 1);
rotate(\@right, 1, 2, 13);
}
sub left_permute {
my($index) = @_;
rotate(\@left, $index);
rotate(\@left, 1, 1, 13);
}
sub rotate {
our @list; local *list = shift;
my($n,$s,$e) = @_;
@list = $s ? @list[0..$s-1, $s+$n..$e+$n-1, $s..$s+$n-1, $e+1..$#list]
: @list[$n..$#list, 0..$n-1]
}
init; $e_msg .= encode($_) for split '', 'WELLDONEISBETTERTHANWELLSAID';
init; $d_msg .= decode($_) for split '', $e_msg;
print "$e_msg\n";
print "$d_msg\n"; |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #JavaScript | JavaScript | var n = 15;
for (var t = [0, 1], i = 1; i <= n; i++) {
for (var j = i; j > 1; j--) t[j] += t[j - 1];
t[i + 1] = t[i];
for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];
document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]);
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Go | Go | package dogs
import "fmt"
// Three variables, three different names.
// (It wouldn't compile if the compiler saw the variable names as the same.)
var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"
func PackageSees() map[*string]int {
// Print dogs visible from here.
fmt.Println("Package sees:", dog, Dog, DOG)
// Return addresses of the variables visible from here.
// The point of putting them in a map is that maps store only
// unique keys, so it will end up with three items only if
// the variables really represent different places in memory.
return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Groovy | Groovy | def dog = "Benjamin", Dog = "Samba", DOG = "Bernie"
println (dog == DOG ? "There is one dog named ${dog}" : "There are three dogs named ${dog}, ${Dog} and ${DOG}.") |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Crystal | Crystal | def cartesian_product(a, b)
return a.flat_map { |i| b.map { |j| [i, j] } }
end
def cartesian_product(l)
if l.size <= 1
return l
elsif l.size == 2
return cartesian_product(l[0], l[1])
end
return l[0].flat_map { |i|
cartesian_product(l[1..]).map { |j|
[i, j].flatten
}
}
end
tests = [ [[1, 2], [3, 4]],
[[3, 4], [1, 2]],
[[1, 2], [] of Int32],
[[] of Int32, [1, 2]],
[[1, 2, 3], [30], [500, 100]],
[[1, 2, 3], [] of Int32, [500, 100]],
[[1776, 1789], [7, 12], [4, 14, 23], [0, 1]] ]
tests.each { |test|
puts "#{test.join(" x ")} ->"
puts " #{cartesian_product(test)}"
puts ""
}
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Arturo | Arturo | catalan: function [n][
if? n=0 -> 1
else -> div (catalan n-1) * (4*n)-2 n+1
]
loop 0..15 [i][
print [
pad.right to :string i 5
pad.left to :string catalan i 20
]
] |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Action.21 | Action! | PROC FillRect(INT x,y,w,h)
INT i
FOR i=y TO y+h-1
DO
Plot(x,i)
DrawTo(x+w-1,i)
OD
RETURN
PROC DrawCantor(INT x0,y0,h,level)
INT x,y,i,j,w,w2,h2
w=1
FOR i=0 TO level-1
DO w==*3 OD
Color=1
y=y0
FOR i=0 TO level
DO
FillRect(x0,y,w,h)
y==+h*2
OD
Color=0
w2=1 h2=h*2
FOR i=0 TO level-1
DO
x=w2 y=(level-i)*(h*2)
WHILE x<w
DO
FillRect(x0+x,y0+y,w2,h2)
x==+w2*2
OD
w2==*3
h2==+h*2
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
COLOR1=$0C
COLOR2=$02
DrawCantor(38,48,8,5)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Ada | Ada | with Ada.Text_IO;
procedure Cantor_Set is
subtype Level_Range is Integer range 1 .. 5;
Image : array (Level_Range) of String (1 .. 81) := (others => (others => ' '));
procedure Cantor (Level : Natural; Length : Natural; Start : Natural) is
begin
if Level in Level_Range then
Image (Level) (Start .. Start + Length - 1) := (others => '*');
Cantor (Level + 1, Length / 3, Start);
Cantor (Level + 1, Length / 3, Start + 2 * Length / 3);
end if;
end Cantor;
begin
Cantor (Level => Level_Range'First,
Length => 81,
Start => 1);
for L in Level_Range loop
Ada.Text_IO.Put_Line (Image (L));
end loop;
end Cantor_Set; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.