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/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Elena | Elena | import system'text;
import system'routines;
import system'calendar;
import extensions;
import extensions'routines;
const MonthNames = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER",
"NOVEMBER","DECEMBER"};
const DayNames = new string[]{"MO", "TU", "WE", "TH", "FR", "SA", "SU"};
class CalendarMonthPrinter
{
Date theDate;
TextBuilder theLine;
int theMonth;
int theYear;
ref<int> theRow;
constructor(year, month)
{
theMonth := month;
theYear := year;
theLine := new TextBuilder();
theRow := 0;
}
writeTitle()
{
theRow.Value := 0;
theDate := Date.new(theYear, theMonth, 1);
DayNames.forEach:(name)
{ theLine.print(" ",name) }
}
writeLine()
{
theLine.clear();
if (theDate.Month == theMonth)
{
var dw := theDate.DayOfWeek;
theLine.writeCopies(" ",theDate.DayOfWeek == 0 ? 6 : (theDate.DayOfWeek - 1));
do
{
theLine.writePaddingLeft(theDate.Day.toPrintable(), $32, 3);
theDate := theDate.addDays:1
}
until(theDate.Month != theMonth || theDate.DayOfWeek == 1)
};
int length := theLine.Length;
if (length < 21)
{ theLine.writeCopies(" ", 21 - length) };
theRow.append(1)
}
indexer() = new Indexer
{
bool Available = theRow < 7;
int Index
{
get() = theRow.Value;
set(int index)
{
if (index <= theRow)
{ self.writeTitle() };
while (index > theRow)
{ self.writeLine() }
}
}
appendIndex(int index)
{
this self.Index := theRow.Value + index
}
get int Length() { ^ 7 }
get() = self;
set(o) { NotSupportedException.raise() }
};
printTitleTo(output)
{
output.writePadding(MonthNames[theMonth - 1], $32, 21)
}
printTo(output)
{
output.write(theLine.Value)
}
}
class Calendar
{
int theYear;
int theRowLength;
constructor new(int year)
{
theYear := year;
theRowLength := 3
}
printTo(output)
{
output.writePadding("[SNOOPY]", $32, theRowLength * 25);
output.writeLine();
output.writePadding(theYear.toPrintable(), $32, theRowLength * 25);
output.writeLine().writeLine();
var rowCount := 12 / theRowLength;
var months := Array.allocate(rowCount).populate:(i =>
Array.allocate(theRowLength)
.populate:(j =>
new CalendarMonthPrinter(theYear, i * theRowLength + j + 1)));
months.forEach:(row)
{
var r := row;
row.forEach:(month)
{
month.printTitleTo:output;
output.write:" "
};
output.writeLine();
ParallelEnumerator.new(row).forEach:(line)
{
line.forEach:(printer)
{
printer.printTo:output;
output.write:" "
};
output.writeLine()
}
}
}
}
public program()
{
var calender := Calendar.new(console.write:"ENTER THE YEAR:".readLine().toInt());
calender.printTo:console;
console.readChar()
} |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #JavaScript | JavaScript | #include <napi.h>
#include <openssl/md5.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace Napi;
Napi::Value md5sum(const Napi::CallbackInfo& info) {
std::string input = info[0].ToString();
unsigned char result[MD5_DIGEST_LENGTH];
MD5((unsigned char*)input.c_str(), input.size(), result);
std::stringstream md5string;
md5string << std::hex << std::setfill('0');
for (const auto& byte : result) md5string << std::setw(2) << (int)byte;
return String::New(info.Env(), md5string.str().c_str());
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "md5sum"),
Napi::Function::New(env, md5sum));
return exports;
}
NODE_API_MODULE(addon, Init) |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #BQN | BQN | {𝕊 ·: 1 + 1}0 |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Nim | Nim | import strutils
const
Width = 81
Height = 5
var lines: array[Height, string]
for line in lines.mitems: line = repeat('*', Width)
proc cantor(start, length, index: Natural) =
let seg = length div 3
if seg == 0: return
for i in index..<Height:
for j in (start + seg)..<(start + seg * 2):
lines[i][j] = ' '
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
cantor(0, Width, 1)
for line in lines:
echo line |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Objeck | Objeck | class CantorSet {
WIDTH : static : Int;
HEIGHT : static : Int;
lines : static : Char[,];
function : Init() ~ Nil {
WIDTH := 81;
HEIGHT := 5;
lines := Char->New[HEIGHT, WIDTH];
each(i : HEIGHT) {
each(j : WIDTH) {
lines[i,j] := '*';
};
};
}
function : Cantor(start : Int, len : Int, index : Int) ~ Nil {
seg : Int := len / 3;
if(seg = 0) {
return;
};
for(i := index; i < HEIGHT; i += 1;) {
for(j := start + seg; j < start + seg * 2; j += 1;) {
lines[i,j] := ' ';
};
};
Cantor(start, seg, index + 1);
Cantor(start + seg * 2, seg, index + 1);
}
function : Main(args : String[]) ~ Nil {
Init();
Cantor(0, WIDTH, 1);
each(i : HEIGHT) {
each(j : WIDTH) {
lines[i,j]->Print();
};
""->PrintLine();
};
}
} |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
[a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1]
Example
The fraction 9/4 has odd continued fraction representation 2; 3, 1, giving a binary representation of 100011,
which means 9/4 appears as the 35th term of the sequence.
Task part 2
Find the position of the number 83116/51639 in the Calkin-Wilf sequence.
See also
Wikipedia entry: Calkin-Wilf tree
Continued fraction
Continued fraction/Arithmetic/Construct from rational number
| #Wren | Wren | import "/rat" for Rat
import "/fmt" for Fmt, Conv
var calkinWilf = Fn.new { |n|
var cw = List.filled(n, null)
cw[0] = Rat.one
for (i in 1...n) {
var t = cw[i-1].floor * 2 - cw[i-1] + 1
cw[i] = Rat.one / t
}
return cw
}
var toContinued = Fn.new { |r|
var a = r.num
var b = r.den
var res = []
while (true) {
res.add((a/b).floor)
var t = a % b
a = b
b = t
if (a == 1) break
}
if (res.count%2 == 0) { // ensure always odd
res[-1] = res[-1] - 1
res.add(1)
}
return res
}
var getTermNumber = Fn.new { |cf|
var b = ""
var d = "1"
for (n in cf) {
b = (d * n) + b
d = (d == "1") ? "0" : "1"
}
return Conv.atoi(b, 2)
}
var cw = calkinWilf.call(20)
System.print("The first 20 terms of the Calkin-Wilf sequence are:")
Rat.showAsInt = true
for (i in 1..20) Fmt.print("$2d: $s", i, cw[i-1])
System.print()
var r = Rat.new(83116, 51639)
var cf = toContinued.call(r)
var tn = getTermNumber.call(cf)
Fmt.print("$s is the $,r term of the sequence.", r, tn) |
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
| #Wren | Wren | var castOut = Fn.new { |base, start, end|
var b = base - 1
var ran = (0...b).where { |n| n % b == (n * n) % b }
var x = (start/b).floor
var result = []
while (true) {
for (n in ran) {
var k = b*x + n
if (k >= start) {
if (k > end) return result
result.add(k)
}
}
x = x + 1
}
}
System.print(castOut.call(16, 1, 255))
System.print()
System.print(castOut.call(10, 1, 99))
System.print()
System.print(castOut.call(17, 1, 288)) |
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
| #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if self % i == 0 {
return false
}
}
return true
}
}
@inlinable
public func carmichael<T: BinaryInteger & SignedNumeric>(p1: T) -> [(T, T, T)] {
func mod(_ n: T, _ m: T) -> T { (n % m + m) % m }
var res = [(T, T, T)]()
guard p1.isPrime else {
return res
}
for h3 in stride(from: 2, to: p1, by: 1) {
for d in stride(from: 1, to: h3 + p1, by: 1) {
if (h3 + p1) * (p1 - 1) % d != 0 || mod(-p1 * p1, h3) != d % h3 {
continue
}
let p2 = 1 + (p1 - 1) * (h3 + p1) / d
guard p2.isPrime else {
continue
}
let p3 = 1 + p1 * p2 / h3
guard p3.isPrime && (p2 * p3) % (p1 - 1) == 1 else {
continue
}
res.append((p1, p2, p3))
}
}
return res
}
let res =
(1..<62)
.lazy
.filter({ $0.isPrime })
.map(carmichael)
.filter({ !$0.isEmpty })
.flatMap({ $0 })
for c in res {
print(c)
} |
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
| #Tcl | Tcl | proc carmichael {limit {rounds 10}} {
set carmichaels {}
for {set p1 2} {$p1 <= $limit} {incr p1} {
if {![miller_rabin $p1 $rounds]} continue
for {set h3 2} {$h3 < $p1} {incr h3} {
set g [expr {$h3 + $p1}]
for {set d 1} {$d < $h3+$p1} {incr d} {
if {(($h3+$p1)*($p1-1))%$d != 0} continue
if {(-($p1**2))%$h3 != $d%$h3} continue
set p2 [expr {1 + ($p1-1)*$g/$d}]
if {![miller_rabin $p2 $rounds]} continue
set p3 [expr {1 + $p1*$p2/$h3}]
if {![miller_rabin $p3 $rounds]} continue
if {($p2*$p3)%($p1-1) != 1} continue
lappend carmichaels $p1 $p2 $p3 [expr {$p1*$p2*$p3}]
}
}
}
return $carmichaels
} |
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
| #Oberon-2 | Oberon-2 |
MODULE Catamorphism;
IMPORT
Object,
NPCT:Tools,
NPCT:Args,
IntStr,
Out;
TYPE
BinaryFunc= PROCEDURE (x,y: LONGINT): LONGINT;
VAR
data: POINTER TO ARRAY OF LONGINT;
i: LONGINT;
PROCEDURE Sum(x,y: LONGINT): LONGINT;
BEGIN
RETURN x + y
END Sum;
PROCEDURE Sub(x,y: LONGINT): LONGINT;
BEGIN
RETURN x - y;
END Sub;
PROCEDURE Mul(x,y: LONGINT): LONGINT;
BEGIN
RETURN x * y;
END Mul;
PROCEDURE Reduce(x: ARRAY OF LONGINT; f: BinaryFunc): LONGINT;
VAR
i,res: LONGINT;
BEGIN
res := x[0];i := 1;
WHILE (i < LEN(x)) DO;
res := f(res,x[i]);
INC(i)
END;
RETURN res
END Reduce;
PROCEDURE InitData(VAR x: ARRAY OF LONGINT);
VAR
i, j: LONGINT;
res: IntStr.ConvResults;
aux: Object.CharsLatin1;
BEGIN
i := 0;j := 1;
WHILE (j <= LEN(x)) DO
aux := Tools.AsString(Args.Get(j));
IntStr.StrToInt(aux^,x[i],res);
IF res # IntStr.strAllRight THEN
Out.String("Incorrect format for data at index ");Out.LongInt(j,0);Out.Ln;
HALT(1);
END;
INC(j);INC(i)
END
END InitData;
BEGIN
IF Args.Number() = 1 THEN
Out.String("Invalid number of arguments. ");Out.Ln;
HALT(0)
ELSE
NEW(data,Args.Number() - 1);
InitData(data^);
Out.LongInt(Reduce(data^,Sum),0);Out.Ln;
Out.LongInt(Reduce(data^,Sub),0);Out.Ln;
Out.LongInt(Reduce(data^,Mul),0);Out.Ln
END
END Catamorphism.
|
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
| #Standard_ML | Standard ML | let
val dog = "Benjamin"
val Dog = "Samba"
val DOG = "Bernie"
in
print("The three dogs are named " ^ dog ^ ", " ^ Dog ^ ", and " ^ DOG ^ ".\n")
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
| #Stata | Stata | . local dog Benjamin
. local Dog Samba
. local DOG Bernie
. display "The three dogs are named $_dog, $_Dog, and $_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}
| #Prolog | Prolog |
product([A|_], Bs, [A, B]) :- member(B, Bs).
product([_|As], Bs, X) :- product(As, Bs, X).
|
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
| #Factor | Factor | USING: kernel math math.combinatorics prettyprint ;
: catalan ( n -- n ) [ 1 + recip ] [ 2 * ] [ nCk * ] tri ;
15 [ catalan . ] each-integer |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Scala | Scala | /* This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
class MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated.
var variable2 = "asdf" // Another instance variable; a public mutable this time
def this() = this(0) // An auxilliary constructor that instantiates with a default value
}
object HelloObject {
val s = "Hello" // Not private, so getter auto-generated
}
/** Demonstrate use of our example class.
*/
object Call_an_object_method extends App {
val s = "Hello"
val m = new MyClass
val n = new MyClass(3)
assert(HelloObject.s == "Hello") // "Hello" by object getterHelloObject
assert(m.memberVal == 0)
assert(n.memberVal == 3)
println("Successfully completed without error.")
} |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Rust | Rust | #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
// Small macro which wraps turning a string-literal into a c-string.
// This is always safe to call, and the resulting pointer has 'static lifetime
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
} |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Scala | Scala | import net.java.dev.sna.SNA
import com.sun.jna.ptr.IntByReference
object GetDiskFreeSpace extends App with SNA {
snaLibrary = "Kernel32" // Native library name
/*
* Important Note!
*
* The val holding the SNA-returned function must have the same name as the native function itself
* (see line following this comment). This is the only place you specify the native function name.
*/
val GetDiskFreeSpaceA = SNA[String, IntByReference, IntByReference, IntByReference, IntByReference, Boolean]
// This Windows function is described here:
// http://msdn.microsoft.com/en-us/library/aa364935(v=vs.85).aspx
val (disk, spc, bps, fc, tc) = ("C:\\",
new IntByReference, // Sectors per cluster
new IntByReference, // Bytes per sector
new IntByReference, // Free clusters
new IntByReference) // Total clusters
val ok = GetDiskFreeSpaceA(disk, spc, bps, fc, tc) // status
println(f"'$disk%s' ($ok%s): sectors/cluster: ${spc.getValue}%d, bytes/sector: ${bps.getValue}%d, " +
f" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n")
}} |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #J | J | oprimes=: {{ NB. all primes of order y
p:(+i.)/-/\ p:inv +/\1 9*10^y
}}
obrill=: {{ NB. all brilliant numbers of order y primes
~.,*/~oprimes y
}}
brillseq=: {{ NB. sequences of brilliant numbers up through order y-1 primes
/:~;obrill each i.y
}} |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Java | Java | import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Ada | Ada | with Ada.Calendar.Formatting;
package Printable_Calendar is
subtype String20 is String(1 .. 20);
type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20;
type Description is record
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
-- for internationalization, you only need to define a new description
Default_Description: constant Description :=
(Weekday_Rep =>
"Mo Tu We Th Fr Sa So",
Month_Rep =>
(" January ", " February ", " March ",
" April ", " May ", " June ",
" July ", " August ", " September ",
" October ", " November ", " December "));
type Calendar (<>) is tagged private;
-- Initialize a calendar for devices with 80- or 132-characters per row
function Init_80(Des: Description := Default_Description) return Calendar;
function Init_132(Des: Description := Default_Description) return Calendar;
-- the following procedures output to standard IO; override if neccessary
procedure New_Line(Cal: Calendar);
procedure Put_String(Cal: Calendar; S: String);
-- the following procedures do the real stuff
procedure Print_Line_Centered(Cal: Calendar'Class; Line: String);
procedure Print(Cal: Calendar'Class;
Year: Ada.Calendar.Year_Number;
Year_String: String); -- this is the main Thing
private
type Calendar is tagged record
Columns, Rows, Space_Between_Columns: Positive;
Left_Space: Natural;
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
end Printable_Calendar; |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Ada | Ada | package OO_Privacy is
type Confidential_Stuff is tagged private;
subtype Password_Type is String(1 .. 8);
private
type Confidential_Stuff is tagged record
Password: Password_Type := "default!"; -- the "secret"
end record;
end OO_Privacy; |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #C.23 | C# | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Action.21 | Action! | BYTE FUNC CheckNeighbors(CARD x BYTE y)
IF Locate(x-1,y-1)=1 THEN RETURN (1) FI
IF Locate(x,y-1)=1 THEN RETURN (1) FI
IF Locate(x+1,y-1)=1 THEN RETURN (1) FI
IF Locate(x-1,y)=1 THEN RETURN (1) FI
IF Locate(x+1,y)=1 THEN RETURN (1) FI
IF Locate(x-1,y+1)=1 THEN RETURN (1) FI
IF Locate(x,y+1)=1 THEN RETURN (1) FI
IF Locate(x+1,y+1)=1 THEN RETURN (1) FI
RETURN (0)
PROC DrawTree()
DEFINE MAXW="255"
DEFINE MINX="1"
DEFINE MAXX="318"
DEFINE MINY="1"
DEFINE MAXY="190"
BYTE CH=$02FC
CARD x,l,r
BYTE y,t,b,w,h,dx,dy,m=[20]
x=160 y=96
Plot(x,y)
l=x-m r=x+m
t=y-m b=y+m
w=r-l+1 h=b-t+1
DO
DO
x=Rand(w)+l y=Rand(h)+t
UNTIL Locate(x,y)=0
OD
WHILE CheckNeighbors(x,y)=0
DO
DO
dx=Rand(3) dy=Rand(3)
UNTIL dx#2 OR dy#2
OD
IF dx=0 THEN
IF x>l THEN x==-1
ELSE x=r-1
FI
ELSEIF dx=1 THEN
IF x<r THEN x==+1
ELSE x=l+1
FI
FI
IF dy=0 THEN
IF y>t THEN y==-1
ELSE y=b-1
FI
ELSEIF dy=1 THEN
IF y<b THEN y==+1
ELSE y=t+1
FI
FI
OD
Plot(x,y)
IF l>MINX AND l+m>x AND w<MAXW THEN
l==-1 w==+1
FI
IF r<MAXX AND r-m<x AND w<MAXW THEN
r==+1 w==+1
FI
IF t>MINY AND t+m>y THEN
t==-1 h==+1
FI
IF b<MAXY AND b-m<y THEN
b==+1 h==+1
FI
Poke(77,0) ;turn off the attract mode
UNTIL CH#$FF ;until key pressed
OD
CH=$FF
RETURN
PROC Main()
BYTE COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$0E
COLOR2=$02
DrawTree()
RETURN |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #ALGOL_68 | ALGOL 68 | STRING digits = "123456789";
[4]CHAR chosen;
STRING available := digits;
FOR i TO UPB chosen DO
INT c = ENTIER(random*UPB available)+1;
chosen[i] := available[c];
available := available[:c-1]+available[c+1:]
OD;
COMMENT print((chosen, new line)); # Debug # END COMMENT
OP D = (INT d)STRING: whole(d,0); # for formatting an integer #
print (("I have chosen a number from ",D UPB chosen," unique digits from 1 to 9 arranged in a random order.", new line,
"You need to input a ",D UPB chosen," digit, unique digit number as a guess at what I have chosen", new line));
PRIO WITHIN = 5, NOTWITHIN = 5;
OP WITHIN = (CHAR c, []CHAR s)BOOL: char in string(c,LOC INT,s);
OP NOTWITHIN = (CHAR c, []CHAR s)BOOL: NOT ( c WITHIN s );
INT guesses := 0, bulls, cows;
WHILE
STRING guess;
guesses +:= 1;
WHILE
# get a good guess #
print((new line,"Next guess [",D guesses,"]: "));
read((guess, new line));
IF UPB guess NE UPB chosen THEN
FALSE
ELSE
BOOL ok;
FOR i TO UPB guess WHILE
ok := guess[i] WITHIN digits AND guess[i] NOTWITHIN guess[i+1:]
DO SKIP OD;
NOT ok
FI
DO
print(("Problem, try again. You need to enter ",D UPB chosen," unique digits from 1 to 9", new line))
OD;
# WHILE #
guess NE chosen
DO
bulls := cows := 0;
FOR i TO UPB chosen DO
IF guess[i] = chosen[i] THEN
bulls +:= 1
ELIF guess[i] WITHIN chosen THEN
cows +:= 1
FI
OD;
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line)) |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #J | J | NB. transform and inverse
bwt=: {:"1@:(/:~ :[:)@:(|."0 1~ -@:i.@:#)@:((2{a.) , ,&(3{a.))@:(([ ('STX or ETX invalid in input' (13!:8) 21 + 0:))^:(1 e. (2 3{a.)&e.)) :.(}.@:}:@:({~ ((3{a.) [: :i.~ {:"1))@:((,"0 1 /:~ :[:)^:(#@[)&(0$00)))
NB. demonstrate the transform
A=: <@bwt ;._2 ] 0 :0
tests[0] = "banana";
tests[1] = "appellee";
tests[2] = "dogwood";
tests[3] = "TO BE OR NOT TO BE OR WANT TO BE OR NOT?";
tests[4] = "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
)
�;� =] a [" s0nnb"taate s
�;� =] e [" s1"elptlepate s
�;� =] d [" s2o"toodwte sg
�;� =]OOORREEETTR ? [" TW BBB ATTT NNOOONOO" s3tte s
�,� =] S "TEXYDST[ .E.IXXIIXXSSMPPS.B..EE.".USFXDIIOIIITs4tte s
NB. and the restoring transformation
bwt inv&> A
tests[0] = "banana";
tests[1] = "appellee";
tests[2] = "dogwood";
tests[3] = "TO BE OR NOT TO BE OR WANT TO BE OR NOT?";
tests[4] = "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
NB. the final test pattern
bwt a. {~ 2 , (a. i. 'ABC') , 3
|STX or ETX invalid in input: bwt
| bwt a.{~2,(a.i.'ABC'),3
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String cannot contain STX or ETX");
}
String ss = STX + s + ETX;
List<String> table = new ArrayList<>();
for (int i = 0; i < ss.length(); i++) {
String before = ss.substring(i);
String after = ss.substring(0, i);
table.add(before + after);
}
table.sort(String::compareTo);
StringBuilder sb = new StringBuilder();
for (String str : table) {
sb.append(str.charAt(str.length() - 1));
}
return sb.toString();
}
private static String ibwt(String r) {
int len = r.length();
List<String> table = new ArrayList<>();
for (int i = 0; i < len; ++i) {
table.add("");
}
for (int j = 0; j < len; ++j) {
for (int i = 0; i < len; ++i) {
table.set(i, r.charAt(i) + table.get(i));
}
table.sort(String::compareTo);
}
for (String row : table) {
if (row.endsWith(ETX)) {
return row.substring(1, len - 1);
}
}
return "";
}
private static String makePrintable(String s) {
// substitute ^ for STX and | for ETX to print results
return s.replace(STX, "^").replace(ETX, "|");
}
public static void main(String[] args) {
List<String> tests = List.of(
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
);
for (String test : tests) {
System.out.println(makePrintable(test));
System.out.print(" --> ");
String t = "";
try {
t = bwt(test);
System.out.println(makePrintable(t));
} catch (IllegalArgumentException e) {
System.out.println("ERROR: " + e.getMessage());
}
String r = ibwt(t);
System.out.printf(" --> %s\n\n", r);
}
}
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #AppleScript | AppleScript | (* Only non-accented English letters are altered here. *)
on caesarDecipher(txt, |key|)
return caesarEncipher(txt, -|key|)
end caesarDecipher
on caesarEncipher(txt, |key|)
set codePoints to id of txt
set keyPlus25 to |key| mod 26 + 25
repeat with thisCode in codePoints
tell thisCode mod 32
if ((it < 27) and (it > 0) and (thisCode div 64 is 1)) then ¬
set thisCode's contents to thisCode - it + (it + keyPlus25) mod 26 + 1
end tell
end repeat
return string id codePoints
end caesarEncipher
-- Test code:
set txt to "ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."
set |key| to 9
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Delphi | Delphi |
program Calculating_the_value_of_e;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
EPSILON = 1.0e-15;
function fAbs(value: Extended): Extended;
begin
Result := value;
if value < 0 then
Result := -Result;
end;
function e: Extended;
var
fact: UInt64;
e, e0: Extended;
n: Integer;
begin
fact := 1;
Result := 2.0;
n := 2;
repeat
e0 := Result;
fact := fact * n;
inc(n);
Result := Result + (1.0 / fact);
until (fAbs(Result - e0) < EPSILON);
end;
begin
writeln(format('e = %.15f', [e]));
readln;
end.
|
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #D | D | void main() {
import std.stdio, std.random, std.algorithm, std.range, std.ascii;
immutable d9 = "123456789";
auto choices = cartesianProduct(d9, d9, d9, d9).map!(t => [t[]])
.filter!(a => a.sort().uniq.count == 4).array;
do {
const ans = choices[uniform(0, $)];
writef("My guess is %s. How many bulls and cows? ", ans);
immutable score = readln.filter!isDigit.map!q{ a - '0' }.array;
choices = choices.remove!(c => score !=
[c.zip(ans).count!(p => p[0] == p[1]),
c.zip(ans).count!(p => p[0] != p[1] && ans.canFind(p[0]))]);
} while (choices.length > 1);
if (choices.empty)
return "Nothing fits the scores you gave.".writeln;
writeln("Solution found: ", choices[0]);
} |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Fortran | Fortran |
MODULE DATEGNASH
TYPE DATEBAG
INTEGER DAY,MONTH,YEAR
END TYPE DATEBAG
CHARACTER*9 MONTHNAME(12),DAYNAME(0:6)
PARAMETER (MONTHNAME = (/"JANUARY","FEBRUARY","MARCH","APRIL",
1 "MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER",
2 "DECEMBER"/))
PARAMETER (DAYNAME = (/"SUNDAY","MONDAY","TUESDAY","WEDNESDAY",
1 "THURSDAY","FRIDAY","SATURDAY"/))
INTEGER*4 JDAYSHIFT
PARAMETER (JDAYSHIFT = 2415020)
CONTAINS
INTEGER FUNCTION LSTNB(TEXT)
CHARACTER*(*),INTENT(IN):: TEXT
INTEGER L
L = LEN(TEXT)
1 IF (L.LE.0) GO TO 2
IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2
L = L - 1
GO TO 1
2 LSTNB = L
RETURN
END FUNCTION LSTNB
CHARACTER*2 FUNCTION I2FMT(N)
INTEGER*4 N
IF (N.LT.0) THEN
IF (N.LT.-9) THEN
I2FMT = "-!"
ELSE
I2FMT = "-"//CHAR(ICHAR("0") - N)
END IF
ELSE IF (N.LT.10) THEN
I2FMT = " " //CHAR(ICHAR("0") + N)
ELSE IF (N.LT.100) THEN
I2FMT = CHAR(N/10 + ICHAR("0"))
1 //CHAR(MOD(N,10) + ICHAR("0"))
ELSE
I2FMT = "+!"
END IF
END FUNCTION I2FMT
CHARACTER*8 FUNCTION I8FMT(N)
INTEGER*4 N
CHARACTER*8 HIC
WRITE (HIC,1) N
1 FORMAT (I8)
I8FMT = HIC
END FUNCTION I8FMT
SUBROUTINE SAY(OUT,TEXT)
INTEGER OUT
CHARACTER*(*) TEXT
WRITE (6,1) TEXT(1:LSTNB(TEXT))
1 FORMAT (A)
END SUBROUTINE SAY
INTEGER*4 FUNCTION DAYNUM(YY,M,D)
INTEGER*4 JDAYN
INTEGER YY,Y,M,MM,D
Y = YY
IF (Y.LT.1) Y = Y + 1
MM = (M - 14)/12
JDAYN = D - 32075
A + 1461*(Y + 4800 + MM)/4
B + 367*(M - 2 - MM*12)/12
C - 3*((Y + 4900 + MM)/100)/4
DAYNUM = JDAYN - JDAYSHIFT
END FUNCTION DAYNUM
TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM)
INTEGER*4 DAYNUM,JDAYN
INTEGER Y,M,D,L,N
JDAYN = DAYNUM + JDAYSHIFT
L = JDAYN + 68569
N = 4*L/146097
L = L - (146097*N + 3)/4
Y = 4000*(L + 1)/1461001
L = L - 1461*Y/4 + 31
M = 80*L/2447
D = L - 2447*M/80
L = M/11
M = M + 2 - 12*L
Y = 100*(N - 49) + Y + L
IF (Y.LT.1) Y = Y - 1
MUNYAD%YEAR = Y
MUNYAD%MONTH = M
MUNYAD%DAY = D
END FUNCTION MUNYAD
INTEGER FUNCTION PMOD(N,M)
INTEGER N,M
PMOD = MOD(MOD(N,M) + M,M)
END FUNCTION PMOD
SUBROUTINE CALENDAR(Y1,Y2,COLUMNS)
INTEGER Y1,Y2,YEAR
INTEGER M,M1,M2,MONTH
INTEGER*4 DN1,DN2,DN,D
INTEGER W,G
INTEGER L,LINE
INTEGER COL,COLUMNS,COLWIDTH
CHARACTER*200 STRIPE(6),SPECIAL(6),MLINE,DLINE
W = 3
G = 1
COLWIDTH = 7*W + G
Y:DO YEAR = Y1,Y2
CALL SAY(MSG,"")
IF (YEAR.EQ.0) THEN
CALL SAY(MSG,"THERE IS NO YEAR ZERO.")
CYCLE Y
END IF
MLINE = ""
L = (COLUMNS*COLWIDTH - G - 8)/2
IF (YEAR.GT.0) THEN
MLINE(L:) = I8FMT(YEAR)
ELSE
MLINE(L - 1:) = I8FMT(-YEAR)//"BC"
END IF
CALL SAY(MSG,MLINE)
DO MONTH = 1,12,COLUMNS
M1 = MONTH
M2 = MIN(12,M1 + COLUMNS - 1)
MLINE = ""
DLINE = ""
STRIPE = ""
SPECIAL = ""
L0 = 1
DO M = M1,M2
L = (COLWIDTH - G - LSTNB(MONTHNAME(M)))/2 - 1
MLINE(L0 + L:) = MONTHNAME(M)
DO D = 0,6
L = L0 + (3 - W) + D*W
DLINE(L:L + 2) = DAYNAME(D)(1:W - 1)
END DO
DN1 = DAYNUM(YEAR,M,1)
DN2 = DAYNUM(YEAR,M + 1,0)
COL = MOD(PMOD(DN1,7) + 7,7)
LINE = 1
D = 1
DO DN = DN1,DN2
L = L0 + COL*W
STRIPE(LINE)(L:L + 1) = I2FMT(D)
D = D + 1
COL = COL + 1
IF (COL.GT.6) THEN
LINE = LINE + 1
COL = 0
END IF
END DO
L0 = L0 + 7*W + G
END DO
CALL SAY(MSG,MLINE)
CALL SAY(MSG,DLINE)
DO LINE = 1,6
IF (STRIPE(LINE).NE."") THEN
CALL SAY(MSG,STRIPE(LINE))
END IF
END DO
END DO
END DO Y
CALL SAY(MSG,"")
END SUBROUTINE CALENDAR
END MODULE DATEGNASH
PROGRAM SHOW1968
USE DATEGNASH
INTEGER NCOL
DO NCOL = 1,6
CALL CALENDAR(1969,1969,NCOL)
END DO
END
|
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Julia | Julia | p = ccall(:strdup, Ptr{Cuchar}, (Ptr{Cuchar},), "Hello world")
@show unsafe_string(p) # "Hello world"
ccall(:free, Void, (Ptr{Cuchar},), p) |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Kotlin | Kotlin | // Kotlin Native v0.2
import kotlinx.cinterop.*
import string.*
fun main(args: Array<String>) {
val hw = strdup ("Hello World!")!!.toKString()
println(hw)
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Bracmat | Bracmat | aFunctionWithoutArguments$ |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Perl | Perl | use strict;
use feature 'say';
sub cantor {
our($height) = @_;
my $width = 3 ** ($height - 1);
our @lines = ('#' x $width) x $height;
sub trim_middle_third {
my($len, $start, $index) = @_;
my $seg = int $len / 3
or return;
for my $i ( $index .. $height - 1 ) {
for my $j ( 0 .. $seg - 1 ) {
substr $lines[$i], $start + $seg + $j, 1, ' ';
}
}
trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;
}
trim_middle_third( $width, 0, 1 );
@lines;
}
say for cantor(5); |
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
| #zkl | zkl | fcn castOut(base=10, start=1, end=999999){
base-=1;
ran:=(0).filter(base,'wrap(n){ n%base == (n*n)%base });
result:=Sink(List);
foreach a,b in ([start/base ..],ran){ // foreach{ foreach {} }
k := base*a + b;
if (k < start) continue;
if (k > end) return(result.close());
result.write(k);
}
// doesn't get here
} |
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET Base=10
20 LET N=2
30 LET c1=0
40 LET c2=0
50 LET k=1
60 IF k>=(Base^N)-1 THEN GO TO 150
70 LET c1=c1+1
80 IF FN m(k,Base-1)=FN m(k*k,Base-1) THEN LET c2=c2+1: PRINT k;" ";
90 LET k=k+1
100 GO TO 60
150 PRINT '"Trying ";c2;" numbers instead of ";c1;" numbers saves ";100-(c2/c1)*100;"%"
160 STOP
170 DEF FN m(a,b)=a-INT (a/b)*b
|
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
| #Vala | Vala | long mod(long n, long m) {
return ((n % m) + m) % m;
}
bool is_prime(long n) {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (long div = 5, inc = 2; div * div <= n;
div += inc, inc = 6 - inc)
if (n % div == 0)
return false;
return true;
}
void main() {
for (long p = 2; p <= 63; p++) {
if (!is_prime(p)) continue;
for (long h3 = 2; h3 <= p; h3++) {
var g = h3 + p;
for (long d = 1; d <= g; d++) {
if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)
continue;
var q = 1 + (p - 1) * g / d;
if (!is_prime(q)) continue;
var r = 1 + (p * q / h3);
if (!is_prime(r) || (q * r) % (p - 1) != 1) continue;
stdout.printf("%5ld × %5ld × %5ld = %10ld\n", p, q, r, p * q * 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
| #Objeck | Objeck |
use Collection;
class Reducer {
function : Main(args : String[]) ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
values->Reduce(Add(Int, Int) ~ Int)->PrintLine();
values->Reduce(Mul(Int, Int) ~ Int)->PrintLine();
}
function : Add(a : Int, b : Int) ~ Int {
return a + b;
}
function : Mul(a : Int, b : Int) ~ Int {
return a * b;
}
} |
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
| #Swift | Swift | let dog = "Benjamin"
let Dog = "Samba"
let DOG = "Bernie"
println("The three dogs are 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
| #Tcl | Tcl | set dog "Benjamin"
set Dog "Samba"
set DOG "Bernie"
puts "The three dogs are 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
| #True_BASIC | True BASIC | LET dog$ = "Benjamin"
LET Dog$ = "Samba"
LET DOG$ = "Bernie"
PRINT "There is just one dog, named "; dog$
END |
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}
| #Python | Python | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[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))]:
print(lists, '=>')
pp(cp(lists), indent=2)
|
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
| #Fantom | Fantom | class Main
{
static Int factorial (Int n)
{
Int res := 1
if (n>1)
(2..n).each |i| { res *= i }
return res
}
static Int catalanA (Int n)
{
return factorial(2*n)/(factorial(n+1) * factorial(n))
}
static Int catalanB (Int n)
{
if (n == 0)
{
return 1
}
else
{
sum := 0
n.times |i| { sum += catalanB(i) * catalanB(n-1-i) }
return sum
}
}
static Int catalanC (Int n)
{
if (n == 0)
{
return 1
}
else
{
return catalanC(n-1)*2*(2*n-1)/(n+1)
}
}
public static Void main ()
{
(1..15).each |n|
{
echo (n.toStr.padl(4) +
catalanA(n).toStr.padl(10) +
catalanB(n).toStr.padl(10) +
catalanC(n).toStr.padl(10))
}
}
} |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Sidef | Sidef | class MyClass {
method foo(arg) { say arg }
}
var arg = 42;
# Call a class method
MyClass.foo(arg);
# Alternatively, using an expression for the method name
MyClass.(:foo)(arg);
# Create an instance
var instance = MyClass();
# Instance method
instance.foo(arg);
# Alternatively, by using an expression for the method name
instance.(:foo)(arg);
# Alternatively, by asking for a method
instance.method(:foo)(arg); |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Smalltalk | Smalltalk | " Class "
MyClass selector: someArgument .
" or equivalently "
foo := MyClass .
foo selector: someArgument.
" Instance "
myInstance selector: someArgument.
" Message with multiple arguments "
myInstance fooWithRed:arg1 green:arg2 blue:arg3 .
" Message with no arguments "
myInstance selector.
" Binary (operator) message"
myInstance + argument . |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #SuperCollider | SuperCollider |
SomeClass {
*someClassMethod {
}
someInstanceMethod {
}
}
SomeClass.someClassMethod;
a = SomeClass.new;
a.someInstanceMethod;
|
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Smalltalk | Smalltalk | DLD addLibrary: 'fakeimglib'.
Object subclass: ExtLib [
ExtLib class >> openimage: aString [
(CFunctionDescriptor isFunction: 'openimage')
ifTrue: [
(CFunctionDescriptor for: 'openimage'
returning: #int
withArgs: #( #string ) ) callInto: (ValueHolder null).
] ifFalse: [ ('internal open image %1' % { aString }) displayNl ]
]
].
ExtLib openimage: 'test.png'. |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #SNOBOL4 | SNOBOL4 | -INCLUDE 'ffi.sno'
ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
ffi_m_hypot = FFI_DLSYM(ffi_m, 'hypot')
DEFINE_FFI('hypot(double,double)double', ffi_m_hypot)
OUTPUT = hypot(1,2)
OUTPUT = hypot(2,3)
OUTPUT = hypot(3,4)
OUTPUT = hypot(4,5)
END |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Julia | Julia |
using Primes
function isbrilliant(n)
p = factor(n).pe
return (length(p) == 1 && p[1][2] == 2) ||
length(p) == 2 && ndigits(p[1][1]) == ndigits(p[2][1]) && p[1][2] == p[2][2] == 1
end
function testbrilliants()
println("First 100 brilliant numbers:")
foreach(p -> print(lpad(p[2], 5), p[1] % 20 == 0 ? "\n" : ""),
enumerate(filter(isbrilliant, 1:1370)))
bcount, results, positions = 0, zeros(Int, 9), zeros(Int, 9)
for n in 1:10^10
if isbrilliant(n)
bcount += 1
for i in 1:9
if n >= 10^i && results[i] == 0
results[i] = n
positions[i] = bcount
println("First >=", lpad(10^i, 12), " is", lpad(bcount, 8),
" in the series: $n")
end
end
end
end
return results, positions
end
testbrilliants()
|
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[PrimesDecade]
PrimesDecade[n_Integer] := Module[{bounds},
bounds = {PrimePi[10^n] + 1, PrimePi[10^(n + 1) - 1]};
Prime[Range @@ bounds]
]
ds = Union @@ Table[Union[Times @@@ Tuples[PrimesDecade[d], 2]], {d, 0, 4}];
Multicolumn[Take[ds, 100], {Automatic, 8}, Appearance -> "Horizontal"]
sel = Min /@ GatherBy[Select[ds, GreaterEqualThan[10]], IntegerLength];
Grid[{#, FirstPosition[ds, #][[1]]} & /@ sel] |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::AllUtils <max head firstidx uniqint>;
use ntheory <primes is_semiprime forsetproduct>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
my(@B,@Br);
for my $oom (1..5) {
my @P = grep { $oom == length } @{primes(10**$oom)};
forsetproduct { is_semiprime($_[0] * $_[1]) and push @B, $_[0] * $_[1] } \@P, \@P;
@Br = uniqint sort { $a <=> $b } @Br, @B;
}
say "First 100 brilliant numbers:\n" . table 10, head 100, @Br;
for my $oom (1..9) {
my $key = firstidx { $_ > 10**$oom } @Br;
printf "First >= %13s is position %9s in the series: %13s\n", comma(10**$oom), comma($key), comma $Br[$key];
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC print calendar = (INT year, page width)VOID: (
[]STRING month names = (
"January","February","March","April","May","June",
"July","August","September","October","November","December"),
weekday names = ("Su","Mo","Tu","We","Th","Fr","Sa");
FORMAT weekday fmt = $g,n(UPB weekday names - LWB weekday names)(" "g)$;
# Juggle the calendar format to fit the printer/screen width #
INT day width = UPB weekday names[1], day gap=1;
INT month width = (day width+day gap) * UPB weekday names-1;
INT month heading lines = 2;
INT month lines = (31 OVER UPB weekday names+month heading lines+2); # +2 for head/tail weeks #
INT year cols = (page width+1) OVER (month width+1);
INT year rows = (UPB month names-1)OVER year cols + 1;
INT month gap = (page width - year cols*month width + 1)OVER year cols;
INT year width = year cols*(month width+month gap)-month gap;
INT year lines = year rows*month lines;
MODE MONTHBOX = [month lines, month width]CHAR;
MODE YEARBOX = [year lines, year width]CHAR;
INT week start = 1; # Sunday #
PROC days in month = (INT year, month)INT:
CASE month IN 31,
IF year MOD 4 EQ 0 AND year MOD 100 NE 0 OR year MOD 400 EQ 0 THEN 29 ELSE 28 FI,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
ESAC;
PROC day of week = (INT year, month, day)INT: (
# Day of the week by Zeller’s Congruence algorithm from 1887 #
INT y := year, m := month, d := day, c;
IF m <= 2 THEN m +:= 12; y -:= 1 FI;
c := y OVER 100;
y %*:= 100;
(d - 1 + ((m + 1) * 26) OVER 10 + y + y OVER 4 + c OVER 4 - 2 * c) MOD 7
);
MODE SIMPLEOUT = UNION(STRING, []STRING, INT);
PROC cputf = (REF[]CHAR out, FORMAT fmt, SIMPLEOUT argv)VOID:(
FILE f; STRING s; associate(f,s);
putf(f, (fmt, argv));
out[:UPB s]:=s;
close(f)
);
PROC month repr = (INT year, month)MONTHBOX:(
MONTHBOX month box; FOR line TO UPB month box DO month box[line,]:=" "* 2 UPB month box OD;
STRING month name = month names[month];
# center the title #
cputf(month box[1,(month width - UPB month name ) OVER 2+1:], $g$, month name);
cputf(month box[2,], weekday fmt, weekday names);
INT first day := day of week(year, month, 1);
FOR day TO days in month(year, month) DO
INT line = (day+first day-week start) OVER UPB weekday names + month heading lines + 1;
INT char =((day+first day-week start) MOD UPB weekday names)*(day width+day gap) + 1;
cputf(month box[line,char:char+day width-1],$g(-day width)$, day)
OD;
month box
);
PROC year repr = (INT year)YEARBOX:(
YEARBOX year box;
FOR line TO UPB year box DO year box[line,]:=" "* 2 UPB year box OD;
FOR month row FROM 0 TO year rows-1 DO
FOR month col FROM 0 TO year cols-1 DO
INT month = month row * year cols + month col + 1;
IF month > UPB month names THEN
done
ELSE
INT month col width = month width+month gap;
year box[
month row*month lines+1 : (month row+1)*month lines,
month col*month col width+1 : (month col+1)*month col width-month gap
] := month repr(year, month)
FI
OD
OD;
done: year box
);
INT center = (year cols*(month width+month gap) - month gap - 1) OVER 2;
INT indent = (page width - year width) OVER 2;
printf((
$n(indent + center - 9)k g l$, "[Insert Snoopy here]",
$n(indent + center - 1)k 4d l$, year, $l$,
$n(indent)k n(year width)(g) l$, year repr(year)
))
);
main: (
CO inspired by http://www.ee.ryerson.ca/~elf/hack/realmen.html
Real Programmers Don't Use PASCAL - Ed Post
Datamation, volume 29 number 7, July 1983
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
CO
INT mankind stepped on the moon = 1969,
line printer width = 80; # as at 1969! #
print calendar(mankind stepped on the moon, line printer width)
) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #C.2B.2B | C++ | #include <iostream>
class CWidget; // Forward-declare that we have a class named CWidget.
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget(); // Disallow the default constructor.
CWidget(const CWidget&); // Disallow the copy constructor
CWidget& operator=(const CWidget&); // Disallow the assignment operator.
public:
CWidget(CFactory& parent);
~CWidget();
};
// CFactory constructors and destructors. Very simple things.
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
// CFactory method which creates CWidgets.
CWidget* CFactory::GetWidget()
{
// Create a new CWidget, tell it we're its parent.
return new CWidget(*this);
}
// CWidget constructor
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
} |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Clojure | Clojure |
(ns a)
(def ^:private priv :secret)
; From REPL, in another namespace 'user':
user=> @a/priv ; fails with: IllegalStateException: var: a/priv is not public
user=> @#'a/priv ; succeeds
:secret
|
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Ada | Ada | with Ada.Numerics.Discrete_Random;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Brownian_Tree is
Width : constant := 800;
Height : constant := 600;
Points : constant := 50_000;
subtype Width_Range is Integer range 1 .. Width;
subtype Height_Range is Integer range 1 .. Height;
type Direction is (N, NE, E, SE, S, SW, W, NW);
package Random_Width is new Ada.Numerics.Discrete_Random (Width_Range);
package Random_Height is new Ada.Numerics.Discrete_Random (Height_Range);
package Random_Direc is new Ada.Numerics.Discrete_Random (Direction);
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
Width_Gen : Random_Width.Generator;
Height_Gen : Random_Height.Generator;
Direc_Gen : Random_Direc.Generator;
function Poll_Quit return Boolean is
use type SDL.Events.Event_Types;
begin
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return True;
end if;
end loop;
return False;
end Poll_Quit;
procedure Draw_Brownian_Tree is
Field : array (Width_Range, Height_Range) of Boolean := (others => (others => False));
X : Width_Range;
Y : Height_Range;
Direc : Direction;
procedure Random_Free (X : out Width_Range; Y : out Height_Range) is
begin
-- Find free random spot
loop
X := Random_Width.Random (Width_Gen);
Y := Random_Height.Random (Height_Gen);
exit when Field (X, Y) = False;
end loop;
end Random_Free;
begin
-- Seed
Field (Random_Width.Random (Width_Gen),
Random_Height.Random (Height_Gen)) := True;
for I in 0 .. Points loop
Random_Free (X, Y);
loop
-- If collide with wall then new random start
while
X = Width_Range'First or X = Width_Range'Last or
Y = Height_Range'First or Y = Height_Range'Last
loop
Random_Free (X, Y);
end loop;
exit when Field (X - 1, Y - 1) or Field (X, Y - 1) or Field (X + 1, Y - 1);
exit when Field (X - 1, Y) or Field (X + 1, Y);
exit when Field (X - 1, Y + 1) or Field (X, Y + 1) or Field (X + 1, Y + 1);
Direc := Random_Direc.Random (Direc_Gen);
case Direc is
when NW | N | NE => Y := Y - 1;
when SW | S | SE => Y := Y + 1;
when others => null;
end case;
case Direc is
when NW | W | SW => X := X - 1;
when SE | E | NE => X := X + 1;
when others => null;
end case;
end loop;
Field (X, Y) := True;
Renderer.Draw (Point => (SDL.C.int (X), SDL.C.int (Y)));
if I mod 100 = 0 then
if Poll_Quit then
return;
end if;
Window.Update_Surface;
end if;
end loop;
end Draw_Brownian_Tree;
begin
Random_Width.Reset (Width_Gen);
Random_Height.Reset (Height_Gen);
Random_Direc.Reset (Direc_Gen);
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Brownian tree",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Renderer.Set_Draw_Colour ((200, 200, 200, 255));
Draw_Brownian_Tree;
Window.Update_Surface;
loop
exit when Poll_Quit;
delay 0.050;
end loop;
Window.Finalize;
SDL.Finalise;
end Brownian_Tree; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #APL | APL | input ← {⍞←'Guess: ' ⋄ 7↓⍞}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
valid ← isdigits∧4=≢
guess ← ⍎¨input⍣(valid⊣)
bulls ← +/=
cows ← +/∊∧≠
game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣)
random ← 4∘⊣?9∘⊣
moo ← 'You win!'⊣(random game⊢)
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #jq | jq | # substitute ^ for STX and | for ETX
def makePrintable:
if . == null then null
else sub("\u0002"; "^") | sub("\u0003"; "|")
end;
def bwt:
{stx: "\u0002", etx: "\u0003"} as $x
| if index($x.stx) >= 0 or index($x.etx) >= 0 then null
else $x.stx + . + $x.etx
| . as $s
| (reduce range(0; length) as $i ([];
.[$i] = $s[$i:] + $s[:$i]) | sort) as $table
| reduce range(0; length) as $i ("";
. + $table[$i][-1:])
end;
def ibwt:
. as $r
| length as $len
| reduce range(0;$len) as $i ([];
reduce range(0; $len) as $j (.;
.[$j] = $r[$j:$j+1] + .[$j]) | sort)
| first( .[] | select(endswith("\u0003")))
| .[1:-1] ;
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Julia | Julia | bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b))
function burrowswheeler_encode(s)
if match(r"\x02|\x03", s) != nothing
throw("String for Burrows-Wheeler input cannot contain STX or ETX")
end
s = "\x02" * s * "\x03"
String([t[end] for t in bwsort([circshift([c for c in s], n) for n in 0:length(s)-1])])
end
function burrowswheeler_decode(s)
len, v = length(s), [c for c in s]
m = fill(' ', len, len)
for col in len:-1:1
m[:, col] .= v
for (i, row) in enumerate(bwsort([collect(r) for r in eachrow(m)]))
m[i, :] .= row
end
end
String(m[findfirst(row -> m[row, end] == '\x03', 1:len), 2:end-1])
end
for s in ["BANANA", "dogwood", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "Oops\x02"]
println("Original: ", s, "\nTransformation: ", burrowswheeler_encode(s),
"\nInverse transformation: ", burrowswheeler_decode(burrowswheeler_encode(s)), "\n")
end
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Applesoft_BASIC | Applesoft BASIC | 100 INPUT ""; T$
110 LET K% = RND(1) * 25 + 1
120 PRINT "ENCODED WITH ";
130 GOSUB 200ENCODED
140 LET K% = 26 - K%
150 PRINT "DECODED WITH ";
160 GOSUB 200DECODED
170 END
REM ENCODED/DECODED
200 PRINT "CAESAR " K%;
210 LET K$(1) = " (ROT-13)"
220 PRINT K$(K% = 13)
230 GOSUB 300CAESAR
240 PRINT T$
250 RETURN
REM CAESAR T$ K%
300 FOR I = 1 TO LEN(T$)
310 LET C$ = MID$(T$, I, 1)
320 GOSUB 400ENCODE
330 LET L = I - 1
340 LET T$(0) = MID$(T$, 1, L)
350 LET L = I + 1
360 LET T$ = C$ + MID$(T$, L)
370 LET T$ = T$(0) + T$
380 NEXT I
390 RETURN
REM ENCODE C$ K%
400 LET C = ASC(C$)
410 LET L = (C > 95) * 32
420 LET C = C - L
430 IF C < 65 THEN RETURN
440 IF C > 90 THEN RETURN
450 LET C = C + K%
460 IF C > 90 THEN C = C - 26
470 LET C$ = CHR$(C + L)
480 RETURN |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Dyalect | Dyalect | func calculateE(epsilon = 1.0e-15) {
func abs(n) {
if n < 0 {
-n
} else {
n
}
}
var fact = 1
var e = 2.0
var e0 = 0.0
var n = 2
while true {
e0 = e
fact *= n
n += 1
e += 1.0 / Float(fact)
if abs(e - e0) < epsilon {
break
}
}
return e
}
print(calculateE()) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #EasyLang | EasyLang | numfmt 0 5
fact = 1
n = 2
e = 2
while abs (e - e0) > 0.0001
e0 = e
fact = fact * n
n += 1
e += 1 / fact
.
print e |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Elixir | Elixir | defmodule Bulls_and_cows do
def player(size \\ 4) do
possibility = permute(size) |> Enum.shuffle
player(size, possibility, 1)
end
def player(size, possibility, i) do
guess = hd(possibility)
IO.puts "Guess #{i} is #{Enum.join(guess)} (from #{length(possibility)} possibilities)"
case get_score(size) do
{^size, 0} -> IO.puts "Solved!"
score ->
case select(size, possibility, guess, score) do
[] -> IO.puts "Sorry! I can't find a solution. Possible mistake in the scoring."
selected -> player(size, selected, i+1)
end
end
end
defp get_score(size) do
IO.gets("Answer (Bulls, cows)? ")
|> String.split(~r/\D/, trim: true)
|> Enum.map(&String.to_integer/1)
|> case do
[bulls, cows] when bulls+cows in 0..size -> {bulls, cows}
_ -> get_score(size)
end
end
defp select(size, possibility, guess, score) do
Enum.filter(possibility, fn x ->
bulls = Enum.zip(x, guess) |> Enum.count(fn {n,g} -> n==g end)
cows = size - length(x -- guess) - bulls
{bulls, cows} == score
end)
end
defp permute(size), do: permute(size, Enum.to_list(1..9))
defp permute(0, _), do: [[]]
defp permute(size, list) do
for x <- list, y <- permute(size-1, list--[x]), do: [x|y]
end
end
Bulls_and_cows.player |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Euphoria | Euphoria | include std/sequence.e
constant line = "--------+--------------------\n"
constant digits = "123456789"
sequence list = {}
function get_digits(integer n)
integer j
sequence d = digits, ret = ""
for i=1 to n do
j = rand(length(digits)-i)
ret &= d[i+j]
if j then
d[i+j] = d[i]
d[i] = ret[i]
end if
end for
return ret
end function
function MASK(integer x)
return power(2,x-digits[1])
end function
function score(sequence pattern, sequence guess)
integer bits = 0, bull = 0, cow = 0
for i = 1 to length(guess) do
if guess[i] != pattern[i] then
bits += MASK(pattern[i])
else
bull += 1
end if
end for
for i = 1 to length(guess) do
cow += and_bits(bits,MASK(guess[i])) != 0
end for
return {bull, cow}
end function
procedure pick(integer n, integer got, integer marker, sequence buf)
integer bits = 1
if got >= n then
list = append(list,buf)
else
for i = 0 to length(digits)-1 do
if not and_bits(marker,bits) then
buf[got+1] = i+digits[1]
pick(n, got+1, or_bits(marker,bits), buf)
end if
bits *= 2
end for
end if
end procedure
function tester(sequence item, sequence data)
return equal(score(item,data[1]),data[2])
end function
constant tester_id = routine_id("tester")
procedure game(sequence tgt)
integer p, n = length(tgt)
sequence buf = repeat(0,n), bc
list = {}
pick(n,0,0,buf)
p = 1
bc = {0,0}
while bc[1]<n do
buf = list[rand($)]
bc = score(tgt,buf)
printf(1,"Guess %2d| %s (from: %d)\nScore | %d bull, %d cow\n%s",
{p, buf, length(list)} & bc & {line})
list = filter(list, tester_id, {buf, bc})
p+=1
end while
end procedure
constant n = 4
sequence secret = get_digits(n)
printf(1,"%sSecret | %s\n%s", {line, secret, line})
game(secret) |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #FreeBASIC | FreeBASIC | ' VERSION 16-03-2016
' COMPILE WITH: FBC -S CONSOLE
' TRUE/FALSE ARE BUILT-IN CONSTANTS SINCE FREEBASIC 1.04
' BUT WE HAVE TO DEFINE THEM FOR OLDER VERSIONS.
#IFNDEF TRUE
#DEFINE FALSE 0
#DEFINE TRUE NOT FALSE
#ENDIF
FUNCTION WD(M AS INTEGER, D AS INTEGER, Y AS INTEGER) AS INTEGER
' ZELLERISH
' 0 = SUNDAY, 1 = MONDAY, 2 = TUESDAY, 3 = WEDNESDAY
' 4 = THURSDAY, 5 = FRIDAY, 6 = SATURDAY
IF M < 3 THEN ' IF M = 1 OR M = 2 THEN
M += 12
Y -= 1
END IF
RETURN (Y + (Y \ 4) - (Y \ 100) + (Y \ 400) + D + ((153 * M + 8) \ 5)) MOD 7
END FUNCTION
FUNCTION LEAPYEAR(Y AS INTEGER) AS INTEGER
IF (Y MOD 4) <> 0 THEN RETURN FALSE
IF (Y MOD 100) = 0 ANDALSO (Y MOD 400) <> 0 THEN RETURN FALSE
RETURN TRUE
END FUNCTION
' ------=< MAIN >=------
' HARD CODED FOR 132 CHARACTERS PER LINE
DIM AS STRING WDN = "MO TU WE TH FR SA SU" ' WEEKDAY NAMES
DIM AS STRING MO(1 TO 12) => {"JANUARY", "FEBRUARY", "MARCH", "APRIL", _
"MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", _
"OCTOBER", "NOVEMBER", "DECEMBER"}
DIM AS STRING TMP1, TMP2, D(1 TO 12)
DIM AS UINTEGER ML(1 TO 12) => {31,28,31,30,31,30,31,31,30,31,30,31}
DIM AS UINTEGER I, I1, J, K, Y = 1969
'SCREENRES 1080,600,8
IF LEAPYEAR(Y) = TRUE THEN ML(2) = 29
TMP1 = ""
FOR I = 1 TO 31
TMP1 = TMP1 + RIGHT((" " + STR(I)), 3)
NEXT I
FOR I = 1 TO 12
TMP2 = ""
J = WD(I,1, Y)
IF J = 0 THEN J = 7
J = J - 1
TMP2 = SPACE(J * 3) + LEFT(TMP1, ML(I) * 3) + SPACE(21)
D(I) = TMP2
NEXT I
PRINT
TMP1 = "INSERT YOUR SNOOPY PICTURE HERE"
PRINT SPACE((132 - LEN(TMP1)) \ 2); TMP1
PRINT
TMP1 = STR(Y)
PRINT SPACE((132 - LEN(TMP1)) \ 2); TMP1
PRINT
' 6 MONTH ON A ROW
TMP2 = " "
FOR I = 1 TO 6
TMP2 = TMP2 + WDN
IF I < 6 THEN TMP2 = TMP2 + " "
NEXT I
FOR I = 1 TO 12 STEP 6
TMP1 = ""
FOR J = I TO I + 4
TMP1 = TMP1 + LEFT(SPACE((22 - LEN(MO(J))) \ 2) + MO(J) + SPACE(11), 22)
NEXT J
TMP1 = TMP1 + SPACE((22 - LEN(MO(I + 5))) \ 2) + MO(I + 5)
PRINT TMP1
PRINT TMP2
FOR J = 1 TO 85 STEP 21
FOR K = I TO I + 4
PRINT MID(D(K), J ,21); " ";
NEXT K
PRINT MID(D(I + 5), J ,21)
NEXT J
PRINT
NEXT I
' EMPTY KEYBOARD BUFFER
WHILE INKEY <> "" : WEND
PRINT : PRINT "HIT ANY KEY TO END PROGRAM"
SLEEP
END |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #LabVIEW | LabVIEW | Section Header
+ name := TEST_C_INTERFACE;
// this will be inserted in front of the program
- external := `#include <string.h>`;
Section Public
- main <- (
+ s : STRING_CONSTANT;
+ p : NATIVE_ARRAY[CHARACTER];
s := "Hello World!";
p := s.to_external;
// this will be inserted in-place
// use `expr`:type to tell Lisaac what's the type of the external expression
p := `strdup(@p)` : NATIVE_ARRAY[CHARACTER];
s.print;
'='.print;
p.println;
// this will also be inserted in-place, expression type disregarded
`free(@p)`;
); |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Lisaac | Lisaac | Section Header
+ name := TEST_C_INTERFACE;
// this will be inserted in front of the program
- external := `#include <string.h>`;
Section Public
- main <- (
+ s : STRING_CONSTANT;
+ p : NATIVE_ARRAY[CHARACTER];
s := "Hello World!";
p := s.to_external;
// this will be inserted in-place
// use `expr`:type to tell Lisaac what's the type of the external expression
p := `strdup(@p)` : NATIVE_ARRAY[CHARACTER];
s.print;
'='.print;
p.println;
// this will also be inserted in-place, expression type disregarded
`free(@p)`;
); |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #C | C | /* function with no argument */
f();
/* fix number of arguments */
g(1, 2, 3);
/* Optional arguments: err...
Feel free to make sense of the following. I can't. */
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
} /* end of sensible code */
/* Variadic function: how the args list is handled solely depends on the function */
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
/* call it as: (if you feed it something it doesn't expect, don't count on it working) */
h(1, 2, 3, 4, "abcd", (void*)0);
/* named arguments: this is only possible through some pre-processor abuse
*/
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17); // prints "17,5"
/* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/
v(.arg2=1); // prints "0,1"
v(); // prints "0,0"
/* as a first-class object (i.e. function pointer) */
printf("%p", f); /* that's the f() above */
/* return value */
double a = asin(1);
/* built-in functions: no such thing. Compiler may interally give special treatment
to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */
/* subroutines: no such thing. You can goto places, but I doubt that counts. */
/* Scalar values are passed by value by default. However, arrays are passed by reference. */
/* Pointers *sort of* work like references, though. */ |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Phix | Phix | integer n = 5,
w = power(3,n-1),
len = w
string line = repeat('#',w)&"\n"
while 1 do
puts(1,line)
if len=1 then exit end if
len /= 3
integer pos = 1
while pos<(w-len) do
pos += len
line[pos..pos+len-1] = ' '
pos += len
end while
end while
|
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
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var mod = Fn.new { |n, m| ((n%m) + m) % m }
var carmichael = Fn.new { |p1|
for (h3 in 2...p1) {
for (d in 1...h3 + p1) {
if ((h3 + p1) * (p1 - 1) % d == 0 && mod.call(-p1 * p1, h3) == d % h3) {
var p2 = 1 + ((p1 - 1) * (h3 + p1) / d).floor
if (Int.isPrime(p2)) {
var p3 = 1 + (p1 * p2 / h3).floor
if (Int.isPrime(p3)) {
if (p2 * p3 % (p1 - 1) == 1) {
var c = p1 * p2 * p3
Fmt.print("$2d $4d $5d $10d", p1, p2, p3, c)
}
}
}
}
}
}
}
System.print("The following are Carmichael munbers for p1 <= 61:\n")
System.print("p1 p2 p3 product")
System.print("== == == =======")
for (p1 in 2..61) {
if (Int.isPrime(p1)) carmichael.call(p1)
} |
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
| #OCaml | OCaml | # let nums = [1;2;3;4;5;6;7;8;9;10];;
val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
# let sum = List.fold_left (+) 0 nums;;
val sum : int = 55
# let product = List.fold_left ( * ) 1 nums;;
val product : int = 3628800 |
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
| #UNIX_Shell | UNIX Shell | dog="Benjamin"
Dog="Samba"
DOG="Bernie"
echo "The three dogs are 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
| #Ursa | Ursa | > decl string dog Dog DOG
> set dog "Benjamin"
> set Dog "Samba"
> set DOG "Bernie"
> out "The three dogs are named " dog ", " Dog ", and " DOG endl console
The three dogs are named Benjamin, Samba, and Bernie
> |
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
| #VBA | VBA | Public Sub case_sensitivity()
'VBA does not allow variables that only differ in case
'The VBA IDE vbe will rename variable 'dog' to 'DOG'
'when trying to define a second variable 'DOG'
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub |
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}
| #Quackery | Quackery | [ [] unrot
swap witheach
[ over witheach
[ over nested
swap nested join
nested dip rot join
unrot ]
drop ] drop ] is cartprod ( [ [ --> [ )
' [ 1 2 ] ' [ 3 4 ] cartprod echo cr
' [ 3 4 ] ' [ 1 2 ] cartprod echo cr
' [ 1 2 ] ' [ ] cartprod echo cr
' [ ] ' [ 1 2 ] cartprod echo cr |
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
| #Fermat | Fermat | Func Catalan(n)=(2*n)!/((n+1)!*n!).;
for i=1 to 15 do !Catalan(i);!' ' od; |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Swift | Swift | // Class
MyClass.method(someParameter)
// or equivalently:
let foo = MyClass.self
foo.method(someParameter)
// Instance
myInstance.method(someParameter)
// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3) |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Tcl | Tcl | package require Tcl 8.6
# "Static" (on class object)
MyClass mthd someParameter
# Instance
$myInstance mthd someParameter |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Ursa | Ursa | # create an instance of the built-in file class
decl file f
# call the file.open method
f.open "filename.txt" |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Tcl | Tcl | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
# Create the OpenImage command by other means here...
}
set handle [OpenImage "/the/file/name"] |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #TXR | TXR | This is the TXR Lisp interactive listener of TXR 176.
Use the :quit command or type Ctrl-D on empty line to exit.
1> (typedef utsarray (zarray 65 char))
#<ffi-type (zarray 65 char)>
2> (typedef utsname (struct utsname (sysname utsarray)
(nodename utsarray)
(release utsarray)
(version utsarray)
(machine utsarray)
(domainname utsarray)))
#<ffi-type (struct utsname (sysname utsarray) (nodename utsarray) (release utsarray)
(version utsarray) (machine utsarray) (domainname utsarray))>
3> (with-dyn-lib nil (deffi uname "uname" int ((ptr-out utsname))))
** warning: (expr-3:1) defun: redefining uname, which is a built-in defun
#:lib-0176
4> (let ((u (new utsname))) (prinl (uname u)) u)
0
#S(utsname sysname "Linux" nodename "zelenka" release "3.2.0-40-generic"
version "#64-Ubuntu SMP Mon Mar 25 21:22:26 UTC 2013" machine "i686"
domainname "(none)") |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Phix | Phix | --
-- demo\rosetta\BrilliantNumbers.exw
-- =================================
--
with javascript_semantics
requires("1.0.2") -- (for in)
atom t0 = time()
function get_primes_by_digits(integer limit)
sequence primes = get_primes_le(power(10,limit)),
primes_by_digits = {}
integer p = 10
while length(primes) do
integer pi = abs(binary_search(p,primes))-1
primes_by_digits &= {primes[1..pi]}
primes = primes[pi+1..$]
p*= 10
end while
return primes_by_digits
end function
sequence primes_by_digits = get_primes_by_digits(8)
procedure first100()
sequence brilliant_numbers = {}
for primes in primes_by_digits do
for i=1 to length(primes) do
--see talk page
-- for j=i to length(primes) do
for j=1 to i do
brilliant_numbers &= primes[i]*primes[j]
end for
end for
if length(brilliant_numbers)>=100 then exit end if
end for
brilliant_numbers = sort(brilliant_numbers)[1..100]
sequence j100 = join_by(brilliant_numbers,1,10," ","\n","%,5d")
printf(1,"First 100 brilliant numbers:\n%s\n\n",{j100})
end procedure
first100()
atom pwr = 10, count = 0
for p=1 to 2*length(primes_by_digits)-1 do
sequence primes = primes_by_digits[floor(p/2)+1]
atom pos = count+1,
min_product = 0
for i=1 to length(primes) do
integer p1 = primes[i],
j = abs(binary_search(floor((pwr+p1-1)/p1),primes,i))
if j<=length(primes) then -- (always is, I think)
integer p2 = primes[j]
atom prod = p1*p2
if min_product=0 or prod<min_product then
min_product = prod
end if
pos += j-i
if p1>=p2 then exit end if
end if
end for
printf(1,"First brilliant number >= 10^%d is %,d at position %,d\n", {p, min_product, pos})
pwr *= 10;
if odd(p) then
integer size = length(primes)
count += size * (size + 1) / 2;
end if
end for
?elapsed(time()-t0)
{} = wait_key()
|
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #11l | 11l | F getitem(=s, depth = 0)
V out = [‘’]
L s != ‘’
V c = String(s[0])
I depth & (c == ‘,’ | c == ‘}’)
R (out, s)
I c == ‘{’
V x = getgroup(s[1..], depth + 1)
I !x[0].empty
out = multiloop(out, x[0], (a, b) -> a‘’b)
s = x[1]
L.continue
I c == "\\" & s.len > 1
(s, c) = (s[1..], c‘’s[1])
out = out.map(a -> a‘’@c)
s = s[1..]
R (out, s)
F getgroup(=s, depth)
[String] out
V comma = 0B
L s != ‘’
V gs = getitem(s, depth)
s = gs[1]
I s == ‘’
L.break
out [+]= gs[0]
I s[0] == ‘}’
I comma
R (out, s[1..])
R (out.map(a -> ‘{’a‘}’), s[1..])
I s[0] == ‘,’
(comma, s) = (1B, s[1..])
R ([‘’] * 0, ‘’)
L(s) |‘~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}’.split("\n")
print(([s] [+] getitem(s)[0]).join("\n\t")"\n") |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #ALGOL_W | ALGOL W | BEGIN
INTEGER WIDTH, YEAR;
INTEGER COLS, LEAD, GAP;
STRING(2) ARRAY WDAYS (0::6);
RECORD MONTH ( STRING(9) MNAME; INTEGER DAYS, START_WDAY, AT_POS );
REFERENCE(MONTH) ARRAY MONTHS(0::11);
WIDTH := 80; YEAR := 1969;
BEGIN
WDAYS(0) := "Su"; WDAYS(1) := "Mo"; WDAYS(2) := "Tu";
WDAYS(3) := "We"; WDAYS(4) := "Th"; WDAYS(5) := "Fr"; WDAYS(6) := "Sa";
MONTHS( 0) := MONTH(" January", 31, 0, 0 );
MONTHS( 1) := MONTH(" February", 28, 0, 0 );
MONTHS( 2) := MONTH(" March", 31, 0, 0 );
MONTHS( 3) := MONTH(" April", 30, 0, 0 );
MONTHS( 4) := MONTH(" May", 31, 0, 0 );
MONTHS( 5) := MONTH(" June", 30, 0, 0 );
MONTHS( 6) := MONTH(" July", 31, 0, 0 );
MONTHS( 7) := MONTH(" August", 31, 0, 0 );
MONTHS( 8) := MONTH("September", 30, 0, 0 );
MONTHS( 9) := MONTH(" October", 31, 0, 0 );
MONTHS(10) := MONTH(" November", 30, 0, 0 );
MONTHS(11) := MONTH(" December", 31, 0, 0 )
END;
BEGIN
PROCEDURE SPACE(INTEGER VALUE N);
BEGIN
WHILE N > 0 DO BEGIN
WRITEON(" "); N := N-1;
END
END SPACE;
PROCEDURE INIT_MONTHS;
BEGIN
INTEGER I;
IF YEAR REM 4 = 0 AND YEAR REM 100 NOT = 0 OR YEAR REM 400 = 0 THEN
DAYS(MONTHS(1)) := 29;
YEAR := YEAR-1;
START_WDAY(MONTHS(0))
:= (YEAR * 365 + YEAR DIV 4 - YEAR DIV 100 + YEAR DIV 400 + 1) REM 7;
FOR I := 1 STEP 1 UNTIL 12-1 DO
START_WDAY(MONTHS(I)) :=
(START_WDAY(MONTHS(I-1)) + DAYS(MONTHS(I-1))) REM 7;
COLS := (WIDTH + 2) DIV 22;
WHILE 12 REM COLS NOT = 0 DO
COLS := COLS-1;
GAP := IF COLS - 1 NOT = 0 THEN (WIDTH - 20 * COLS) DIV (COLS - 1) ELSE 0;
IF GAP > 4 THEN
GAP := 4;
LEAD := (WIDTH - (20 + GAP) * COLS + GAP + 1) DIV 2;
YEAR := YEAR+1
END INIT_MONTHS;
PROCEDURE PRINT_ROW(INTEGER VALUE ROW);
BEGIN
INTEGER C, I, FROM, UP_TO;
INTEGER PROCEDURE PREINCREMENT(INTEGER VALUE RESULT I);
BEGIN I := I+1; I
END PREINCREMENT;
INTEGER PROCEDURE POSTINCREMENT(INTEGER VALUE RESULT I);
BEGIN INTEGER PREV_VALUE;
PREV_VALUE := I; I := I+1; PREV_VALUE
END POSTINCREMENT;
FROM := ROW * COLS;
UP_TO := FROM + COLS;
SPACE(LEAD);
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
I := 9 % LENGTH OF MNAME(MONTHS(C)) % ;
SPACE((20 - I) DIV 2);
WRITEON(MNAME(MONTHS(C)));
SPACE(20 - I - (20 - I) DIV 2 + (IF C = UP_TO - 1 THEN 0 ELSE GAP));
END;
WRITE();
SPACE(LEAD);
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
FOR I := 0 STEP 1 UNTIL 7-1 DO BEGIN
WRITEON(WDAYS(I)); IF I NOT = 6 THEN WRITEON(" ")
END;
IF C < UP_TO - 1 THEN
SPACE(GAP)
ELSE
WRITE();
END;
WHILE BEGIN
C := FROM;
WHILE C < UP_TO AND AT_POS(MONTHS(C)) >= DAYS(MONTHS(C)) DO
C := C + 1;
C NOT = UP_TO
END DO BEGIN
SPACE(LEAD);
C := FROM;
WHILE C < UP_TO DO BEGIN
I := 0;
WHILE I < START_WDAY(MONTHS(C)) DO BEGIN
I := I + 1;
SPACE(3)
END;
WHILE POSTINCREMENT(I) < 7 AND AT_POS(MONTHS(C)) < DAYS(MONTHS(C)) DO BEGIN
WRITEON(I_W := 2, S_W := 0, PREINCREMENT(AT_POS(MONTHS(C))));
IF I < 7 OR C < UP_TO - 1 THEN
SPACE(1)
END;
WHILE POSTINCREMENT(I) <= 7 AND C < UP_TO-1 DO
SPACE(3);
IF C < UP_TO - 1 THEN
SPACE(GAP - 1);
START_WDAY(MONTHS(C)) := 0;
C := C + 1
END;
WRITE();
END;
WRITE()
END PRINT_ROW;
PROCEDURE PRINT_YEAR;
BEGIN
INTEGER ROW, STRLEN, Y;
STRLEN := 1;
Y := YEAR;
WHILE Y > 9 DO BEGIN Y := Y DIV 10; STRLEN := STRLEN + 1 END;
SPACE((WIDTH - STRLEN) DIV 2);
WRITEON(I_W := 1, YEAR);
WRITE(); WRITE();
WHILE ROW * COLS < 12 DO BEGIN
PRINT_ROW(ROW);
ROW := ROW+1
END
END PRINT_YEAR;
INIT_MONTHS;
PRINT_YEAR
END
END. |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Common_Lisp | Common Lisp | (defpackage :funky
;; only these symbols are public
(:export :widget :get-wobbliness)
;; for convenience, bring common lisp symbols into funky
(:use :cl))
;; switch reader to funky package: all symbols that are
;; not from the CL package are interned in FUNKY.
(in-package :funky)
(defclass widget ()
;; :initarg -> slot "wobbliness" is initialized using :wobbliness keyword
;; :initform -> if initarg is missing, slot defaults to 42
;; :reader -> a "getter" method called get-wobbliness is generated
((wobbliness :initarg :wobbliness :initform 42 :reader get-wobbliness)))
;; simulate being in another source file with its own package:
;; cool package gets external symbols from funky, and cl:
(defpackage :cool
(:use :funky :cl))
(in-package :cool)
;; we can use the symbol funky:widget without any package prefix:
(defvar *w* (make-instance 'widget :wobbliness 36))
;; ditto with funky:get-wobbliness
(format t "wobbliness: ~a~%" (get-wobbliness *w*))
;; direct access to the slot requires fully qualified private symbol
;; and double colon:
(format t "wobbliness: ~a~%" (slot-value *w* 'funky::wobbliness))
;; if we use unqualified wobbliness, it's a different symbol:
;; it is cool::wobbliness interned in our local package.
;; we do not have funky:wobbliness because it's not exported by funky.
(unless (ignore-errors
(format t "wobbliness: ~a~%" (slot-value *w* 'wobbliness)))
(write-line "didn't work"))
;; single colon results in error at read time! The expression is not
;; even read and evaluated. The symbol is internal and so cannot be used.
(format t "wobbliness: ~a~%" (slot-value *w* 'funky:wobbliness))
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #D | D | module breakingprivacy;
struct Foo
{
int[] arr;
private:
int x;
string str;
float f;
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Applesoft_BASIC | Applesoft BASIC | 0GOSUB2:FORQ=0TOTSTEP0:X=A:Y=B:FORO=0TOTSTEP0:XDRAWTATX,Y:X=INT(RND(T)*J)*Z:Y=INT(RND(T)*H):XDRAWTATX,Y:O=PEEK(C)>0:NEXTO:FORP=0TOTSTEP0:A=X:B=Y:R=INT(RND(T)*E):X=X+X(R):Y=Y+Y(R):IFX<0ORX>MORY<0ORY>NTHENNEXTQ
1 XDRAW T AT X,Y:P = NOT PEEK (C): XDRAW T AT A,B: NEXT P: XDRAW T AT X,Y:Q = A = 0 OR A = M OR B = 0 OR B = N: NEXT Q: END
2 T = 1:Z = 2:E = 8:C = 234
3 W = 280:A = W / 2:J = A
4 H = 192:B = H / 2:M = W - 2
5 N = H - 1:U = - 1:V = - 2
6 Y(0) = U:X(0) = V:Y(1) = U
7 Y(2) = U:X(2) = 2:X(3) = 2
8 Y(4) = 1:X(4) = 2:Y(5) = 1
9 X(6) = V:Y(6) = 1:X(7) = V
10 POKE 768,1: POKE 769,0
11 POKE 770,4: POKE 771,0
12 POKE 772,5: POKE 773,0
13 POKE 232,0: POKE 233,3
14 HGR : POKE 49234,0
15 ROT= 0: SCALE= 1: RETURN |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #AppleScript | AppleScript | on pickNumber()
set theNumber to ""
repeat 4 times
set theDigit to (random number from 1 to 9) as string
repeat while (offset of theDigit in theNumber) > 0
set theDigit to (random number from 1 to 9) as string
end repeat
set theNumber to theNumber & theDigit
end repeat
end pickNumber
to bulls of theGuess given key:theKey
set bullCount to 0
repeat with theIndex from 1 to 4
if text theIndex of theGuess = text theIndex of theKey then
set bullCount to bullCount + 1
end if
end repeat
return bullCount
end bulls
to cows of theGuess given key:theKey, bulls:bullCount
set cowCount to -bullCount
repeat with theIndex from 1 to 4
if (offset of (text theIndex of theKey) in theGuess) > 0 then
set cowCount to cowCount + 1
end if
end repeat
return cowCount
end cows
to score of theGuess given key:theKey
set bullCount to bulls of theGuess given key:theKey
set cowCount to cows of theGuess given key:theKey, bulls:bullCount
return {bulls:bullCount, cows:cowCount}
end score
on run
set theNumber to pickNumber()
set pastGuesses to {}
repeat
set theMessage to ""
repeat with aGuess in pastGuesses
set {theGuess, theResult} to aGuess
set theMessage to theMessage & theGuess & ":" & bulls of theResult & "B, " & cows of theResult & "C" & linefeed
end repeat
set theMessage to theMessage & linefeed & "Enter guess:"
set theGuess to text returned of (display dialog theMessage with title "Bulls and Cows" default answer "")
set theScore to score of theGuess given key:theNumber
if bulls of theScore is 4 then
display dialog "Correct! Found the secret in " & ((length of pastGuesses) + 1) & " guesses!"
exit repeat
else
set end of pastGuesses to {theGuess, theScore}
end if
end repeat
end run |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Kotlin | Kotlin | // Version 1.2.60
const val STX = "\u0002"
const val ETX = "\u0003"
fun bwt(s: String): String {
if (s.contains(STX) || s.contains(ETX)) {
throw RuntimeException("String can't contain STX or ETX")
}
val ss = STX + s + ETX
val table = Array<String>(ss.length) { ss.substring(it) + ss.substring(0, it) }
table.sort()
return String(table.map { it[it.lastIndex] }.toCharArray())
}
fun ibwt(r: String): String {
val len = r.length
val table = Array<String>(len) { "" }
repeat(len) {
for (i in 0 until len) {
table[i] = r[i].toString() + table[i]
}
table.sort()
}
for (row in table) {
if (row.endsWith(ETX)) {
return row.substring(1, len - 1)
}
}
return ""
}
fun makePrintable(s: String): String {
// substitute ^ for STX and | for ETX to print results
return s.replace(STX, "^").replace(ETX, "|")
}
fun main(args: Array<String>) {
val tests = listOf(
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
)
for (test in tests) {
println(makePrintable(test))
print(" --> ")
var t = ""
try {
t = bwt(test)
println(makePrintable(t))
}
catch (ex: RuntimeException) {
println("ERROR: " + ex.message)
}
val r = ibwt(t)
println(" --> $r\n")
}
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Arc | Arc |
(= rot (fn (L N)
(if
(and (<= 65 L) (>= 90 L))
(do
(= L (- L 65))
(= L (mod (+ N L) 26))
(= L (+ L 65)))
(and (<= 97 L) (>= 122 L))
(do
(= L (- L 97))
(= L (mod (+ N L) 26))
(= L (+ L 97))))
L))
(= caesar (fn (text (o shift))
(unless shift (= shift 13))
(= output (map [int _] (coerce text 'cons)))
(= output (map [rot _ shift] output))
(string output)
))
|
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #EDSAC_order_code | EDSAC order code |
[Calculate e]
[EDSAC program, Initial Orders 2]
[Library subroutine M3. Prints header and is then overwritten]
[Here, last character sets teleprinter to figures]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
@&*CALCULATION!OF!E@&#
..PZ [blank tape, needed to mark end of header text]
[Library subroutine D6. Division, accurate, fast.
Closed, 36 locations, working positions 6D and 8D.
C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
T56K [define load address for subroutine]
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[Library subroutine P1.
Prints a single positive number (without layout or round-off).
Prints number in 0D to n places of decimals, where
n is specified by 'P n F' pseudo-order after subroutine call.
Closed, 21 locations.]
T92K [define load address for subroutine]
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
..PZ
[Main routine]
T120K [Define load address for main program.
Must be even, because of double values at start.]
GK [set @ (theta) for relative addresses]
[0] PF PF [build sum 4*(1/3! + 1/4! + 1/5! + ...)]
[2] PF PF [term in sum]
[4] PD PF [2^-34, stop when term < this]
[6] PF [divisor]
[7] IF [1/2]
[8] QF [1/16]
[9] @F [carriage return]
[10] &F [line feed]
[11] WF [digit '2']
[12] MF [full stop / decimal point]
[13] K4096F [teleprinter null]
[14] A8@ [load 1/16]
LD [shift, makes 1/8]
UD [to 0D for subroutine D6]
T6@ [divisor := 1/8]
T#@ [sum := 0]
[loop, acc assumed to be 0 here]
[19] A6@ [load divisor]
A8@ [add 1/16]
U6@ [update divisor]
T4D [to 4D for subroutine D6]
[23] A23@ [for subroutine return]
G56F [call D6]
AD [load quotient]
U2#@ [store as term]
A#@ [add term into sum]
T#@ [update sum]
A2#@ [load term]
S4#@ [test for convergence]
G36@ [jump out if so]
A4#@ [restore term after test]
R4F [divide by 16]
TD [to 0D for subroutine D6]
E19@ [loop back]
[here when converged]
[36] TF [clear acc]
A#@ [load sum]
R1F [shift to divide by 4]
A7@ [add 1/2, now have (e - 2)]
YF [round]
TD [to 0D for subroutine P1]
O11@ [print '2.']
O12@
[44] A44@ [for subroutine return]
G92F [call P1 to print (e - 2)]
P10F [10 decimals]
O9@ [print CR]
O10@ [print LF]
O13@ [null to flush print buffer]
ZF [stop]
E14Z [relative address of entry]
PF [enter with accumulator = 0]
|
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Factor | Factor | USING: arrays combinators.short-circuit formatting fry io kernel
math math.combinatorics math.functions math.order math.parser
math.ranges random regexp sequences sets splitting ;
: bulls ( seq1 seq2 -- n ) [ = 1 0 ? ] 2map sum ;
: cows ( seq1 seq2 -- n ) [ intersect length ] [ bulls - ] 2bi ;
: score ( seq1 seq2 -- pair ) [ bulls ] [ cows 2array ] 2bi ;
: possibilities ( -- seq ) 9 [1,b] 4 <k-permutations> ;
: pare ( seq guess score -- new-seq ) '[ _ score _ = ] filter ;
: >number ( seq -- n ) reverse [ 10^ * ] map-index sum ;
: >score ( str -- pair ) "," split [ string>number ] map ;
: ask ( n -- ) "My guess is %d. How many bulls, cows? " printf ;
: valid-input? ( str -- ? )
{ [ R/ \d,\d/ matches? ] [ >score sum 0 4 between? ] } 1&& ;
: get-score ( n -- pair )
[ ask ] keep flush readln dup valid-input?
[ nip >score ] [ drop get-score ] if ;
: game ( seq -- )
dup random [
dup >number get-score dup first 4 =
[ 3drop "Success!" print ] [ pare game ] if
] [ drop "Scoring inconsistency." print ] if* ;
possibilities game |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Go | Go | PACKAGE MAIN
IMPORT (
"FMT"
"TIME"
)
CONST PAGEWIDTH = 80
FUNC MAIN() {
PRINTCAL(1969)
}
FUNC PRINTCAL(YEAR INT) {
THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)
VAR (
DAYARR [12][7][6]INT // MONTH, WEEKDAY, WEEK
MONTH, LASTMONTH TIME.MONTH
WEEKINMONTH, DAYINMONTH INT
)
FOR THISDATE.YEAR() == YEAR {
IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {
WEEKINMONTH = 0
DAYINMONTH = 1
}
WEEKDAY := THISDATE.WEEKDAY()
IF WEEKDAY == 0 && DAYINMONTH > 1 {
WEEKINMONTH++
}
DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()
LASTMONTH = MONTH
DAYINMONTH++
THISDATE = THISDATE.ADD(TIME.HOUR * 24)
}
CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2)
FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]")
CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2)
FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR)
MONTHS := [12]STRING{
" JANUARY ", " FEBRUARY", " MARCH ", " APRIL ",
" MAY ", " JUNE ", " JULY ", " AUGUST ",
"SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"}
DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"}
FOR QTR := 0; QTR < 4; QTR++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { // MONTH NAMES
FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR])
}
FMT.PRINTLN()
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { // DAY NAMES
FOR DAY := 0; DAY < 7; DAY++ {
FMT.PRINTF(" %S", DAYS[DAY])
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FOR DAY := 0; DAY < 7; DAY++ {
IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {
FMT.PRINTF(" ")
} ELSE {
FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])
}
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
}
FMT.PRINTLN()
}
} |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Lua | Lua | local ffi = require("ffi")
ffi.cdef[[
char * strndup(const char * s, size_t n);
int strlen(const char *s);
]]
local s1 = "Hello, world!"
print("Original: " .. s1)
local s_s1 = ffi.C.strlen(s1)
print("strlen: " .. s_s1)
local s2 = ffi.string(ffi.C.strndup(s1, s_s1), s_s1)
print("Copy: " .. s2)
print("strlen: " .. ffi.C.strlen(s2))
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #C.23 | C# |
/* a function that has no argument */
public int MyFunction();
/* a function with a fixed number of arguments */
FunctionWithArguments(4, 3, 2);
/* a function with optional arguments */
public void OptArg();
public static void Main()
{
OptArg(1);
OptArg(1, 2);
OptArg(1, 2, 3);
}
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
/* If you know the first and the last parameter */
ExampleMethod(3, optionalint: 4);
/* If you know all the parameter */
ExampleMethod(3, "Hello World", 4);
/* Variable number of arguments use array */
public static void UseVariableParameters(params int[] list)
/* Obtain return value from function */
public internal MyFunction();
int returnValue = MyFunction();
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
5 >ps
3 tps 1 - power var w
"#" 1 get nip w repeat var line
ps> for
3 swap 1 - power
w over / int var step
true >ps
for var j
tps not if
step for var k
line 32 j 1 - step * k + set var line
endfor
endif
ps> not >ps
endfor
cps
line ?
endfor |
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
| #zkl | zkl | var BN=Import("zklBigNum"), bi=BN(0); // gonna recycle bi
primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61);
var p2,p3;
cs:=[[(p1,h3,d); primes; { [2..p1 - 1] }; // list comprehension
{ [1..h3 + p1 - 1] },
{ ((h3 + p1)*(p1 - 1)%d == 0 and ((-p1*p1):mod(_,h3) == d%h3)) },//guard
{ (p2=1 + (p1 - 1)*(h3 + p1)/d):bi.set(_).probablyPrime() },//guard
{ (p3=1 + (p1*p2/h3)):bi.set(_).probablyPrime() }, //guard
{ 1==(p2*p3)%(p1 - 1) }; //guard
{ T(p1,p2,p3) } // return list of three primes in Carmichael number
]];
fcn mod(a,b) { m:=a%b; if(m<0) m+b else 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
| #Oforth | Oforth | [ 1, 2, 3, 4, 5 ] reduce(#max)
[ "abc", "def", "gfi" ] reduce(#+) |
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
| #Wren | Wren | var dog = "Benjamin"
var Dog = "Samba"
var DOG = "Bernie"
System.print("The three dogs are 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
| #XBS | XBS | set dog="Benjamin";
set DOG="Samba";
set Dog="Bernie";
log(`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}
| #R | R |
one_w_many <- function(one, many) lapply(many, function(x) c(one,x))
# Let's define an infix operator to perform a cartesian product.
"%p%" <- function( a, b ) {
p = c( sapply(a, function (x) one_w_many(x, b) ) )
if (is.null(unlist(p))) list() else p}
display_prod <-
function (xs) { for (x in xs) cat( paste(x, collapse=", "), "\n" ) }
fmt_vec <- function(v) sprintf("(%s)", paste(v, collapse=', '))
go <- function (...) {
cat("\n", paste( sapply(list(...),fmt_vec), collapse=" * "), "\n")
prod = Reduce( '%p%', list(...) )
display_prod( prod ) }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.