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 m... | #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 m... | #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 VA... |
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 c... | #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 c... | #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 bri... | #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 #
... |
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-s... | #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("In... |
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... | #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)... |
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);
... |
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.))
;;... |
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 equ... | #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... |
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 al... | #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" ... |
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... | #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... | #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 "str... |
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
C... | #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); "";
... |
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] = ' '... |
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 ... | #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... |
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 ... | #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();
l... |
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.
Par... | #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
fo... |
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.
Par... | #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)
}
... |
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 met... | #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)
... |
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 met... | #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) % ... |
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: ... | #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: ... | #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 onl... | #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... | #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 ", ... |
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... | #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 y... | #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] = ... |
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... | #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 m... | #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 m... | #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 = ... |
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 m... | #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 explici... |
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 c... | #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 c... | #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 bri... | #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.eve... |
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 bri... | #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 (uin... |
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 random... | #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,
randloo... |
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-s... | #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-s... | #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)
... |
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... | #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)
... |
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 U... |
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 equ... | #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <time.h>
//--------------------------------------------------------------------------------------------------
using namespace std;
//---------------------------------------------------------------------------... |
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 al... | #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" ... |
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... | #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 retur... |
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... | #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
C... | #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 %%fileco... |
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
... |
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 ... | #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
... |
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.
Par... | #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::... |
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 met... | #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 =... |
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 met... | #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);
... |
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: ... | #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: ... | #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(f... |
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... | #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... | #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... | #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 y... | #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
... |
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... | #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)*factor... |
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 m... | #Quackery | Quackery | ( ---------------- zen object orientation -------------- )
[ immovable
]this[ swap do ]done[ ] is object ( --> )
[ ]'[ ] is method ( --> [ )
[ method
[ dup share
swap put ] ] is localise ( --> [ )
[ method [ release ] ] is delocali... |
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 m... | #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 m... | #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 $thin... |
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 c... | #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 c... | #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 bri... | #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 lz... |
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 bri... | #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 <= dig... |
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 random... | #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(... |
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-s... | #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 +... |
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... | #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#;... |
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 equ... | #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 ... |
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 al... | #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 /... |
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... | #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
C... | #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;
... |
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 ... | #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 Calk... |
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 ... | #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()
... |
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.
Par... | #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
... |
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 met... | #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... |
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: ... | #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: ... | #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(numbe... |
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... | #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... | #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... | #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 y... | #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
(car... |
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... | #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 m... | #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 m... | #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.anothe... |
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 m... | #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!("... |
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 c... | #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", '... |
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 c... | #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... |
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 bri... | #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 -... |
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 fo... | #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) "
... |
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... | #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... |
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 random... | #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... |
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-s... | #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... |
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... | #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 [... |
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 equ... | #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 #{curre... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.