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/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.
| #Pike | Pike | obj->method();
obj["method"]();
call_function(obj->method);
call_function(obj["method"]); |
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.
| #PL.2FSQL | PL/SQL | CREATE OR REPLACE TYPE myClass AS OBJECT (
-- A class needs at least one member even though we don't use it
dummy NUMBER,
STATIC FUNCTION static_method RETURN VARCHAR2,
MEMBER FUNCTION instance_method RETURN VARCHAR2
);
/
CREATE OR REPLACE TYPE BODY myClass AS
STATIC FUNCTION static_method RETURN VARCHAR2 IS
BEGIN
RETURN 'Called myClass.static_method';
END static_method;
MEMBER FUNCTION instance_method RETURN VARCHAR2 IS
BEGIN
RETURN 'Called myClass.instance_method';
END instance_method;
END;
/
DECLARE
myInstance myClass;
BEGIN
myInstance := myClass(NULL);
DBMS_OUTPUT.put_line( myClass.static_method() );
DBMS_OUTPUT.put_line( myInstance.instance_method() );
END;/ |
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.
| #PureBasic | PureBasic | if OpenLibrary(0, "USER32.DLL")
*MessageBox = GetFunction(0, "MessageBoxA")
CallFunctionFast(*MessageBox, 0, "Body", "Title", 0)
CloseLibrary(0)
endif |
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.
| #Python | Python | import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime() |
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
| #ALGOL_68 | ALGOL 68 | BEGIN # Find Brilliant numbers - semi-primes whose two prime factors have #
# the same number of digits #
PR read "primes.incl.a68" PR # include prime utilities #
INT max prime = 1 010; # maximum prime we will consider #
# should be enough to find the first brilliant number > 10^6 #
[]BOOL prime = PRIMESIEVE max prime; # sieve of primes to max prime #
# construct a table of brilliant numbers #
[ 1 : max prime * max prime ]BOOL brilliant;
FOR n FROM LWB brilliant TO UPB brilliant DO brilliant[ n ] := FALSE OD;
# brilliant numbers where one of the fators is 2 #
brilliant[ 4 ] := TRUE;
FOR p FROM 3 BY 2 TO 7 DO brilliant[ 2 * p ] := TRUE OD;
# brilliant numbers where both factors are odd #
INT p start := 1, p end := 9;
WHILE pstart < max prime DO
FOR p FROM p start BY 2 TO p end DO
IF prime[ p ] THEN
brilliant[ p * p ] := TRUE;
FOR q FROM p + 2 BY 2 TO p end DO
IF prime[ q ] THEN
brilliant[ p * q ] := TRUE
FI
OD
FI
OD;
p start := p end + 2;
p end := ( ( p start - 1 ) * 10 ) - 1;
IF p end > max prime THEN p end := max prime FI
OD;
# show the first 100 brilliant numbers #
INT b count := 0;
FOR n TO UPB brilliant WHILE b count < 100 DO
IF brilliant[ n ] THEN
print( ( whole( n, -6 ) ) );
IF ( b count +:= 1 ) MOD 10 = 0 THEN print( ( newline ) ) FI
FI
OD;
# first brilliant number >= 10^n, n = 1, 2, ..., 6 #
b count := 0;
INT power of 10 := 10;
FOR n TO UPB brilliant DO
IF brilliant[ n ] THEN
b count +:= 1;
IF n >= power of 10 THEN
print( ( "First brilliant number >= ", whole( power of 10, -8 )
, ": " , whole( n, -8 )
, " at position " , whole( b count, -6 )
, newline
)
);
power of 10 *:= 10
FI
FI
OD
END |
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
| #D | D | import std.algorithm.iteration;
import std.algorithm.mutation;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.array;
import std.stdio;
import std.string;
immutable STX = 0x02;
immutable ETX = 0x03;
string bwt(string s) {
if (s.any!"a==0x02 || a==0x03") {
throw new Exception("Input can't contain STX or ETX");
}
char[] ss = (STX ~ s ~ ETX).dup;
string[] table;
foreach (i; 0..ss.length) {
table ~= ss.idup;
bringToFront(ss[0..$-1], ss[$-1..$]);
}
table.sort();
return table.map!"a[$-1]".array;
}
string ibwt(string r) {
const len = r.length;
string[] table;
table.length = len;
foreach (_; 0..len) {
foreach (i; 0..len) {
table[i] = r[i] ~ table[i];
}
table.sort();
}
foreach (row; table) {
if (row[$-1] == ETX) {
return row[1..len-1];
}
}
return "";
}
string makePrintable(string s) {
return tr(s, "\u0002\u0003", "^|");
}
void main() {
immutable tests = [
"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"
];
foreach (test; tests) {
writeln(test.makePrintable);
write(" --> ");
string t;
try {
t = bwt(test);
writeln(t.makePrintable);
} catch (Exception e) {
writeln("ERROR: ", e.message);
}
auto r = ibwt(t);
writeln(" --> ", r);
writeln;
}
} |
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
| #Action.21 | Action! | CHAR FUNC Shift(CHAR c BYTE code)
CHAR base
IF c>='a AND c<='z THEN
base='a
ELSEIF c>='A AND c<='Z THEN
base='A
ELSE
RETURN (c)
FI
c==+code-base
c==MOD 26
RETURN (c+base)
PROC Encrypt(CHAR ARRAY in,out BYTE code)
INT i
out(0)=in(0)
FOR i=1 TO in(0)
DO
out(i)=Shift(in(i),code)
OD
RETURN
PROC Decrypt(CHAR ARRAY in,out BYTE code)
Encrypt(in,out,26-code)
RETURN
PROC Test(CHAR ARRAY in BYTE code)
CHAR ARRAY enc(256),dec(256)
PrintE("Original:") PrintE(in)
Encrypt(in,enc,code)
PrintF("Encrypted code=%B:%E",code) PrintE(enc)
Decrypt(enc,dec,code)
PrintF("Decrypted code=%B:%E",code) PrintE(dec)
PutE()
RETURN
PROC Main()
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",5)
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
| #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
const double EPSILON = 1.0e-15;
unsigned long long fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
}
while (fabs(e - e0) >= EPSILON);
cout << "e = " << setprecision(16) << e << endl;
return 0;
} |
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
| #Clojure | Clojure |
;; Calculating the number e, euler-napier number.
;; We will use two methods
;; First method: the forumula (1 + 1/n)^n
;; Second method: the series partial sum 1/(p!)
;;first method
(defn inverse-plus-1 [n]
(+ 1 (/ 1 n)))
(defn e-return [n]
(Math/pow (inverse-plus-1 n) n))
(time (e-return 100000.))
;;"Elapsed time: 0.165629 msecs"
;;2.7182682371922975
;;SECOND METHOD
(defn method-e [n]
(loop [e-aprx 0M
value-add 1M
p 1M]
(if (> p n)
e-aprx
(recur (+ e-aprx value-add) (/ value-add p) (inc p)))))
(time (with-precision 110 (method-e 200M)))
|
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)
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BullsAndCows
{
class Program
{
const int ANSWER_SIZE = 4;
static IEnumerable<string> Permutations(int size)
{
if (size > 0)
{
foreach (string s in Permutations(size - 1))
foreach (char n in "123456789")
if (!s.Contains(n))
yield return s + n;
}
else
yield return "";
}
static IEnumerable<T> Shuffle<T>(IEnumerable<T> source)
{
Random random = new Random();
List<T> list = source.ToList();
while (list.Count > 0)
{
int ix = random.Next(list.Count);
yield return list[ix];
list.RemoveAt(ix);
}
}
static bool ReadBullsCows(out int bulls, out int cows)
{
string[] input = Console.ReadLine().Split(',').ToArray();
bulls = cows = 0;
if (input.Length < 2)
return false;
else
return int.TryParse(input[0], out bulls)
&& int.TryParse(input[1], out cows);
}
static void Main(string[] args)
{
Console.WriteLine("Bulls and Cows");
Console.WriteLine("==============");
Console.WriteLine();
List<string> answers = Shuffle(Permutations(ANSWER_SIZE)).ToList();
while (answers.Count > 1)
{
string guess = answers[0];
Console.Write("My guess is {0}. How many bulls, cows? ", guess);
int bulls, cows;
if (!ReadBullsCows(out bulls, out cows))
Console.WriteLine("Sorry, I didn't understand that. Please try again.");
else
for (int ans = answers.Count - 1; ans >= 0; ans--)
{
int tb = 0, tc = 0;
for (int ix = 0; ix < ANSWER_SIZE; ix++)
if (answers[ans][ix] == guess[ix])
tb++;
else if (answers[ans].Contains(guess[ix]))
tc++;
if ((tb != bulls) || (tc != cows))
answers.RemoveAt(ans);
}
}
if (answers.Count == 1)
Console.WriteLine("Hooray! The answer is {0}!", answers[0]);
else
Console.WriteLine("No possible answer fits the scores you gave.");
}
}
}
|
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.
| #COBOL | COBOL | (QL:QUICKLOAD '(DATE-CALC))
(DEFPARAMETER *DAY-ROW* "SU MO TU WE TH FR SA")
(DEFPARAMETER *CALENDAR-MARGIN* 3)
(DEFUN MONTH-TO-WORD (MONTH)
"TRANSLATE A MONTH FROM 1 TO 12 INTO ITS WORD REPRESENTATION."
(SVREF #("JANUARY" "FEBRUARY" "MARCH" "APRIL"
"MAY" "JUNE" "JULY" "AUGUST"
"SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER")
(1- MONTH)))
(DEFUN MONTH-STRINGS (YEAR MONTH)
"COLLECT ALL OF THE STRINGS THAT MAKE UP A CALENDAR FOR A GIVEN
MONTH AND YEAR."
`(,(DATE-CALC:CENTER (MONTH-TO-WORD MONTH) (LENGTH *DAY-ROW*))
,*DAY-ROW*
;; WE CAN ASSUME THAT A MONTH CALENDAR WILL ALWAYS FIT INTO A 7 BY 6 BLOCK
;; OF VALUES. THIS MAKES IT EASY TO FORMAT THE RESULTING STRINGS.
,@ (LET ((DAYS (MAKE-ARRAY (* 7 6) :INITIAL-ELEMENT NIL)))
(LOOP :FOR I :FROM (DATE-CALC:DAY-OF-WEEK YEAR MONTH 1)
:FOR DAY :FROM 1 :TO (DATE-CALC:DAYS-IN-MONTH YEAR MONTH)
:DO (SETF (AREF DAYS I) DAY))
(LOOP :FOR I :FROM 0 :TO 5
:COLLECT
(FORMAT NIL "~{~:[ ~;~2,D~]~^ ~}"
(LOOP :FOR DAY :ACROSS (SUBSEQ DAYS (* I 7) (+ 7 (* I 7)))
:APPEND (IF DAY (LIST DAY DAY) (LIST DAY))))))))
(DEFUN CALC-COLUMNS (CHARACTERS MARGIN-SIZE)
"CALCULATE THE NUMBER OF COLUMNS GIVEN THE NUMBER OF CHARACTERS PER
COLUMN AND THE MARGIN-SIZE BETWEEN THEM."
(MULTIPLE-VALUE-BIND (COLS EXCESS)
(TRUNCATE CHARACTERS (+ MARGIN-SIZE (LENGTH *DAY-ROW*)))
(INCF EXCESS MARGIN-SIZE)
(IF (>= EXCESS (LENGTH *DAY-ROW*))
(1+ COLS)
COLS)))
(DEFUN TAKE (N LIST)
"TAKE THE FIRST N ELEMENTS OF A LIST."
(LOOP :REPEAT N :FOR X :IN LIST :COLLECT X))
(DEFUN DROP (N LIST)
"DROP THE FIRST N ELEMENTS OF A LIST."
(COND ((OR (<= N 0) (NULL LIST)) LIST)
(T (DROP (1- N) (CDR LIST)))))
(DEFUN CHUNKS-OF (N LIST)
"SPLIT THE LIST INTO CHUNKS OF SIZE N."
(ASSERT (> N 0))
(LOOP :FOR X := LIST :THEN (DROP N X)
:WHILE X
:COLLECT (TAKE N X)))
(DEFUN PRINT-CALENDAR (YEAR &KEY (CHARACTERS 80) (MARGIN-SIZE 3))
"PRINT OUT THE CALENDAR FOR A GIVEN YEAR, OPTIONALLY SPECIFYING
A WIDTH LIMIT IN CHARACTERS AND MARGIN-SIZE BETWEEN MONTHS."
(ASSERT (>= CHARACTERS (LENGTH *DAY-ROW*)))
(ASSERT (>= MARGIN-SIZE 0))
(LET* ((CALENDARS (LOOP :FOR MONTH :FROM 1 :TO 12
:COLLECT (MONTH-STRINGS YEAR MONTH)))
(COLUMN-COUNT (CALC-COLUMNS CHARACTERS MARGIN-SIZE))
(TOTAL-SIZE (+ (* COLUMN-COUNT (LENGTH *DAY-ROW*))
(* (1- COLUMN-COUNT) MARGIN-SIZE)))
(FORMAT-STRING (CONCATENATE 'STRING
"~{~A~^~" (WRITE-TO-STRING MARGIN-SIZE) ",0@T~}~%")))
(FORMAT T "~A~%~A~%~%"
(DATE-CALC:CENTER "[SNOOPY]" TOTAL-SIZE)
(DATE-CALC:CENTER (WRITE-TO-STRING YEAR) TOTAL-SIZE))
(LOOP :FOR ROW :IN (CHUNKS-OF COLUMN-COUNT CALENDARS)
:DO (APPLY 'MAPCAR
(LAMBDA (&REST HEADS)
(FORMAT T FORMAT-STRING HEADS))
ROW)))) |
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
| #Hare | Hare | // hare run -lc ffi.ha
use fmt;
use strings;
@symbol("strdup") fn cstrdup(_: *const char) *char;
@symbol("free") fn cfree(_: nullable *void) void;
export fn main() void = {
let s = strings::to_c("Hello, World!");
defer free(s);
let dup = cstrdup(s);
fmt::printfln("{}", strings::fromc(dup))!;
cfree(dup);
}; |
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
| #Haskell | Haskell | {-# LANGUAGE ForeignFunctionInterface #-}
import Foreign (free)
import Foreign.C.String (CString, withCString, peekCString)
-- import the strdup function itself
-- the "unsafe" means "assume this foreign function never calls back into Haskell and avoid extra bookkeeping accordingly"
foreign import ccall unsafe "string.h strdup" strdup :: CString -> IO CString
testC = withCString "Hello World!" -- marshall the Haskell string "Hello World!" into a C string...
(\s -> -- ... and name it s
do s2 <- strdup s
s2_hs <- peekCString s2 -- marshall the C string called s2 into a Haskell string named s2_hs
putStrLn s2_hs
free s2) -- s is automatically freed by withCString once done |
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.
| #BASIC256 | BASIC256 | function Copialo$ (txt$, siNo, final$)
nuevaCadena$ = ""
for cont = 1 to siNo
nuevaCadena$ += txt$
next cont
return trim(nuevaCadena$) + final$
end function
subroutine Saludo()
print "Hola mundo!"
end subroutine
subroutine testCadenas (txt$)
for cont = 1 to length(txt$)
print mid(txt$, cont, 1); "";
next cont
end subroutine
subroutine testNumeros (a, b, c)
print a, b, c
end subroutine
call Saludo()
print Copialo$("Saludos ", 6, "")
print Copialo$("Saludos ", 3, "!!")
print
call testNumeros(1, 2, 3)
call testNumeros(1, 2, 0)
print
call testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \#incluye texto\#")
end |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Kotlin | Kotlin | // Version 1.2.31
const val WIDTH = 81
const val HEIGHT = 5
val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } }
fun cantor(start: Int, len: Int, index: Int) {
val seg = len / 3
if (seg == 0) return
for (i in index until HEIGHT) {
for (j in start + seg until start + seg * 2) lines[i][j] = ' '
}
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
}
fun main(args: Array<String>) {
cantor(0, WIDTH, 1)
lines.forEach { println(it) }
} |
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
| #Ruby | Ruby | cw = Enumerator.new do |y|
y << a = 1.to_r
loop { y << a = 1/(2*a.floor + 1 - a) }
end
def term_num(rat)
num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1
while den > 0
num, (digit, den) = den, num.divmod(den)
digit.times do
res |= dig << pwr
pwr += 1
end
dig ^= 1
end
res
end
puts cw.take(20).join(", ")
puts term_num (83116/51639r)
|
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
| #Rust | Rust | // [dependencies]
// num = "0.3"
use num::rational::Rational;
fn calkin_wilf_next(term: &Rational) -> Rational {
Rational::from_integer(1) / (Rational::from_integer(2) * term.floor() + 1 - term)
}
fn continued_fraction(r: &Rational) -> Vec<isize> {
let mut a = *r.numer();
let mut b = *r.denom();
let mut result = Vec::new();
loop {
let (q, r) = num::integer::div_rem(a, b);
result.push(q);
a = b;
b = r;
if a == 1 {
break;
}
}
let len = result.len();
if len != 0 && len % 2 == 0 {
result[len - 1] -= 1;
result.push(1);
}
result
}
fn term_number(r: &Rational) -> usize {
let mut result: usize = 0;
let mut d: usize = 1;
let mut p: usize = 0;
for n in continued_fraction(r) {
for _ in 0..n {
result |= d << p;
p += 1;
}
d ^= 1;
}
result
}
fn main() {
println!("First 20 terms of the Calkin-Wilf sequence are:");
let mut term = Rational::from_integer(1);
for i in 1..=20 {
println!("{:2}: {}", i, term);
term = calkin_wilf_next(&term);
}
let r = Rational::new(83116, 51639);
println!("{} is the {}th term of the sequence.", r, term_number(&r));
} |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func bitset: castOut (in integer: base, in integer: start, in integer: ending) is func
result
var bitset: casted is {};
local
var bitset: ran is {};
var integer: x is 0;
var integer: n is 0;
var integer: k is 0;
var boolean: finished is FALSE;
begin
for x range 0 to base - 2 do
if x rem pred(base) = x ** 2 rem pred(base) then
incl(ran, x);
end if;
end for;
x := start div pred(base);
repeat
for n range ran until finished do
k := pred(base) * x + n;
if k >= start then
if k > ending then
finished := TRUE;
else
incl(casted, k);
end if;
end if;
end for;
incr(x);
until finished;
end func;
const proc: main is func
begin
writeln(castOut(16, 1, 255));
end func; |
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
| #Sidef | Sidef | func cast_out(base = 10, min = 1, max = (base**2 - 1)) {
var b9 = base-1
var ran = b9.range.grep {|n| n%b9 == (n*n % b9) }
var x = min//b9
var r = []
loop {
ran.each {|n|
var k = (b9*x + n)
return r if (k > max)
r << k if (k >= min)
}
++x
}
return r
}
say cast_out().join(' ')
say cast_out(16).join(' ')
say cast_out(17).join(' ') |
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
| #Ring | Ring |
# Project : Carmichael 3 strong pseudoprimes
see "The following are Carmichael munbers for p1 <= 61:" + nl
see "p1 p2 p3 product" + nl
for p = 2 to 61
carmichael3(p)
next
func carmichael3(p1)
if isprime(p1) = 0 return ok
for h3 = 1 to p1 -1
t1 = (h3 + p1) * (p1 -1)
t2 = (-p1 * p1) % h3
if t2 < 0
t2 = t2 + h3
ok
for d = 1 to h3 + p1 -1
if t1 % d = 0 and t2 = (d % h3)
p2 = 1 + (t1 / d)
if isprime(p2) = 0
loop
ok
p3 = 1 + floor((p1 * p2 / h3))
if isprime(p3) = 0 or ((p2 * p3) % (p1 -1)) != 1
loop
ok
see "" + p1 + " " + p2 + " " + p3 + " " + p1*p2*p3 + nl
ok
next
next
func isprime(num)
if (num <= 1) return 0 ok
if (num % 2 = 0) and num != 2
return 0
ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0)
return 0
ok
next
return 1
|
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
| #Ruby | Ruby | # Generate Charmichael Numbers
require 'prime'
Prime.each(61) do |p|
(2...p).each do |h3|
g = h3 + p
(1...g).each do |d|
next if (g*(p-1)) % d != 0 or (-p*p) % h3 != d % h3
q = 1 + ((p - 1) * g / d)
next unless q.prime?
r = 1 + (p * q / h3)
next unless r.prime? and (q * r) % (p - 1) == 1
puts "#{p} x #{q} x #{r}"
end
end
puts
end |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Fold[f, x, {a, b, c, d}] |
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
| #Maxima | Maxima | lreduce(f, [a, b, c, d], x0);
/* (%o1) f(f(f(f(x0, a), b), c), d) */ |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET N=15
20 DIM t(N+2)
30 LET t(2)=1
40 FOR i=2 TO N+1
50 FOR j=i TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
60 LET t(i+1)=t(i)
70 FOR j=i+1 TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
80 PRINT t(i+1)-t(i);" ";
90 NEXT i |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Scheme | Scheme | (define dog "Benjamin")
(define Dog "Samba")
(define DOG "Bernie")
(if (eq? dog DOG)
(begin (display "There is one dog named ")
(display DOG)
(display ".")
(newline))
(begin (display "The three dogs are named ")
(display dog) (display ", ")
(display Dog) (display " and ")
(display DOG)
(display ".")
(newline))) |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const string: dog is "Benjamin";
const string: Dog is "Samba";
const string: DOG is "Bernie";
const proc: main is func
begin
writeln("The three dogs are named " <& dog <& ", " <& Dog <& " and " <& DOG <& ".");
end func; |
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}
| #Phix | Phix | with javascript_semantics
function cart(sequence s)
sequence res = {}
for n=2 to length(s) do
for i=1 to length(s[1]) do
for j=1 to length(s[2]) do
res = append(res,s[1][i]&s[2][j])
end for
end for
if length(s)=2 then exit end if
s[1..2] = {res}
res = {}
end for
return res
end function
?cart({{1,2},{3,4}})
?cart({{3,4},{1,2}})
?cart({{1,2},{}})
?cart({{},{1,2}})
?cart({{1776, 1789},{7, 12},{4, 14, 23},{0, 1}})
?cart({{1, 2, 3},{30},{500, 100}})
?cart({{1, 2, 3},{},{500, 100}})
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #ERRE | ERRE | PROGRAM CATALAN
PROCEDURE CATALAN(N->RES)
RES=1
FOR I=1 TO N DO
RES=RES*2*(2*I-1)/(I+1)
END FOR
END PROCEDURE
BEGIN
FOR N=0 TO 15 DO
CATALAN(N->RES)
PRINT(N;"=";RES)
END FOR
END PROGRAM
|
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.
| #PowerShell | PowerShell | $Date = Get-Date
$Date.AddDays( 1 )
[System.Math]::Sqrt( 2 ) |
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.
| #Processing | Processing | // define a rudimentary class
class HelloWorld
{
public static void sayHello()
{
println("Hello, world!");
}
public void sayGoodbye()
{
println("Goodbye, cruel world!");
}
}
// call the class method
HelloWorld.sayHello();
// create an instance of the class
HelloWorld hello = new HelloWorld();
// and call the instance method
hello.sayGoodbye(); |
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.
| #Python | Python | class MyClass(object):
@classmethod
def myClassMethod(self, x):
pass
@staticmethod
def myStaticMethod(x):
pass
def myMethod(self, x):
return 42 + x
myInstance = MyClass()
# Instance method
myInstance.myMethod(someParameter)
# A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:
MyClass.myMethod(myInstance, someParameter)
# Class or static methods
MyClass.myClassMethod(someParameter)
MyClass.myStaticMethod(someParameter)
# You can also call class or static methods on an instance, which will simply call it on the instance's class
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter) |
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.
| #QB64 | QB64 |
Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Function GetLastError& ()
End Declare
SetLastError 20
Print GetLastError |
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.
| #R | R | dyn.load("my/special/R/lib.so")
.Call("my_lib_fun", arg1, arg2) |
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
| #Arturo | Arturo | brilliant?: function [x][
pf: factors.prime x
and? -> 2 = size pf
-> equal? size digits first pf
size digits last pf
]
brilliants: new []
i: 2
while [100 > size brilliants][
if brilliant? i -> 'brilliants ++ i
i: i + 1
]
print "First 100 brilliant numbers:"
loop split.every: 10 brilliants 'row [
print map to [:string] row 'item -> pad item 4
]
print ""
i: 4
nth: 0
order: 1
while [order =< 6] [
if brilliant? i [
nth: nth + 1
if i >= 10^order [
print ["First brilliant number >= 10 ^" order "is" i "at position" nth]
order: order + 1
]
]
i: i + 1
] |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
} |
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
| #8080_Assembly | 8080 Assembly | bdos equ 5
putchar equ 2
rawio equ 6
puts equ 9
cstat equ 11
reads equ 10
org 100h
mvi c,puts
lxi d,signon ; Print name
call bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize the RNG with keyboard input
mvi c,puts
lxi d,entropy ; Ask for randomness
call bdos
mvi b,9 ; 9 times,
randloop: mvi c,3 ; read 3 keys.
lxi h,xabcdat + 1
randkey: push b ; Read a key
push h
randkeywait: mvi c,rawio
mvi e,0FFh
call bdos
ana a
jz randkeywait
pop h
pop b
xra m ; XOR it with the random memory
mov m,a
inx h
dcr c
jnz randkey ; Go get more characters
dcr b
jnz randloop
mvi c,puts
lxi d,done ; Tell the user we're done
call bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generate 4-digit secret code
lxi h,secret
mvi b,4
gencode: push h
push b
call randcode
pop b
pop h
mov m,a
inx h
dcr b
jnz gencode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User makes a guess
readguess: mvi c,puts ; Ask for guess
lxi d,guess
call bdos
mvi c,reads ; Read guess
lxi d,bufdef
call bdos
call newline ; Print newline
mvi b,4 ; Check input
lxi h,buf
validate: mov a,m
cpi '9' + 1 ; >9?
jnc inval ; = invalid
cpi '1' ; <1?
jc inval ; = invalid
sui '0' ; Make ASCII digit into number
mov m,a
inx h
dcr b
jnz validate
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Count bulls
mvi c,puts
lxi d,bulls ; Output "Bulls:"
call bdos
lxi d,secret
lxi h,buf
lxi b,4 ; No bulls, counter = 4
bullloop: ldax d ; Get secret digit
cmp m ; Match to buffer digit
cz countmatch
inx h
inx d
dcr c
jnz bullloop
push b ; Keep bulls for cow count,
push b ; and for final check.
call printcount
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Count cows
mvi c,puts
lxi d,cows ; Output ", Cows:"
call bdos
pop psw ; Retrieve the bulls (into A reg)
cma ; Negate amount of bulls
inr a
mov b,a ; Use it as start of cow count
mvi d,4 ; For all 4 secret digits..
lxi h,secret
cowouter: mov a,m ; Grab secret digit to test
push h ; Store secret position
mvi e,4 ; For all 4 input digits...
lxi h,buf
cowinner: cmp m ; Compare to current secret digit
cz countmatch
inx h
dcr e ; While there are more digits in buf
jnz cowinner ; Test next digit
pop h ; Restore secret position
inx h ; Look at next secret digit
dcr d ; While there are digits left
jnz cowouter
push b ; Keep cow count
call printcount
call newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Check win condition
pop psw ; Cow count (in A)
pop b ; Bull count (in B)
ana a ; To win, there must be 0 cows...
jnz readguess
mvi a,4 ; And 4 bulls.
cmp b
jnz readguess
mvi c,puts
lxi d,win
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Increment bull/cow counter
countmatch: inr b
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Print a newline
newline: mvi c,puts
lxi d,nl
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Output counter as ASCII
printcount: mvi a,'0'
add b
mvi c,putchar
mov e,a
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User entered invalid input
inval: mvi c,puts
lxi d,invalid
call bdos
jmp readguess
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generate random number 1-9 that isn't in key
randcode: call xabcrand
ani 0fh ; Low nybble
ana a ; 0 = invalid
jz randcode
cpi 10 ; >9 = invalid
jnc randcode
;; Check if it is a duplicate
mvi b,4
lxi h,secret
checkdup: cmp m
jz randcode
inx h
dcr b
jnz checkdup
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The "X ABC" 8-bit random number generator
;; (Google that to find where it came from)
xabcrand: lxi h,xabcdat
inr m ; X++
mov a,m ; X,
inx h ;
xra m ; ^ C,
inx h ;
xra m ; ^ A,
mov m,a ; -> A
inx h
add m ; + B,
mov m,a ; -> B
rar ; >>1
dcx h
xra m ; ^ A,
dcx h
add m ; + C
mov m,a ; -> C
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Strings
signon: db 'Bulls and Cows',13,10,'$'
entropy: db 'Please mash the keyboard to generate entropy...$'
done: db 'done.',13,10,13,10,'$'
bulls: db 'Bulls: $'
cows: db ', Cows: $'
guess: db 'Guess: $'
invalid: db 'Invalid input.',13,10,'$'
win: db 'You win!',13,10,'$'
nl: db 13,10,'$'
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variables
xabcdat: ds 4 ; RNG state
secret: ds 4 ; Holds the secret code
bufdef: db 4,0 ; User input buffer
buf: ds 4 |
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
| #Factor | Factor | USING: formatting io kernel math.transforms.bwt sequences ;
{
"banana" "dogwood" "TO BE OR NOT TO BE OR WANT TO BE OR NOT?"
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES"
} [
[ print ] [ bwt ] bi
2dup " bwt-->%3d %u\n" printf
ibwt " ibwt-> %u\n" printf nl
] each |
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
| #Go | Go | package main
import (
"fmt"
"sort"
"strings"
)
const stx = "\002"
const etx = "\003"
func bwt(s string) (string, error) {
if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 {
return "", fmt.Errorf("String can't contain STX or ETX")
}
s = stx + s + etx
le := len(s)
table := make([]string, le)
table[0] = s
for i := 1; i < le; i++ {
table[i] = s[i:] + s[:i]
}
sort.Strings(table)
lastBytes := make([]byte, le)
for i := 0; i < le; i++ {
lastBytes[i] = table[i][le-1]
}
return string(lastBytes), nil
}
func ibwt(r string) string {
le := len(r)
table := make([]string, le)
for range table {
for i := 0; i < le; i++ {
table[i] = r[i:i+1] + table[i]
}
sort.Strings(table)
}
for _, row := range table {
if strings.HasSuffix(row, etx) {
return row[1 : le-1]
}
}
return ""
}
func makePrintable(s string) string {
// substitute ^ for STX and | for ETX to print results
t := strings.Replace(s, stx, "^", 1)
return strings.Replace(t, etx, "|", 1)
}
func main() {
tests := []string{
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\002ABC\003",
}
for _, test := range tests {
fmt.Println(makePrintable(test))
fmt.Print(" --> ")
t, err := bwt(test)
if err != nil {
fmt.Println("ERROR:", err)
} else {
fmt.Println(makePrintable(t))
}
r := ibwt(t)
fmt.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
| #Ada | Ada | with Ada.Text_IO;
procedure Caesar is
type modulo26 is modulo 26;
function modulo26 (Character: Character; Output: Character) return modulo26 is
begin
return modulo26 (Character'Pos(Character)+Character'Pos(Output));
end modulo26;
function Character(Val: in modulo26; Output: Character)
return Character is
begin
return Character'Val(Integer(Val)+Character'Pos(Output));
end Character;
function crypt (Playn: String; Key: modulo26) return String is
Ciph: String(Playn'Range);
begin
for I in Playn'Range loop
case Playn(I) is
when 'A' .. 'Z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'A');
when 'a' .. 'z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'a');
when others =>
Ciph(I) := Playn(I);
end case;
end loop;
return Ciph;
end crypt;
Text: String := Ada.Text_IO.Get_Line;
Key: modulo26 := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
begin -- encryption main program
Ada.Text_IO.Put_Line("Playn ------------>" & Text);
Text := crypt(Text, Key);
Ada.Text_IO.Put_Line("Ciphertext ----------->" & Text);
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
end Caesar; |
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
| #COBOL | COBOL | >>SOURCE FORMAT IS FIXED
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 EPSILON USAGE COMPUTATIONAL-2 VALUE 1.0E-15.
01 FACT USAGE BINARY-DOUBLE UNSIGNED VALUE 1.
01 N USAGE BINARY-INT UNSIGNED.
01 E USAGE COMPUTATIONAL-2 VALUE 2.0.
01 E0 USAGE COMPUTATIONAL-2 value 0.0.
01 RESULT-MESSAGE.
03 FILLER PIC X(4) VALUE 'e = '.
03 RESULT-VALUE PIC 9.9(18) USAGE DISPLAY.
PROCEDURE DIVISION.
MAIN SECTION.
PERFORM
VARYING N FROM 2 BY 1
UNTIL FUNCTION ABS(E - E0) < EPSILON
MOVE E TO E0
COMPUTE FACT = FACT * N
COMPUTE E = E + 1.0 / FACT
END-PERFORM.
MOVE E TO RESULT-VALUE.
DISPLAY RESULT-MESSAGE.
STOP RUN.
|
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)
| #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <time.h>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const unsigned int LEN = 4;
//--------------------------------------------------------------------------------------------------
class CowsAndBulls_Player
{
public:
CowsAndBulls_Player() { fillPool(); }
void play() { secret = createSecret(); guess(); }
private:
void guess()
{
pair<int, int> res; int cc = 1;
cout << endl << " SECRET: " << secret << endl << "==============" << endl;
cout << "+-----------+---------+--------+\n| GUESS | BULLS | COWS |\n+-----------+---------+--------+\n";
while( true )
{
string gs = gimmeANumber();
if( gs.empty() ) { cout << endl << "Something went wrong with the scoring..." << endl << "Cannot find an answer!" << endl; return; }
if( scoreIt( gs, res ) ) { cout << endl << "I found the secret number!" << endl << "It is: " << gs << endl; return; }
cout << "| " << gs << " | " << setw( 3 ) << res.first << " | " << setw( 3 ) << res.second << " |\n+-----------+---------+--------+\n";
clearPool( gs, res );
}
}
void clearPool( string gs, pair<int, int>& r )
{
vector<string>::iterator pi = pool.begin();
while( pi != pool.end() )
{
if( removeIt( gs, ( *pi ), r ) ) pi = pool.erase( pi );
else pi++;
}
}
string gimmeANumber()
{
if( pool.empty() ) return "";
return pool[rand() % pool.size()];
}
void fillPool()
{
for( int x = 1234; x < 9877; x++ )
{
ostringstream oss; oss << x;
if( check( oss.str() ) ) pool.push_back( oss.str() );
}
}
bool check( string s )
{
for( string::iterator si = s.begin(); si != s.end(); si++ )
{
if( ( *si ) == '0' ) return false;
if( count( s.begin(), s.end(), ( *si ) ) > 1 ) return false;
}
return true;
}
bool removeIt( string gs, string ts, pair<int, int>& res )
{
pair<int, int> tp; getScore( gs, ts, tp );
return tp != res;
}
bool scoreIt( string gs, pair<int, int>& res )
{
getScore( gs, secret, res );
return res.first == LEN;
}
void getScore( string gs, string st, pair<int, int>& pr )
{
pr.first = pr.second = 0;
for( unsigned int ui = 0; ui < LEN; ui++ )
{
if( gs[ui] == st[ui] ) pr.first++;
else
{
for( unsigned int vi = 0; vi < LEN; vi++ )
if( gs[ui] == st[vi] ) pr.second++;
}
}
}
string createSecret()
{
string n = "123456789", rs = "";
while( rs.length() < LEN )
{
int r = rand() % n.length();
rs += n[r]; n.erase( r, 1 );
}
return rs;
}
string secret;
vector<string> pool;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); CowsAndBulls_Player cb;
cb.play(); cout << endl << endl;
return system( "pause" );
}
//--------------------------------------------------------------------------------------------------
|
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.
| #Common_Lisp | Common Lisp | (QL:QUICKLOAD '(DATE-CALC))
(DEFPARAMETER *DAY-ROW* "SU MO TU WE TH FR SA")
(DEFPARAMETER *CALENDAR-MARGIN* 3)
(DEFUN MONTH-TO-WORD (MONTH)
"TRANSLATE A MONTH FROM 1 TO 12 INTO ITS WORD REPRESENTATION."
(SVREF #("JANUARY" "FEBRUARY" "MARCH" "APRIL"
"MAY" "JUNE" "JULY" "AUGUST"
"SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER")
(1- MONTH)))
(DEFUN MONTH-STRINGS (YEAR MONTH)
"COLLECT ALL OF THE STRINGS THAT MAKE UP A CALENDAR FOR A GIVEN
MONTH AND YEAR."
`(,(DATE-CALC:CENTER (MONTH-TO-WORD MONTH) (LENGTH *DAY-ROW*))
,*DAY-ROW*
;; WE CAN ASSUME THAT A MONTH CALENDAR WILL ALWAYS FIT INTO A 7 BY 6 BLOCK
;; OF VALUES. THIS MAKES IT EASY TO FORMAT THE RESULTING STRINGS.
,@ (LET ((DAYS (MAKE-ARRAY (* 7 6) :INITIAL-ELEMENT NIL)))
(LOOP :FOR I :FROM (DATE-CALC:DAY-OF-WEEK YEAR MONTH 1)
:FOR DAY :FROM 1 :TO (DATE-CALC:DAYS-IN-MONTH YEAR MONTH)
:DO (SETF (AREF DAYS I) DAY))
(LOOP :FOR I :FROM 0 :TO 5
:COLLECT
(FORMAT NIL "~{~:[ ~;~2,D~]~^ ~}"
(LOOP :FOR DAY :ACROSS (SUBSEQ DAYS (* I 7) (+ 7 (* I 7)))
:APPEND (IF DAY (LIST DAY DAY) (LIST DAY))))))))
(DEFUN CALC-COLUMNS (CHARACTERS MARGIN-SIZE)
"CALCULATE THE NUMBER OF COLUMNS GIVEN THE NUMBER OF CHARACTERS PER
COLUMN AND THE MARGIN-SIZE BETWEEN THEM."
(MULTIPLE-VALUE-BIND (COLS EXCESS)
(TRUNCATE CHARACTERS (+ MARGIN-SIZE (LENGTH *DAY-ROW*)))
(INCF EXCESS MARGIN-SIZE)
(IF (>= EXCESS (LENGTH *DAY-ROW*))
(1+ COLS)
COLS)))
(DEFUN TAKE (N LIST)
"TAKE THE FIRST N ELEMENTS OF A LIST."
(LOOP :REPEAT N :FOR X :IN LIST :COLLECT X))
(DEFUN DROP (N LIST)
"DROP THE FIRST N ELEMENTS OF A LIST."
(COND ((OR (<= N 0) (NULL LIST)) LIST)
(T (DROP (1- N) (CDR LIST)))))
(DEFUN CHUNKS-OF (N LIST)
"SPLIT THE LIST INTO CHUNKS OF SIZE N."
(ASSERT (> N 0))
(LOOP :FOR X := LIST :THEN (DROP N X)
:WHILE X
:COLLECT (TAKE N X)))
(DEFUN PRINT-CALENDAR (YEAR &KEY (CHARACTERS 80) (MARGIN-SIZE 3))
"PRINT OUT THE CALENDAR FOR A GIVEN YEAR, OPTIONALLY SPECIFYING
A WIDTH LIMIT IN CHARACTERS AND MARGIN-SIZE BETWEEN MONTHS."
(ASSERT (>= CHARACTERS (LENGTH *DAY-ROW*)))
(ASSERT (>= MARGIN-SIZE 0))
(LET* ((CALENDARS (LOOP :FOR MONTH :FROM 1 :TO 12
:COLLECT (MONTH-STRINGS YEAR MONTH)))
(COLUMN-COUNT (CALC-COLUMNS CHARACTERS MARGIN-SIZE))
(TOTAL-SIZE (+ (* COLUMN-COUNT (LENGTH *DAY-ROW*))
(* (1- COLUMN-COUNT) MARGIN-SIZE)))
(FORMAT-STRING (CONCATENATE 'STRING
"~{~A~^~" (WRITE-TO-STRING MARGIN-SIZE) ",0@T~}~%")))
(FORMAT T "~A~%~A~%~%"
(DATE-CALC:CENTER "[SNOOPY]" TOTAL-SIZE)
(DATE-CALC:CENTER (WRITE-TO-STRING YEAR) TOTAL-SIZE))
(LOOP :FOR ROW :IN (CHUNKS-OF COLUMN-COUNT CALENDARS)
:DO (APPLY 'MAPCAR
(LAMBDA (&REST HEADS)
(FORMAT T FORMAT-STRING HEADS))
ROW)))) |
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
| #Icon_and_Unicon | Icon and Unicon |
#include <string.h>
#include "icall.h" // a header routine from the Unicon sources - provides helpful type-conversion macros
int strdup_wrapper (int argc, descriptor *argv)
{
ArgString (1); // check that the first argument is a string
RetString (strdup (StringVal(argv[1]))); // call strdup, convert and return result
}
// and strcat, for a result that does not equal the input
int strcat_wrapper (int argc, descriptor *argv)
{
ArgString (1);
ArgString (2);
char * result = strcat (StringVal(argv[1]), StringVal(argv[2]));
RetString (result);
}
|
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
| #J | J | require 'dll'
strdup=: 'msvcrt.dll _strdup >x *' cd <
free=: 'msvcrt.dll free n x' cd <
getstr=: free ] memr@,&0 _1 |
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.
| #Batch_File | Batch File |
:: http://rosettacode.org/wiki/Call_a_function
:: Demonstrate the different syntax and semantics provided for calling a function.
@echo off
echo Calling myFunction1
call:myFunction1
echo.
echo Calling myFunction2 11 8
call:myFunction2 11 8
echo.
echo Calling myFunction3 /fi and saving the output into %%filecount%%
call:myFunction3 /fi
echo.%filecount%
echo.
echo Calling myFunction4 1 2 3 4 5
call:myFunction4 1 2 3 4 5
echo.
echo Calling myFunction5 "filename=test.file" "filepath=C:\Test Directory\"
call:myFunction5 "filename=test.file" "filepath=C:\Test Directory\"
echo.
echo Calling myFunction5 "filepath=C:\Test Directory\" "filename=test.file"
call:myFunction5 "filepath=C:\Test Directory\" "filename=test.file"
echo.
pause>nul
exit
:: Requires no arguments
:myFunction1
echo myFunction1 has been called.
goto:eof
:: Fixed number of arguments (%a% & %b%)
:myFunction2
:: Returns %a% + %b%
setlocal
set /a c=%~1+%~2
endlocal & echo %c%
goto:eof
:: Optional arguments
:myFunction3
:: Returns the amount of folders + files in the current directory
:: /fi Returns only file count
:: /fo Returns only folder count
setlocal
set count=0
if "%~1"=="" set "command=dir /b"
if "%~1"=="/fi" set "command=dir /b /A-d"
if "%~1"=="/fo" set "command=dir /b /Ad"
for /f "usebackq" %%i in (`%command%`) do set /a count+=1
endlocal & set filecount=%count%
goto:eof
:: Variable number of arguments
:myFunction4
:: Returns sum of arguments
setlocal
:myFunction4loop
set sum=0
for %%i in (%*) do set /a sum+=%%i
endlocal & echo %sum%
goto:eof
:: Named Arguments (filepath=[path] & filename=[name])
:myFunction5
:: Returns the complete path based off the 2 arguments
if "%~1"=="" then goto:eof
setlocal enabledelayedexpansion
set "param=%~1"
for /l %%i in (1,1,2) do (
for /f "tokens=1,2 delims==" %%j in ("!param!") do set %%j=%%k
set "param=%~2"
)
endlocal & echo.%filepath%%filename%
goto:eof
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Lua | Lua | local WIDTH = 81
local HEIGHT = 5
local lines = {}
function cantor(start, length, index)
-- must be local, or only one side will get calculated
local seg = math.floor(length / 3)
if 0 == seg then
return nil
end
-- remove elements that are not in the set
for it=0, HEIGHT - index do
i = index + it
for jt=0, seg - 1 do
j = start + seg + jt
pos = WIDTH * i + j
lines[pos] = ' '
end
end
-- left side
cantor(start, seg, index + 1)
-- right side
cantor(start + seg * 2, seg, index + 1)
return nil
end
-- initialize the lines
for i=0, WIDTH * HEIGHT do
lines[i] = '*'
end
-- calculate
cantor(0, WIDTH, 1)
-- print the result sets
for i=0, HEIGHT-1 do
beg = WIDTH * i
for j=beg, beg+WIDTH-1 do
if j <= WIDTH * HEIGHT then
io.write(lines[j])
end
end
print()
end |
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
| #Scheme | Scheme | ; Create a terminating Continued Fraction generator for the given rational number.
; Returns one term per call; returns #f when no more terms remaining.
(define make-continued-fraction-gen
(lambda (rat)
(let ((num (numerator rat)) (den (denominator rat)))
(lambda ()
(if (= den 0)
#f
(let ((ret (quotient num den))
(rem (modulo num den)))
(set! num den)
(set! den rem)
ret))))))
; Return the continued fraction representation of a rational number as a list of terms.
(define rat->cf-list
(lambda (rat)
(let ((cf (make-continued-fraction-gen rat))
(lst '()))
(let loop ((term (cf)))
(when term
(set! lst (append lst (list term)))
(loop (cf))))
lst)))
; Enforce the length of the given continued fraction list to be odd.
; Changes the list in situ (if needed), and returns its possibly changed value.
(define continued-fraction-list-enforce-odd-length!
(lambda (cf)
(when (even? (length cf))
(let ((cf-last-cons (list-tail cf (1- (length cf)))))
(set-car! cf-last-cons (1- (car cf-last-cons)))
(set-cdr! cf-last-cons (cons 1 '()))))
cf)) |
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
| #Tcl | Tcl | proc co9 {x} {
while {[string length $x] > 1} {
set x [tcl::mathop::+ {*}[split $x ""]]
}
return $x
}
# Extended to the general case
proc coBase {x {base 10}} {
while {$x >= $base} {
for {set digits {}} {$x} {set x [expr {$x / $base}]} {
lappend digits [expr {$x % $base}]
}
set x [tcl::mathop::+ {*}$digits]
}
return $x
}
# Simple helper
proc percent {part whole} {format "%.2f%%" [expr {($whole - $part) * 100.0 / $whole}]}
puts "In base 10..."
set satisfying {}
for {set i 1} {$i < 100} {incr i} {
if {[co9 $i] == [co9 [expr {$i*$i}]]} {
lappend satisfying $i
}
}
puts $satisfying
puts "Trying [llength $satisfying] numbers instead of 99 numbers saves [percent [llength $satisfying] 99]"
puts "In base 16..."
set satisfying {}
for {set i 1} {$i < 256} {incr i} {
if {[coBase $i 16] == [coBase [expr {$i*$i}] 16]} {
lappend satisfying $i
}
}
puts $satisfying
puts "Trying [llength $satisfying] numbers instead of 255 numbers saves [percent [llength $satisfying] 255]" |
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
| #Rust | Rust |
fn is_prime(n: i64) -> bool {
if n > 1 {
(2..((n / 2) + 1)).all(|x| n % x != 0)
} else {
false
}
}
// The modulo operator actually calculates the remainder.
fn modulo(n: i64, m: i64) -> i64 {
((n % m) + m) % m
}
fn carmichael(p1: i64) -> Vec<(i64, i64, i64)> {
let mut results = Vec::new();
if !is_prime(p1) {
return results;
}
for h3 in 2..p1 {
for d in 1..(h3 + p1) {
if (h3 + p1) * (p1 - 1) % d != 0 || modulo(-p1 * p1, h3) != d % h3 {
continue;
}
let p2 = 1 + ((p1 - 1) * (h3 + p1) / d);
if !is_prime(p2) {
continue;
}
let p3 = 1 + (p1 * p2 / h3);
if !is_prime(p3) || ((p2 * p3) % (p1 - 1) != 1) {
continue;
}
results.push((p1, p2, p3));
}
}
results
}
fn main() {
(1..62)
.filter(|&x| is_prime(x))
.map(carmichael)
.filter(|x| !x.is_empty())
.flat_map(|x| x)
.inspect(|x| println!("{:?}", x))
.count(); // Evaluate entire iterator
}
|
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isPrime (in integer: number) is func
result
var boolean: prime is FALSE;
local
var integer: upTo is 0;
var integer: testNum is 3;
begin
if number = 2 then
prime := TRUE;
elsif odd(number) and number > 2 then
upTo := sqrt(number);
while number rem testNum <> 0 and testNum <= upTo do
testNum +:= 2;
end while;
prime := testNum > upTo;
end if;
end func;
const proc: main is func
local
var integer: p1 is 0;
var integer: h3 is 0;
var integer: g is 0;
var integer: d is 0;
var integer: p2 is 0;
var integer: p3 is 0;
begin
for p1 range 2 to 61 do
if isPrime(p1) then
for h3 range 2 to p1 do
g := h3 + p1;
for d range 1 to pred(g) do
if (g * pred(p1)) mod d = 0 and -p1 ** 2 mod h3 = d mod h3 then
p2 := 1 + pred(p1) * g div d;
if isPrime(p2) then
p3 := 1 + p1 * p2 div h3;
if isPrime(p3) and (p2 * p3) mod pred(p1) = 1 then
writeln(p1 <& " * " <& p2 <& " * " <& p3 <& " = " <& p1*p2*p3);
end if;
end if;
end if;
end for;
end for;
end if;
end for;
end func; |
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
| #min | min | (1 2 3 4) 0 '+ reduce puts! ; sum
(1 2 3 4) 1 '* reduce puts! ; product |
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
| #Modula-2 | Modula-2 | MODULE Catamorphism;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
(* Alas, there are no generic types. This function works for
CARDINAL only - you would have to copy it and change the types
to reduce functions of other types. *)
TYPE Reduction = PROCEDURE (CARDINAL, CARDINAL): CARDINAL;
PROCEDURE reduce(func: Reduction;
arr: ARRAY OF CARDINAL;
first: CARDINAL): CARDINAL;
VAR i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(arr) DO
first := func(first, arr[i]);
END;
RETURN first;
END reduce;
(* Demonstration *)
PROCEDURE add(a,b: CARDINAL): CARDINAL;
BEGIN RETURN a+b; END add;
PROCEDURE mul(a,b: CARDINAL): CARDINAL;
BEGIN RETURN a*b; END mul;
PROCEDURE Demonstration;
VAR a: ARRAY [1..5] OF CARDINAL;
i: CARDINAL;
BEGIN
FOR i := 1 TO 5 DO a[i] := i; END;
WriteString("Sum of [1..5]: ");
WriteCard(reduce(add, a, 0), 3);
WriteLn;
WriteString("Product of [1..5]: ");
WriteCard(reduce(mul, a, 1), 3);
WriteLn;
END Demonstration;
BEGIN Demonstration;
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
| #SenseTalk | SenseTalk |
set dog to "Benjamin"
set Dog to "Samba"
set DOG to "Bernie"
put !"There is just one dog named [[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
| #SETL | SETL | dog := 'Benjamin';
Dog := 'Samba';
DOG := 'Bernie';
print( 'There is just one dog named', 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
| #Sidef | Sidef | var dog = 'Benjamin';
var Dog = 'Samba';
var DOG = 'Bernie';
say "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}
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def cart
( ) var res
-1 get var ta -1 del
-1 get var he -1 del
ta "" != he "" != and if
he len nip for
he swap get var h drop
ta len nip for
ta swap get var t drop
( h t ) flatten res swap 0 put var res
endfor
endfor
len if res 0 put cart endif
endif
enddef
/# ---------- MAIN ---------- #/
( ( 1 2 ) ( 3 4 ) ) cart
drop res print nl nl
( ( 1776 1789 ) ( 7 12 ) ( 4 14 23 ) ( 0 1 ) ) cart
drop res print nl nl
( ( 1 2 3 ) ( 30 ) ( 500 100 ) ) cart
drop res print nl nl
( ( 1 2 ) ( ) ) cart
drop res print nl nl |
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
| #Euphoria | Euphoria | --Catalan number task from Rosetta Code wiki
--User:Lnettnay
--function from factorial task
function factorial(integer n)
atom f = 1
while n > 1 do
f *= n
n -= 1
end while
return f
end function
function catalan(integer n)
atom numerator = factorial(2 * n)
atom denominator = factorial(n+1)*factorial(n)
return numerator/denominator
end function
for i = 0 to 15 do
? catalan(i)
end for |
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.
| #Quackery | Quackery | ( ---------------- zen object orientation -------------- )
[ immovable
]this[ swap do ]done[ ] is object ( --> )
[ ]'[ ] is method ( --> [ )
[ method
[ dup share
swap put ] ] is localise ( --> [ )
[ method [ release ] ] is delocalise ( --> [ )
( -------------- example: counter methods -------------- )
( to create a counter object, use:
"[ object 0 ] is 'name' ( [ --> )" )
[ method
[ 0 swap replace ] ] is reset-counter ( --> [ )
[ method
[ 1 swap tally ] ] is increment-counter ( --> [ )
[ method [ share ] ] is report-counter ( --> [ )
( -------------------- demonstration ------------------- )
say 'Creating counter object: "mycounter".' cr cr
[ object 0 ] is mycounter ( [ --> )
say "Initial value of mycounter: "
report-counter mycounter echo cr cr
say "Incrementing mycounter three times." cr
3 times [ increment-counter mycounter ]
say "Current value of mycounter: "
report-counter mycounter echo cr cr
say "Localising mycounter." cr cr
localise mycounter
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say " Resetting mycounter." cr
reset-counter mycounter
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say " Incrementing mycounter six times." cr
6 times [ increment-counter mycounter ]
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say "Delocalising mycounter." cr cr
delocalise mycounter
say "Current value of mycounter: "
report-counter mycounter echo cr cr
say "Resetting mycounter." cr
reset-counter mycounter
say "Current value of mycounter: "
report-counter mycounter echo cr cr |
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.
| #Racket | Racket | #lang racket/gui
(define timer (new timer%))
(send timer start 100) |
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.
| #Raku | Raku | class Thing {
method regular-example() { say 'I haz a method' }
multi method multi-example() { say 'No arguments given' }
multi method multi-example(Str $foo) { say 'String given' }
multi method multi-example(Int $foo) { say 'Integer given' }
};
# 'new' is actually a method, not a special keyword:
my $thing = Thing.new;
# No arguments: parentheses are optional
$thing.regular-example;
$thing.regular-example();
$thing.multi-example;
$thing.multi-example();
# Arguments: parentheses or colon required
$thing.multi-example("This is a string");
$thing.multi-example: "This is a string";
$thing.multi-example(42);
$thing.multi-example: 42;
# Indirect (reverse order) method call syntax: colon required
my $foo = new Thing: ;
multi-example $thing: 42;
|
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.
| #Racket | Racket | #lang racket
(require ffi/unsafe)
(define libm (ffi-lib "libm")) ; get a handle for the C math library
; look up sqrt in the math library. if we can't find it, return the builtin sqrt
(define extern-sqrt (get-ffi-obj 'sqrt libm (_fun _double -> _double)
(lambda () sqrt))) |
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.
| #Raku | Raku | use NativeCall;
sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
sub XCloseDisplay(int64 $i --> int32) is native('X11') {*}
if try my $d = XOpenDisplay ":0.0" {
say "ID = $d";
XCloseDisplay($d);
}
else {
say "No X11 library!";
say "Use this window instead --> ⬜";
} |
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
| #Factor | Factor | USING: assocs formatting grouping io kernel lists lists.lazy
math math.functions math.primes.factors prettyprint
project-euler.common sequences ;
MEMO: brilliant? ( n -- ? )
factors [ length 2 = ] keep
[ number-length ] map all-eq? and ;
: lbrilliant ( -- list )
2 lfrom [ brilliant? ] lfilter 1 lfrom lzip ;
: first> ( m -- n )
lbrilliant swap '[ first _ >= ] lfilter car ;
: .first> ( n -- )
dup first> first2
"First brilliant number >= %7d: %7d at position %5d\n"
printf ;
100 lbrilliant ltake list>array keys 10 group simple-table. nl
{ 1 2 3 4 5 6 } [ 10^ .first> ] each |
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
| #Go | Go | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
} |
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
| #Action.21 | Action! | DEFINE DIGNUM="4"
TYPE Score=[BYTE bulls,cows,err]
PROC Generate(CHAR ARRAY secret)
DEFINE DIGCOUNT="9"
CHAR ARRAY digits(DIGCOUNT)
BYTE i,j,d,tmp,count
FOR i=0 TO DIGCOUNT-1
DO
digits(i)=i+'1
OD
secret(0)=DIGNUM
count=DIGCOUNT
FOR i=1 TO DIGNUM
DO
d=Rand(count)
secret(i)=digits(d)
count==-1
digits(d)=digits(count)
OD
RETURN
PROC CheckScore(CHAR ARRAY code,guess Score POINTER res)
BYTE i,j
res.bulls=0
res.cows=0
IF guess(0)#DIGNUM THEN
res.err=1
RETURN
FI
res.err=0
FOR i=1 TO DIGNUM
DO
IF guess(i)=code(i) THEN
res.bulls==+1
ELSE
FOR j=1 TO DIGNUM
DO
IF j#i AND guess(j)=code(i) THEN
res.cows==+1
EXIT
FI
OD
FI
OD
RETURN
PROC Main()
CHAR ARRAY code(DIGNUM+1),guess(255)
Score res
Generate(code)
PrintE("Bull and cows game.") PutE()
Print("I choose a 4-digit number from digits 1 to 9 without repetition. ")
PrintE("Your goal is to guess it.") PutE()
PrintE("Enter your guess:")
DO
InputS(guess)
CheckScore(code,guess,res)
Put(28) ;cursor up
PrintF("%S -> ",guess)
IF res.err THEN
Print("Wrong input")
ELSE
PrintF("Bulls=%B Cows=%B",res.bulls,res.cows)
IF res.bulls=DIGNUM THEN
PutE() PutE()
PrintE("You win!")
EXIT
FI
FI
PrintE(", try again:")
OD
RETURN |
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
| #Groovy | Groovy | 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)
}
Collections.sort(table)
StringBuilder sb = new StringBuilder()
for (String str : table) {
sb.append(str[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[i] = r[i] + table[i]
}
Collections.sort(table)
}
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, "|")
}
static void main(String[] args) {
List<String> tests = new ArrayList<>()
tests.add("banana")
tests.add("appellee")
tests.add("dogwood")
tests.add("TO BE OR NOT TO BE OR WANT TO BE OR NOT?")
tests.add("SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES")
tests.add("\u0002ABC\u0003")
for (String test : tests) {
println(makePrintable(test))
print(" --> ")
String t = ""
try {
t = bwt(test)
println(makePrintable(t))
} catch (IllegalArgumentException e) {
println("ERROR: " + e.getMessage())
}
String r = ibwt(t)
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
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
program caesar: BEGIN
MODE MODXXVI = SHORT SHORT INT; # MOD26 #
PROC to m26 = (CHAR c, offset)MODXXVI:
BEGIN
ABS c - ABS offset
END #to m26#;
PROC to char = (MODXXVI value, CHAR offset)CHAR:
BEGIN
REPR ( ABS offset + value MOD 26 )
END #to char#;
PROC encrypt = (STRING plain, MODXXVI key)STRING:
BEGIN
[UPB plain]CHAR ciph;
FOR i TO UPB plain DO
CHAR c = plain[i];
ciph[i]:=
IF "A" <= c AND c <= "Z" THEN
to char(to m26(c, "A")+key, "A")
ELIF "a" <= c AND c <= "z" THEN
to char(to m26(c, "a")+key, "a")
ELSE
c
FI
OD;
ciph
END #encrypt#;
# caesar main program #
STRING text := "The five boxing wizards jump quickly" # OR read string #;
MODXXVI key := 3; # Default key from "Bello Gallico" #
printf(($gl$, "Plaintext ------------>" + text));
text := encrypt(text, key);
printf(($gl$, "Ciphertext ----------->" + text));
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))
END #caesar# |
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
| #Commodore_BASIC | Commodore BASIC |
100 REM COMPUTE E VIA INVERSE FACTORIAL SUM
110 N = 11:REM NUMBER OF ITERATIONS
120 E = 1:REM APPROXIMATE E HERE
130 F = 1:REM BUILD FACTORIAL HERE
140 FOR I = 1 TO N
150 : F = F*I
160 : E = E + 1/F
170 NEXT I
180 PRINT "AFTER" N "ITERATIONS, E =" E |
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
| #Common_Lisp | Common Lisp | (ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(defparameter *iterations* 1000)
(let ((e 1) (f 1))
(loop for i from 1 to *iterations* doing
(setq f (* f i))
(setq e (+ e (/ 1 f))))
(format t "After ~a iterations, e = " *iterations*)
(print-r e 2570)) |
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)
| #Common_Lisp | Common Lisp |
(defun random-number ()
(do* ((lst '(1 2 3 4 5 6 7 8 9) (remove d lst))
(l 9 (length lst))
(d (nth (random l) lst) (nth (random l) lst))
(number nil (cons d number)))
((= l 5) number)))
(defun validp (number)
(loop for el in number with rst = (rest number)
do (cond ((= el 0) (return-from validp nil))
((member el rst) (return-from validp nil))
(t (setq rst (rest rst))))
finally (return number)))
(defun bulls (number guess)
(loop for x in number
for y in guess
counting (= x y) into b
finally (return b)))
(defun bulls+cows (number guess)
(loop for x in guess
counting (member x number) into c
finally (return c)))
(defun solve ()
(let ((number (random-number))
(possible-guesses (loop for i from 1234 to 9876
when (validp (map 'list #'digit-char-p (prin1-to-string i))) collect it)))
(format t "Secret: ~a~%" number)
(loop with guess = (nth (random (length possible-guesses)) possible-guesses)
with b = (bulls number guess)
with c = (- (bulls+cows number guess) b)
do (format t "Guess: ~a B: ~a C: ~a~%" guess b c)
(if (= b 4)
(return-from solve (format t "Solution found!")))
(setq possible-guesses (mapcan #'(lambda (x) (if (and (= b (bulls x guess))
(= c (- (bulls+cows x guess) b)))
(list x)))
(remove guess possible-guesses)))
(setq guess (nth (random (length possible-guesses)) possible-guesses))
(setq b (bulls number guess))
(setq c (- (bulls+cows number guess) b)))))
|
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.
| #D | D | IMPORT STD.STDIO, STD.DATETIME, STD.STRING, STD.CONV,
STD.ALGORITHM, STD.ARRAY;
VOID PRINT_CALENDAR(IN UINT YEAR, IN UINT COLS)
IN {
ASSERT(COLS > 0 && COLS <= 12);
} BODY {
STATIC ENUM CAMEL_CASE = (STRING[] PARTS) PURE =>
PARTS[0] ~ PARTS[1 .. $].MAP!CAPITALIZE.JOIN;
IMMUTABLE ROWS = 12 / COLS + (12 % COLS != 0);
MIXIN("AUTO DATE = " ~ "DATE(YEAR, 1, 1);".CAPITALIZE);
ENUM STRING S1 = CAMEL_CASE("DAY OF WEEK".SPLIT);
MIXIN(FORMAT("AUTO OFFS = CAST(INT)DATE.%S;", S1));
CONST MONTHS = "JANUARY FEBRUARY MARCH APRIL MAY JUNE
JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER"
.SPLIT.MAP!CAPITALIZE.ARRAY;
STRING[8][12] MONS;
FOREACH (IMMUTABLE M; 0 .. 12) {
MONS[M][0] = MONTHS[M].CENTER(21);
MONS[M][1] = " " ~ "SU MO TU WE TH FR SA"
.SPLIT.MAP!CAPITALIZE.JOIN(" ");
ENUM STRING S2 = CAMEL_CASE("DAYS IN MONTH".SPLIT);
MIXIN(FORMAT("IMMUTABLE DIM = DATE.%S;", S2));
FOREACH (IMMUTABLE D; 1 .. 43) {
IMMUTABLE DAY = D > OFFS && D <= OFFS + DIM;
IMMUTABLE STR = DAY ? FORMAT(" %2S", D-OFFS) : " ";
MONS[M][2 + (D - 1) / 7] ~= STR;
}
OFFS = (OFFS + DIM) % 7;
DATE.ADD!"MONTHS"(1);
}
FORMAT("[%S %S]", "SNOOPY".CAPITALIZE, "PICTURE".CAPITALIZE)
.CENTER(COLS * 24 + 4).WRITELN;
WRITELN(YEAR.TEXT.CENTER(COLS * 24 + 4), "\N");
FOREACH (IMMUTABLE R; 0 .. ROWS) {
STRING[8] S;
FOREACH (IMMUTABLE C; 0 .. COLS) {
IF (R * COLS + C > 11)
BREAK;
FOREACH (IMMUTABLE I, LINE; MONS[R * COLS + C])
S[I] ~= FORMAT(" %S", LINE);
}
WRITEFLN("%-(%S\N%)\N", S);
}
}
STATIC THIS() {
PRINT_CALENDAR(1969, 3);
} |
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
| #Java | Java | public class JNIDemo
{
static
{ System.loadLibrary("JNIDemo"); }
public static void main(String[] args)
{
System.out.println(callStrdup("Hello World!"));
}
private static native String callStrdup(String s);
} |
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.
| #BBC_BASIC | BBC BASIC | PRINT SQR(2) |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Graphics[MeshPrimitives[CantorMesh[#],1]/.{x_}:>{x,-0.05#}&/@Range[5],ImageSize->600] |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Modula-2 | Modula-2 | MODULE Cantor;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
CONST
WIDTH = 81;
HEIGHT = 5;
VAR
lines : ARRAY[0..HEIGHT] OF ARRAY[0..WIDTH] OF CHAR;
PROCEDURE Init;
VAR i,j : CARDINAL;
BEGIN
FOR i:=0 TO HEIGHT DO
FOR j:=0 TO WIDTH DO
lines[i,j] := '*'
END
END
END Init;
PROCEDURE Cantor(start,len,index : CARDINAL);
VAR i,j,seg : CARDINAL;
BEGIN
seg := len DIV 3;
IF seg=0 THEN RETURN END;
FOR i:=index TO HEIGHT-1 DO
j := start+seg;
FOR j:=start+seg TO start+seg*2-1 DO
lines[i,j] := ' '
END
END;
Cantor(start, seg, index+1);
Cantor(start+seg*2, seg, index+1)
END Cantor;
PROCEDURE Print;
VAR i,j : CARDINAL;
BEGIN
FOR i:=0 TO HEIGHT-1 DO
FOR j:=0 TO WIDTH-1 DO
Write(lines[i,j])
END;
WriteLn
END
END Print;
BEGIN
Init;
Cantor(0,WIDTH,1);
Print;
ReadChar;
END Cantor. |
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
| #Sidef | Sidef | func calkin_wilf(n) is cached {
return 1 if (n == 1)
1/(2*floor(__FUNC__(n-1)) + 1 - __FUNC__(n-1))
}
func r2cw(r) {
var cfrac = r.as_cfrac
cfrac.len.is_odd || return nil
Num(cfrac.flip.map_kv {|k,v| (k.is_odd ? '0' : '1') * v }.join, 2)
}
with (20) {|n|
say "First #{n} terms of the Calkin-Wilf sequence:"
say calkin_wilf.map(1..n)
}
with (83116/51639) {|r|
say ("\n#{r.as_rat} is at index: ", r2cw(r))
} |
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
| #Vlang | Vlang | import math.fractions
import math
import strconv
fn calkin_wilf(n int) []fractions.Fraction {
mut cw := []fractions.Fraction{len: n+1}
cw[0] = fractions.fraction(1, 1)
one := fractions.fraction(1, 1)
two := fractions.fraction(2, 1)
for i in 1..n {
mut t := cw[i-1]
mut f := t.f64()
f = math.floor(f)
t = fractions.approximate(f)
t*=two
t-= cw[i-1]
t+=one
t=t.reciprocal()
cw[i] = t
}
return cw
}
fn to_continued(r fractions.Fraction) []int {
idx := r.str().index('/') or {0}
mut a := r.str()[..idx].i64()
mut b := r.str()[idx+1..].i64()
mut res := []int{}
for {
res << int(a/b)
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := res.len
if le%2 == 0 { // ensure always odd
res[le-1]--
res << 1
}
return res
}
fn get_term_number(cf []int) ?int {
mut b := ""
mut d := "1"
for n in cf {
b = d.repeat(n)+b
if d == "1" {
d = "0"
} else {
d = "1"
}
}
i := strconv.parse_int(b, 2, 64)?
return int(i)
}
fn commatize(n int) string {
mut s := "$n"
if n < 0 {
s = s[1..]
}
le := s.len
for i := le - 3; i >= 1; i -= 3 {
s = s[0..i] + "," + s[i..]
}
if n >= 0 {
return s
}
return "-" + s
}
fn main() {
cw := calkin_wilf(20)
println("The first 20 terms of the Calkin-Wilf sequnence are:")
for i := 1; i <= 20; i++ {
println("${i:2}: ${cw[i-1]}")
}
println('')
r := fractions.fraction(83116, 51639)
cf := to_continued(r)
tn := get_term_number(cf) or {0}
println("$r is the ${commatize(tn)}th term of the sequence.")
} |
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
Console.WriteLine("]")
End Sub
Function CastOut(base As Integer, start As Integer, last As Integer) As List(Of Integer)
Dim ran = Enumerable.Range(0, base - 1).Where(Function(y) y Mod (base - 1) = (y * y) Mod (base - 1)).ToArray()
Dim x = start \ (base - 1)
Dim result As New List(Of Integer)
While True
For Each n In ran
Dim k = (base - 1) * x + n
If k < start Then
Continue For
End If
If k > last Then
Return result
End If
result.Add(k)
Next
x += 1
End While
Return result
End Function
Sub Main()
Print(CastOut(16, 1, 255))
Print(CastOut(10, 1, 99))
Print(CastOut(17, 1, 288))
End Sub
End Module |
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
| #Sidef | Sidef | func forprimes(a, b, callback) {
for (a = (a-1 -> next_prime); a <= b; a.next_prime!) {
callback(a)
}
}
forprimes(3, 61, func(p) {
for h3 in (2 ..^ p) {
var ph3 = (p + h3)
for d in (1 ..^ ph3) {
((-p * p) % h3) != (d % h3) && next
((p-1) * ph3) % d && next
var q = 1+((p-1) * ph3 / d)
q.is_prime || next
var r = 1+((p*q - 1)/h3)
r.is_prime || next
(q*r) % (p-1) == 1 || next
printf("%2d x %5d x %5d = %s\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
| #Nemerle | Nemerle | def seq = [1, 4, 6, 3, 7];
def sum = seq.Fold(0, _ + _); // Fold takes an initial value and a function, here the + operator |
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
| #Nim | Nim | import sequtils
block:
let
numbers = @[5, 9, 11]
addition = foldl(numbers, a + b)
substraction = foldl(numbers, a - b)
multiplication = foldl(numbers, a * b)
words = @["nim", "is", "cool"]
concatenation = foldl(words, a & b)
block:
let
numbers = @[5, 9, 11]
addition = foldr(numbers, a + b)
substraction = foldr(numbers, a - b)
multiplication = foldr(numbers, a * b)
words = @["nim", "is", "cool"]
concatenation = foldr(words, 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
| #Simula | Simula | begin
text dog;
dog :- blanks( 8 );
dog := "Benjamin";
Dog := "Samba";
DOG := "Bernie";
outtext( "There is just one dog, named " );
outtext( dog );
outimage
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
| #Smalltalk | Smalltalk | |dog Dog DOG|
dog := 'Benjamin'.
Dog := 'Samba'.
DOG := 'Bernie'.
( 'The three dogs are named %1, %2 and %3' %
{ dog . Dog . DOG } ) displayNl. |
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
| #SNOBOL4 | SNOBOL4 | DOG = 'Benjamin'
Dog = 'Samba'
dog = 'Bernie'
OUTPUT = 'The three dogs are named ' DOG ', ' Dog ', and ' 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}
| #PicoLisp | PicoLisp | (de 2lists (L1 L2)
(mapcan
'((I)
(mapcar
'((A) ((if (atom A) list cons) I A))
L2 ) )
L1 ) )
(de reduce (L . @)
(ifn (rest) L (2lists L (apply reduce (rest)))) )
(de cartesian (L . @)
(and L (rest) (pass reduce L)) )
(println
(cartesian (1 2)) )
(println
(cartesian NIL (1 2)) )
(println
(cartesian (1 2) (3 4)) )
(println
(cartesian (3 4) (1 2)) )
(println
(cartesian (1776 1789) (7 12) (4 14 23) (0 1)) )
(println
(cartesian (1 2 3) (30) (500 100)) )
(println
(cartesian (1 2 3) NIL (500 100)) ) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #F.23 | F# |
Seq.unfold(fun (c,n) -> let cc = 2*(2*n-1)*c/(n+1) in Some(c,(cc,n+1))) (1,1) |> Seq.take 15 |> Seq.iter (printf "%i, ")
|
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.
| #Ring | Ring |
new point { print() }
Class Point
x = 10 y = 20 z = 30
func print see x + nl + y + nl + z + nl
|
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.
| #Ruby | Ruby | # Class method
MyClass.some_method(some_parameter)
# Class may be computed at runtime
foo = MyClass
foo.some_method(some_parameter)
# Instance method
my_instance.a_method(some_parameter)
# The parentheses are optional
my_instance.a_method some_parameter
# Calling a method with no parameters
my_instance.another_method |
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.
| #Rust | Rust | struct Foo;
impl Foo {
// implementation of an instance method for struct Foo
// returning the answer to life
fn get_the_answer_to_life(&self) -> i32 {
42
}
// implementation of a static method for struct Foo
// returning a new instance object
fn new() -> Foo {
println!("Hello, world!");
Foo // returning the new Foo object
}
}
fn main() {
// create the instance object foo,
// by calling the static method new of struct Foo
let foo = Foo::new();
// get the answer to life
// by calling the instance method of object foo
println!("The answer to life is {}.", foo.get_the_answer_to_life());
// Note that in Rust, methods still work on references to the object.
// Rust will automatically do the appropriate dereferencing to get the method to work:
let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
} |
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.
| #REXX | REXX | /*REXX program calls a function (sysTextScreenSize) in a shared library (regUtil). */
/*Note: the REGUTIL.DLL (REGina UTILity Dynamic Link Library */
/* should be in the PATH or the current directory. */
rca= rxFuncAdd('sysLoadFuncs', "regUtil", 'sysLoadFuncs') /*add a function library. */
if rca\==0 then do /*examine the return code.*/
say 'return code' rca "from rxFuncAdd" /*tell about bad " " */
exit rca /*exit this program with RC. */
end
rcl= sysLoadFuncs() /*we can load the functions. */
if rcl\==0 then do /*examine the return code.*/
say 'return code' rcl "from sysLoadFuncs" /*tell about bad " " */
exit rcl /*exit this program with RC. */
end
/* [↓] call a function. */
$= sysTextScreenSize() /*$ has 2 words: rows cols */
parse var $ rows cols . /*get two numeric words in $.*/
say ' rows=' rows /*show number of screen rows.*/
say ' cols=' cols /* " " " " cols.*/
rcd= SysDropFuncs() /*make functions inaccessible*/
if rcd\==0 then do /*examine the return code.*/
say 'return code' rcd "from sysDropFuncs" /*tell about bad " " */
exit rcd /*exit this program with RC. */
end
exit 0 /*stick a fork in it, we're all done. */ |
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.
| #Ruby | Ruby | require 'fiddle/import'
module FakeImgLib
extend Fiddle::Importer
begin
dlload './fakeimglib.so'
extern 'int openimage(const char *)'
rescue Fiddle::DLError
# Either fakeimglib or openimage() is missing.
@@handle = -1
def openimage(path)
$stderr.puts "internal openimage opens #{path}\n"
@@handle += 1
end
module_function :openimage
end
end
handle = FakeImgLib.openimage("path/to/image")
puts "opened with handle #{handle}" |
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
| #Haskell | Haskell | import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf, splitWhen)
import Data.Numbers.Primes (primeFactors)
import Text.Printf (printf)
-------------------- BRILLIANT NUMBERS -------------------
isBrilliant :: (Integral a, Show a) => a -> Bool
isBrilliant n = case primeFactors n of
[a, b] -> length (show a) == length (show b)
_ -> False
--------------------------- TEST -------------------------
main :: IO ()
main = do
let indexedBrilliants =
zip
[1 ..]
(filter isBrilliant [1 ..])
putStrLn $
table " " $
chunksOf 10 $
show . snd
<$> take 100 indexedBrilliants
putStrLn "(index, brilliant)"
mapM_ print $
take 6 $
fmap (fst . head) $
splitWhen
(uncurry (<) . join bimap (length . show . snd))
$ zip indexedBrilliants (tail indexedBrilliants)
------------------------- DISPLAY ------------------------
table :: String -> [[String]] -> String
table gap rows =
let ws = maximum . fmap length <$> transpose rows
pw = printf . flip intercalate ["%", "s"] . show
in unlines $ intercalate gap . zipWith pw ws <$> rows |
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
| #360_Assembly | 360 Assembly | * calendar 08/06/2016
CALENDAR CSECT
USING CALENDAR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
L R4,YEAR year
SRDA R4,32 .
D R4,=F'4' year//4
LTR R4,R4 if year//4=0
BNZ LYNOT
L R4,YEAR year
SRDA R4,32 .
D R4,=F'100' year//100
LTR R4,R4 if year//100=0
BNZ LY
L R4,YEAR year
SRDA R4,32 .
D R4,=F'400' if year//400
LTR R4,R4 if year//400=0
BNZ LYNOT
LY MVC ML+2,=H'29' ml(2)=29 leapyear
LYNOT SR R10,R10 ltd1=0
LA R6,1 i=1
LOOPI1 C R6,=F'31' do i=1 to 31
BH ELOOPI1
XDECO R6,XDEC edit i
LA R14,TD1 td1
AR R14,R10 td1+ltd1
MVC 0(3,R14),XDEC+9 sub(td1,ltd1+1,3)=pic(i,3)
LA R10,3(R10) ltd1+3
LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI1 LA R6,1 i=1
LOOPI2 C R6,=F'12' do i=1 to 12
BH ELOOPI2
ST R6,M m=i
MVC D,=F'1' d=1
MVC YY,YEAR yy=year
L R4,M m
C R4,=F'3' if m<3
BNL GE3
L R2,M m
LA R2,12(R2) m+12
ST R2,M m=m+12
L R2,YY yy
BCTR R2,0 yy-1
ST R2,YY yy=yy-1
GE3 L R2,YY yy
LR R1,R2 yy
SRA R1,2 yy/4
AR R2,R1 yy+(yy/4)
L R4,YY yy
SRDA R4,32 .
D R4,=F'100' yy/100
SR R2,R5 yy+(yy/4)-(yy/100)
L R4,YY yy
SRDA R4,32 .
D R4,=F'400' yy/400
AR R2,R5 yy+(yy/4)-(yy/100)+(yy/400)
A R2,D r2=yy+(yy/4)-(yy/100)+(yy/400)+d
LA R5,153 153
M R4,M 153*m
LA R5,8(R5) 153*m+8
D R4,=F'5' (153*m+8)/5
AR R5,R2 ((153*m+8)/5+r2
LA R4,0 .
D R4,=F'7' r4=mod(r5,7) 0=sun 1=mon ... 6=sat
LTR R4,R4 if j=0
BNZ JNE0
LA R4,7 j=7
JNE0 BCTR R4,0 j-1
MH R4,=H'3' j*3
LR R10,R4 j1=j*3
LR R1,R6 i
SLA R1,1 *2
LH R11,ML-2(R1) ml(i)
MH R11,=H'3' j2=ml(i)*3
MVC TD2,BLANK td2=' '
LA R4,TD1 @td1
LR R5,R11 j2
LA R2,TD2 @td2
AR R2,R10 @td2+j1
LR R3,R5 j2
MVCL R2,R4 sub(td2,j1+1,j2)=sub(td1,1,j2)
LR R1,R6 i
MH R1,=H'144' *144
LA R14,DA-144(R1) @da(i)
MVC 0(144,R14),TD2 da(i)=td2
LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 L R1,YEAR year
XDECO R1,PG+23 edit year
XPRNT PG,35 print year
MVC WDLINE,BLANK wdline=' '
LA R10,1 lwdline=1
LA R8,1 k=1
LOOPK3 C R8,=F'3' do k=1 to 3
BH ELOOPK3
LA R4,WDLINE @wdline
AR R4,R10 +lwdline
MVC 0(20,R4),WDNA sub(wdline,lwdline+1,20)=wdna
LA R10,20(R10) lwdline=lwdline+20
C R8,=F'3' if k<3
BNL ITERK3
LA R10,2(R10) lwdline=lwdline+2
ITERK3 LA R8,1(R8) k=k+1
B LOOPK3
ELOOPK3 LA R6,1 i=1
LOOPI4 C R6,=F'12' do i=1 to 12 by 3
BH ELOOPI4
MVC MOLINE,BLANK moline=' '
LA R10,6 lmoline=6
LR R8,R6 k=i
LOOPK4 LA R2,2(R6) i+2
CR R8,R2 do k=i to i+2
BH ELOOPK4
LR R1,R8 k
MH R1,=H'10' *10
LA R3,MO-10(R1) mo(k)
LA R4,MOLINE @moline
AR R4,R10 +lmoline
MVC 0(10,R4),0(R3) sub(moline,lmoline+1,10)=mo(k)
LA R10,22(R10) lmoline=lmoline+22
LA R8,1(R8) k=k+1
B LOOPK4
ELOOPK4 XPRNT MOLINE,L'MOLINE print months
XPRNT WDLINE,L'WDLINE print days of week
LA R7,1 j=1
LOOPJ4 C R7,=F'106' do j=1 to 106 by 21
BH ELOOPJ4
MVC PG,BLANK clear buffer
LA R9,PG pgi=0
LR R8,R6 k=i
LOOPK5 LA R2,2(R6) i+2
CR R8,R2 do k=i to i+2
BH ELOOPK5
LR R1,R8 k
MH R1,=H'144' *144
LA R4,DA-144(R1) da(k)
BCTR R4,0 -1
AR R4,R7 +j
MVC 0(21,R9),0(R4) substr(da(k),j,21)
LA R9,22(R9) pgi=pgi+22
LA R8,1(R8) k=k+1
B LOOPK5
ELOOPK5 XPRNT PG,L'PG print buffer
LA R7,21(R7) j=j+21
B LOOPJ4
ELOOPJ4 LA R6,3(R6) i=i+3
B LOOPI4
ELOOPI4 L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
LTORG
YEAR DC F'1969' <==
MO DC CL10' January ',CL10' February ',CL10' March '
DC CL10' April ',CL10' May ',CL10' June '
DC CL10' July ',CL10' August ',CL10'September '
DC CL10' October ',CL10' November ',CL10' December '
ML DC H'31',H'28',H'31',H'30',H'31',H'30'
DC H'31',H'31',H'30',H'31',H'30',H'31'
WDNA DC CL20'Mo Tu We Th Fr Sa Su'
M DS F
D DS F
YY DS F
TD1 DS CL93
TD2 DS CL144
MOLINE DS CL66
WDLINE DS CL66
PG DC CL66' '
XDEC DS CL12
BLANK DC CL144' '
DA DS 12CL144
YREG
END 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.
| #ABAP | ABAP | class friendly_class definition deferred.
class my_class definition friends friendly_class .
public section.
methods constructor.
private section.
data secret type char30.
endclass.
class my_class implementation .
method constructor.
secret = 'a password'. " Instantiate secret.
endmethod.
endclass.
class friendly_class definition create public .
public section.
methods return_secret
returning value(r_secret) type char30.
endclass.
class friendly_class implementation.
method return_secret.
data lr_my_class type ref to my_class.
create object lr_my_class. " Instantiate my_class
write lr_my_class->secret. " Here's the privacy violation.
endmethod.
endclass.
|
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Bulls_And_Cows is
package Random_Natural is new Ada.Numerics.Discrete_Random (Natural);
Number : String (1..4);
begin
declare -- Generation of number
use Random_Natural;
Digit : String := "123456789";
Size : Positive := 9;
Dice : Generator;
Position : Natural;
begin
Reset (Dice);
for I in Number'Range loop
Position := Random (Dice) mod Size + 1;
Number (I) := Digit (Position);
Digit (Position..Size - 1) := Digit (Position + 1..Size);
Size := Size - 1;
end loop;
end;
loop -- Guessing loop
Put ("Enter four digits:");
declare
Guess : String := Get_Line;
Bulls : Natural := 0;
Cows : Natural := 0;
begin
if Guess'Length /= 4 then
raise Data_Error;
end if;
for I in Guess'Range loop
for J in Number'Range loop
if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then
raise Data_Error;
end if;
if Number (I) = Guess (J) then
if I = J then
Bulls := Bulls + 1;
else
Cows := Cows + 1;
end if;
end if;
end loop;
end loop;
exit when Bulls = 4;
Put_Line (Integer'Image (Bulls) & " bulls," & Integer'Image (Cows) & " cows");
exception
when Data_Error => Put_Line ("You should enter four different digits 1..9");
end;
end loop;
end Bulls_And_Cows; |
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
| #Haskell | Haskell | -- A straightforward, inefficient implementation of the Burrows–Wheeler
-- transform, based on the description in the Wikipedia article.
--
-- Special characters are *not* used to indicate the start or end of sequences,
-- so all strings can be represented.
import Data.List ((!!), find, sort, tails, transpose)
import Data.Maybe (fromJust)
import Text.Printf (printf)
newtype BWT a = BWT [Val a]
bwt :: Ord a => [a] -> BWT a
bwt xs = let n = length xs + 2
ys = transpose $ sort $ take n $ tails $ cycle $ pos xs
in BWT $ ys !! (n-1)
invBwt :: Ord a => BWT a -> [a]
invBwt (BWT xs) = let ys = iterate step (map (const []) xs) !! length xs
in unpos $ fromJust $ find ((== Post) . last) ys
where step = sort . zipWith (:) xs
data Val a = In a | Pre | Post deriving (Eq, Ord)
pos :: [a] -> [Val a]
pos xs = Pre : map In xs ++ [Post]
unpos :: [Val a] -> [a]
unpos xs = [x | In x <- xs]
main :: IO ()
main = mapM_ testBWT [ "", "a", "BANANA", "dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" ]
testBWT :: String -> IO ()
testBWT xs = let fwd = bwt xs
inv = invBwt fwd
in printf "%s\n\t%s\n\t%s\n" xs (pretty fwd) inv
where pretty (BWT ps) = map prettyVal ps
prettyVal (In c) = c
prettyVal Pre = '^'
prettyVal Post = '|' |
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
| #APL | APL |
∇CAESAR[⎕]∇
∇
[0] A←K CAESAR V
[1] A←'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
[2] ((,V∊A)/,V)←A[⎕IO+52|(2×K)+((A⍳,V)-⎕IO)~52]
[3] A←V
∇
|
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
| #D | D | import std.math;
import std.stdio;
enum EPSILON = 1.0e-15;
void main() {
ulong fact = 1;
double e = 2.0;
double e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (abs(e - e0) >= EPSILON);
writefln("e = %.15f", e);
} |
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
| #dc | dc | 1000 sn [ n = number of iterations ]sx
2574k [ precision to use during computation ]sx
1 d se sf [ set e and f to 1 ]sx
0 si [ set i to 0 ]sx
[ [ p = begin ]sx
lf li 1 + d si * sf [ f = f*(++i) ]sx
le 1 lf / + se [ e = e + 1/f ]sx
ln li <p [ if i<n recur ]sx
]sp [ end ]sx
lpx [ call p ]sx
[After ]n lnn [ output header. uses n + 10P for newline ]sx
[ iterations, e =]n [ instead of p, so nothing is left hanging ]sx
10P [ around on the stack.]sx
2570k [ now reset precision to match correct digits ]sx
le 1 / [ get result truncated to that precision ]sx
n 10P [ and print it out, again with n + 10P ]sx |
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)
| #Crystal | Crystal | size = 4
scores = [] of Tuple(Int32, Int32)
guesses = [] of Array(Char)
puts "Playing Bulls & Cows with #{size} unique digits."
possible_guesses = ('1'..'9').to_a.permutations(size).shuffle
loop do
guesses << (current_guess = possible_guesses.pop)
print "Guess #{guesses.size} (#{possible_guesses.size}) is #{current_guess.join}. Answer (bulls,cows)? "
bulls, cows = gets.not_nil!.split(',').map(&.to_i)
scores << (score = {bulls, cows})
# handle win
break (puts "Yeah!") if score == {size, 0}
# filter possible guesses
possible_guesses.select! do |guess|
bulls = guess.zip(current_guess).count { |g, cg| g == cg }
cows = size - (guess - current_guess).size - bulls
{bulls, cows} == score
end
# handle 'no possible guesses left'
if possible_guesses.empty?
puts "Error in scoring?"
guesses.zip(scores).each { |g, (b, c)| puts "#{g.join} => bulls #{b} cows #{c}" }
break
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.