task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to al... | #Elena | Elena | import system'text;
import system'routines;
import system'calendar;
import extensions;
import extensions'routines;
const MonthNames = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER",
"NOVEMBER","DECEMBER"};
const DayNames = new strin... |
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... | #JavaScript | JavaScript | #include <napi.h>
#include <openssl/md5.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace Napi;
Napi::Value md5sum(const Napi::CallbackInfo& info) {
std::string input = info[0].ToString();
unsigned char result[MD5_DIGEST_LENGTH];
MD5((unsigned char*)input.c_str()... |
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... | #BQN | BQN | {𝕊 ·: 1 + 1}0 |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Nim | Nim | import strutils
const
Width = 81
Height = 5
var lines: array[Height, string]
for line in lines.mitems: line = repeat('*', Width)
proc cantor(start, length, index: Natural) =
let seg = length div 3
if seg == 0: return
for i in index..<Height:
for j in (start + seg)..<(start + seg * 2):
lines[i]... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Objeck | Objeck | class CantorSet {
WIDTH : static : Int;
HEIGHT : static : Int;
lines : static : Char[,];
function : Init() ~ Nil {
WIDTH := 81;
HEIGHT := 5;
lines := Char->New[HEIGHT, WIDTH];
each(i : HEIGHT) {
each(j : WIDTH) {
lines[i,j] := '*';
};
};
}
function : Cantor(star... |
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 ... | #Wren | Wren | import "/rat" for Rat
import "/fmt" for Fmt, Conv
var calkinWilf = Fn.new { |n|
var cw = List.filled(n, null)
cw[0] = Rat.one
for (i in 1...n) {
var t = cw[i-1].floor * 2 - cw[i-1] + 1
cw[i] = Rat.one / t
}
return cw
}
var toContinued = Fn.new { |r|
var a = r.num
var b = ... |
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... | #Wren | Wren | var castOut = Fn.new { |base, start, end|
var b = base - 1
var ran = (0...b).where { |n| n % b == (n * n) % b }
var x = (start/b).floor
var result = []
while (true) {
for (n in ran) {
var k = b*x + n
if (k >= start) {
if (k > end) return result
... |
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... | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if self % i == ... |
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... | #Tcl | Tcl | proc carmichael {limit {rounds 10}} {
set carmichaels {}
for {set p1 2} {$p1 <= $limit} {incr p1} {
if {![miller_rabin $p1 $rounds]} continue
for {set h3 2} {$h3 < $p1} {incr h3} {
set g [expr {$h3 + $p1}]
for {set d 1} {$d < $h3+$p1} {incr d} {
if {(($h3+$p1)*($p1-1))%$d != 0} continue
if {(-($... |
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: ... | #Oberon-2 | Oberon-2 |
MODULE Catamorphism;
IMPORT
Object,
NPCT:Tools,
NPCT:Args,
IntStr,
Out;
TYPE
BinaryFunc= PROCEDURE (x,y: LONGINT): LONGINT;
VAR
data: POINTER TO ARRAY OF LONGINT;
i: LONGINT;
PROCEDURE Sum(x,y: LONGINT): LONGINT;
BEGIN
RETURN x + y
END Sum;
PROCEDURE Sub(x,y: LONGINT): LONGINT;
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... | #Standard_ML | Standard ML | let
val dog = "Benjamin"
val Dog = "Samba"
val DOG = "Bernie"
in
print("The three dogs are named " ^ dog ^ ", " ^ Dog ^ ", and " ^ DOG ^ ".\n")
end; |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Stata | Stata | . local dog Benjamin
. local Dog Samba
. local DOG Bernie
. display "The three dogs are named $_dog, $_Dog, and $_DOG."
The three dogs are named Benjamin, Samba, and Bernie. |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Prolog | Prolog |
product([A|_], Bs, [A, B]) :- member(B, Bs).
product([_|As], Bs, X) :- product(As, Bs, X).
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #Factor | Factor | USING: kernel math math.combinatorics prettyprint ;
: catalan ( n -- n ) [ 1 + recip ] [ 2 * ] [ nCk * ] tri ;
15 [ catalan . ] each-integer |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Scala | Scala | /* This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
class MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated.
var variable2 = "asdf" // Another instance variable; a public mutable this time
def this() = this(... |
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... | #Rust | Rust | #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
// Small macro which wraps turning a string-literal into a c-string.
// This is always safe to call, and the resulting pointer has 'static lifetime
macro_rules! to_cstr {
($s:expr... |
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... | #Scala | Scala | import net.java.dev.sna.SNA
import com.sun.jna.ptr.IntByReference
object GetDiskFreeSpace extends App with SNA {
snaLibrary = "Kernel32" // Native library name
/*
* Important Note!
*
* The val holding the SNA-returned function must have the same name as the native function itself
* (see line following this c... |
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... | #J | J | oprimes=: {{ NB. all primes of order y
p:(+i.)/-/\ p:inv +/\1 9*10^y
}}
obrill=: {{ NB. all brilliant numbers of order y primes
~.,*/~oprimes y
}}
brillseq=: {{ NB. sequences of brilliant numbers up through order y-1 primes
/:~;obrill each i.y
}} |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a bri... | #Java | Java | import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) ... |
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... | #Ada | Ada | with Ada.Calendar.Formatting;
package Printable_Calendar is
subtype String20 is String(1 .. 20);
type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20;
type Description is record
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
-- for internationalization, yo... |
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... | #Ada | Ada | package OO_Privacy is
type Confidential_Stuff is tagged private;
subtype Password_Type is String(1 .. 8);
private
type Confidential_Stuff is tagged record
Password: Password_Type := "default!"; -- the "secret"
end record;
end OO_Privacy; |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is... | #C.23 | C# | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answ... |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere wi... | #Action.21 | Action! | BYTE FUNC CheckNeighbors(CARD x BYTE y)
IF Locate(x-1,y-1)=1 THEN RETURN (1) FI
IF Locate(x,y-1)=1 THEN RETURN (1) FI
IF Locate(x+1,y-1)=1 THEN RETURN (1) FI
IF Locate(x-1,y)=1 THEN RETURN (1) FI
IF Locate(x+1,y)=1 THEN RETURN (1) FI
IF Locate(x-1,y+1)=1 THEN RETURN (1) FI
IF Locate(x,y+1)=1 THEN RETURN (... |
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... | #ALGOL_68 | ALGOL 68 | STRING digits = "123456789";
[4]CHAR chosen;
STRING available := digits;
FOR i TO UPB chosen DO
INT c = ENTIER(random*UPB available)+1;
chosen[i] := available[c];
available := available[:c-1]+available[c+1:]
OD;
COMMENT print((chosen, new line)); # Debug # END COMMENT
OP D = (INT d)STRING: whole(d,... |
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... | #J | J | NB. transform and inverse
bwt=: {:"1@:(/:~ :[:)@:(|."0 1~ -@:i.@:#)@:((2{a.) , ,&(3{a.))@:(([ ('STX or ETX invalid in input' (13!:8) 21 + 0:))^:(1 e. (2 3{a.)&e.)) :.(}.@:}:@:({~ ((3{a.) [: :i.~ {:"1))@:((,"0 1 /:~ :[:)^:(#@[)&(0$00)))
NB. demonstrate the transform
A=: <@bwt ;._2 ] 0 :0
tests[0] = "ban... |
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... | #Java | Java | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String can... |
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... | #AppleScript | AppleScript | (* Only non-accented English letters are altered here. *)
on caesarDecipher(txt, |key|)
return caesarEncipher(txt, -|key|)
end caesarDecipher
on caesarEncipher(txt, |key|)
set codePoints to id of txt
set keyPlus25 to |key| mod 26 + 25
repeat with thisCode in codePoints
tell thisCode mod 32
... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Delphi | Delphi |
program Calculating_the_value_of_e;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
EPSILON = 1.0e-15;
function fAbs(value: Extended): Extended;
begin
Result := value;
if value < 0 then
Result := -Result;
end;
function e: Extended;
var
fact: UInt64;
e, e0: Extended;
n: Integer;... |
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... | #D | D | void main() {
import std.stdio, std.random, std.algorithm, std.range, std.ascii;
immutable d9 = "123456789";
auto choices = cartesianProduct(d9, d9, d9, d9).map!(t => [t[]])
.filter!(a => a.sort().uniq.count == 4).array;
do {
const ans = choices[uniform(0, $)];
wri... |
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... | #Fortran | Fortran |
MODULE DATEGNASH
TYPE DATEBAG
INTEGER DAY,MONTH,YEAR
END TYPE DATEBAG
CHARACTER*9 MONTHNAME(12),DAYNAME(0:6)
PARAMETER (MONTHNAME = (/"JANUARY","FEBRUARY","MARCH","APRIL",
1 "MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER",
2 "DECEMBER"/))
... |
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... | #Julia | Julia | p = ccall(:strdup, Ptr{Cuchar}, (Ptr{Cuchar},), "Hello world")
@show unsafe_string(p) # "Hello world"
ccall(:free, Void, (Ptr{Cuchar},), p) |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #Kotlin | Kotlin | // Kotlin Native v0.2
import kotlinx.cinterop.*
import string.*
fun main(args: Array<String>) {
val hw = strdup ("Hello World!")!!.toKString()
println(hw)
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #Bracmat | Bracmat | aFunctionWithoutArguments$ |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Perl | Perl | use strict;
use feature 'say';
sub cantor {
our($height) = @_;
my $width = 3 ** ($height - 1);
our @lines = ('#' x $width) x $height;
sub trim_middle_third {
my($len, $start, $index) = @_;
my $seg = int $len / 3
or return;
for my $i ( $index .. $height - 1 ) {... |
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... | #zkl | zkl | fcn castOut(base=10, start=1, end=999999){
base-=1;
ran:=(0).filter(base,'wrap(n){ n%base == (n*n)%base });
result:=Sink(List);
foreach a,b in ([start/base ..],ran){ // foreach{ foreach {} }
k := base*a + b;
if (k < start) continue;
if (k > end) return(result.close());
result.write... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET Base=10
20 LET N=2
30 LET c1=0
40 LET c2=0
50 LET k=1
60 IF k>=(Base^N)-1 THEN GO TO 150
70 LET c1=c1+1
80 IF FN m(k,Base-1)=FN m(k*k,Base-1) THEN LET c2=c2+1: PRINT k;" ";
90 LET k=k+1
100 GO TO 60
150 PRINT '"Trying ";c2;" numbers instead of ";c1;" numbers saves ";100-(c2/c1)*100;"%"
160 STOP
170 DEF FN m(a,b... |
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... | #Vala | Vala | long mod(long n, long m) {
return ((n % m) + m) % m;
}
bool is_prime(long n) {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (long div = 5, inc = 2; div * div <= n;
div += inc, inc = 6 - inc)
if (n % div == 0)
return false;
return tru... |
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: ... | #Objeck | Objeck |
use Collection;
class Reducer {
function : Main(args : String[]) ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
values->Reduce(Add(Int, Int) ~ Int)->PrintLine();
values->Reduce(Mul(Int, Int) ~ Int)->PrintLine();
}
function : Add(a : Int, b : Int) ~ Int {
return a + b;
}
function : ... |
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... | #Swift | Swift | let dog = "Benjamin"
let Dog = "Samba"
let DOG = "Bernie"
println("The three dogs are named \(dog), \(Dog), and \(DOG).") |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Tcl | Tcl | set dog "Benjamin"
set Dog "Samba"
set DOG "Bernie"
puts "The three dogs are named $dog, $Dog and $DOG" |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #True_BASIC | True BASIC | LET dog$ = "Benjamin"
LET Dog$ = "Samba"
LET DOG$ = "Bernie"
PRINT "There is just one dog, named "; dog$
END |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Python | Python | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), ... |
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... | #Fantom | Fantom | class Main
{
static Int factorial (Int n)
{
Int res := 1
if (n>1)
(2..n).each |i| { res *= i }
return res
}
static Int catalanA (Int n)
{
return factorial(2*n)/(factorial(n+1) * factorial(n))
}
static Int catalanB (Int n)
{
if (n == 0)
{
return 1
}
else
... |
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... | #Sidef | Sidef | class MyClass {
method foo(arg) { say arg }
}
var arg = 42;
# Call a class method
MyClass.foo(arg);
# Alternatively, using an expression for the method name
MyClass.(:foo)(arg);
# Create an instance
var instance = MyClass();
# Instance method
instance.foo(arg);
# Alternatively, by using an expression fo... |
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... | #Smalltalk | Smalltalk | " Class "
MyClass selector: someArgument .
" or equivalently "
foo := MyClass .
foo selector: someArgument.
" Instance "
myInstance selector: someArgument.
" Message with multiple arguments "
myInstance fooWithRed:arg1 green:arg2 blue:arg3 .
" Message with no arguments "
myInstance selector.
" Binary (operator)... |
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... | #SuperCollider | SuperCollider |
SomeClass {
*someClassMethod {
}
someInstanceMethod {
}
}
SomeClass.someClassMethod;
a = SomeClass.new;
a.someInstanceMethod;
|
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Smalltalk | Smalltalk | DLD addLibrary: 'fakeimglib'.
Object subclass: ExtLib [
ExtLib class >> openimage: aString [
(CFunctionDescriptor isFunction: 'openimage')
ifTrue: [
(CFunctionDescriptor for: 'openimage'
returning: #int
withArgs: #( #string ) ) callInto: (ValueH... |
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... | #SNOBOL4 | SNOBOL4 | -INCLUDE 'ffi.sno'
ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
ffi_m_hypot = FFI_DLSYM(ffi_m, 'hypot')
DEFINE_FFI('hypot(double,double)double', ffi_m_hypot)
OUTPUT = hypot(1,2)
OUTPUT = hypot(2,3)
OUTPUT = hypot(3,4)
OUTPUT = hypot(4,5)
END |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a bri... | #Julia | Julia |
using Primes
function isbrilliant(n)
p = factor(n).pe
return (length(p) == 1 && p[1][2] == 2) ||
length(p) == 2 && ndigits(p[1][1]) == ndigits(p[2][1]) && p[1][2] == p[2][2] == 1
end
function testbrilliants()
println("First 100 brilliant numbers:")
foreach(p -> print(lpad(p[2], 5), p[1] % 2... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[PrimesDecade]
PrimesDecade[n_Integer] := Module[{bounds},
bounds = {PrimePi[10^n] + 1, PrimePi[10^(n + 1) - 1]};
Prime[Range @@ bounds]
]
ds = Union @@ Table[Union[Times @@@ Tuples[PrimesDecade[d], 2]], {d, 0, 4}];
Multicolumn[Take[ds, 100], {Automatic, 8}, Appearance -> "Horizontal"]
sel = Min /@ Ga... |
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::AllUtils <max head firstidx uniqint>;
use ntheory <primes is_semiprime forsetproduct>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ ... |
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... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC print calendar = (INT year, page width)VOID: (
[]STRING month names = (
"January","February","March","April","May","June",
"July","August","September","October","November","December"),
weekday names = ("Su","Mo","Tu","We","Th","Fr","Sa");
FORMAT weekday fmt ... |
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... | #C.2B.2B | C++ | #include <iostream>
class CWidget; // Forward-declare that we have a class named CWidget.
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget(); // Disallow t... |
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... | #Clojure | Clojure |
(ns a)
(def ^:private priv :secret)
; From REPL, in another namespace 'user':
user=> @a/priv ; fails with: IllegalStateException: var: a/priv is not public
user=> @#'a/priv ; succeeds
:secret
|
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere wi... | #Ada | Ada | with Ada.Numerics.Discrete_Random;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Brownian_Tree is
Width : constant := 800;
Height : constant := 600;
Points : constant := 50_000;
subtype Width_Range is Integer range 1 .. Width;
subtype Heigh... |
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... | #APL | APL | input ← {⍞←'Guess: ' ⋄ 7↓⍞}
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
valid ← isdigits∧4=≢
guess ← ⍎¨input⍣(valid⊣)
bulls ← +/=
cows ← +/∊∧≠
game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣)
random ← 4∘⊣?9∘⊣
moo ← 'You win!'⊣(random game⊢)
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-s... | #jq | jq | # substitute ^ for STX and | for ETX
def makePrintable:
if . == null then null
else sub("\u0002"; "^") | sub("\u0003"; "|")
end;
def bwt:
{stx: "\u0002", etx: "\u0003"} as $x
| if index($x.stx) >= 0 or index($x.etx) >= 0 then null
else $x.stx + . + $x.etx
| . as $s
| (reduce range(0; length) as ... |
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... | #Julia | Julia | bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b))
function burrowswheeler_encode(s)
if match(r"\x02|\x03", s) != nothing
throw("String for Burrows-Wheeler input cannot contain STX or ETX")
end
s = "\x02" * s * "\x03"
String([t[end] for t in bwsort([circshift([c for c in s], n) for ... |
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... | #Applesoft_BASIC | Applesoft BASIC | 100 INPUT ""; T$
110 LET K% = RND(1) * 25 + 1
120 PRINT "ENCODED WITH ";
130 GOSUB 200ENCODED
140 LET K% = 26 - K%
150 PRINT "DECODED WITH ";
160 GOSUB 200DECODED
170 END
REM ENCODED/DECODED
200 PRINT "CAESAR " K%;
210 LET K$(1) = " (ROT-13)"
220 PRINT K$(K% = 13)
230 GOSUB 300CAESAR
240 PRINT T$
250 RETURN
R... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Dyalect | Dyalect | func calculateE(epsilon = 1.0e-15) {
func abs(n) {
if n < 0 {
-n
} else {
n
}
}
var fact = 1
var e = 2.0
var e0 = 0.0
var n = 2
while true {
e0 = e
fact *= n
n += 1
e += 1.0 / Float(fact)
if abs(e -... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #EasyLang | EasyLang | numfmt 0 5
fact = 1
n = 2
e = 2
while abs (e - e0) > 0.0001
e0 = e
fact = fact * n
n += 1
e += 1 / fact
.
print e |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ... | #Elixir | Elixir | defmodule Bulls_and_cows do
def player(size \\ 4) do
possibility = permute(size) |> Enum.shuffle
player(size, possibility, 1)
end
def player(size, possibility, i) do
guess = hd(possibility)
IO.puts "Guess #{i} is #{Enum.join(guess)} (from #{length(possibility)} possibilities)"
case get_scor... |
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... | #Euphoria | Euphoria | include std/sequence.e
constant line = "--------+--------------------\n"
constant digits = "123456789"
sequence list = {}
function get_digits(integer n)
integer j
sequence d = digits, ret = ""
for i=1 to n do
j = rand(length(digits)-i)
ret &= d[i+j]
if j then
d[i+j] =... |
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... | #FreeBASIC | FreeBASIC | ' VERSION 16-03-2016
' COMPILE WITH: FBC -S CONSOLE
' TRUE/FALSE ARE BUILT-IN CONSTANTS SINCE FREEBASIC 1.04
' BUT WE HAVE TO DEFINE THEM FOR OLDER VERSIONS.
#IFNDEF TRUE
#DEFINE FALSE 0
#DEFINE TRUE NOT FALSE
#ENDIF
FUNCTION WD(M AS INTEGER, D AS INTEGER, Y AS INTEGER) AS INTEGER
' ZELLERISH
' 0 = ... |
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... | #LabVIEW | LabVIEW | Section Header
+ name := TEST_C_INTERFACE;
// this will be inserted in front of the program
- external := `#include <string.h>`;
Section Public
- main <- (
+ s : STRING_CONSTANT;
+ p : NATIVE_ARRAY[CHARACTER];
s := "Hello World!";
p := s.to_external;
// this will be inserted in-place
// use `expr`... |
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... | #Lisaac | Lisaac | Section Header
+ name := TEST_C_INTERFACE;
// this will be inserted in front of the program
- external := `#include <string.h>`;
Section Public
- main <- (
+ s : STRING_CONSTANT;
+ p : NATIVE_ARRAY[CHARACTER];
s := "Hello World!";
p := s.to_external;
// this will be inserted in-place
// use `expr`... |
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... | #C | C | /* function with no argument */
f();
/* fix number of arguments */
g(1, 2, 3);
/* Optional arguments: err...
Feel free to make sense of the following. I can't. */
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Phix | Phix | integer n = 5,
w = power(3,n-1),
len = w
string line = repeat('#',w)&"\n"
while 1 do
puts(1,line)
if len=1 then exit end if
len /= 3
integer pos = 1
while pos<(w-len) do
pos += len
line[pos..pos+len-1] = ' '
pos += len
end while
end while
|
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var mod = Fn.new { |n, m| ((n%m) + m) % m }
var carmichael = Fn.new { |p1|
for (h3 in 2...p1) {
for (d in 1...h3 + p1) {
if ((h3 + p1) * (p1 - 1) % d == 0 && mod.call(-p1 * p1, h3) == d % h3) {
var p2 = 1 + ((p1 - 1) * (h3 + p1) / ... |
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: ... | #OCaml | OCaml | # let nums = [1;2;3;4;5;6;7;8;9;10];;
val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
# let sum = List.fold_left (+) 0 nums;;
val sum : int = 55
# let product = List.fold_left ( * ) 1 nums;;
val product : int = 3628800 |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #UNIX_Shell | UNIX Shell | dog="Benjamin"
Dog="Samba"
DOG="Bernie"
echo "The three dogs are named $dog, $Dog and $DOG." |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Ursa | Ursa | > decl string dog Dog DOG
> set dog "Benjamin"
> set Dog "Samba"
> set DOG "Bernie"
> out "The three dogs are named " dog ", " Dog ", and " DOG endl console
The three dogs are named Benjamin, Samba, and Bernie
> |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #VBA | VBA | Public Sub case_sensitivity()
'VBA does not allow variables that only differ in case
'The VBA IDE vbe will rename variable 'dog' to 'DOG'
'when trying to define a second variable 'DOG'
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog name... |
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... | #Quackery | Quackery | [ [] unrot
swap witheach
[ over witheach
[ over nested
swap nested join
nested dip rot join
unrot ]
drop ] drop ] is cartprod ( [ [ --> [ )
' [ 1 2 ] ' [ 3 4 ] cartprod echo cr
' [ 3 4 ] ' [ 1 2 ] cartprod echo cr
' [ 1 2 ] ' [ ]... |
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... | #Fermat | Fermat | Func Catalan(n)=(2*n)!/((n+1)!*n!).;
for i=1 to 15 do !Catalan(i);!' ' od; |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Swift | Swift | // Class
MyClass.method(someParameter)
// or equivalently:
let foo = MyClass.self
foo.method(someParameter)
// Instance
myInstance.method(someParameter)
// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3) |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Tcl | Tcl | package require Tcl 8.6
# "Static" (on class object)
MyClass mthd someParameter
# Instance
$myInstance mthd someParameter |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Ursa | Ursa | # create an instance of the built-in file class
decl file f
# call the file.open method
f.open "filename.txt" |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Tcl | Tcl | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
# Create the OpenImage command by other means here...
}
set handle [OpenImage "/the/file/name"] |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #TXR | TXR | This is the TXR Lisp interactive listener of TXR 176.
Use the :quit command or type Ctrl-D on empty line to exit.
1> (typedef utsarray (zarray 65 char))
#<ffi-type (zarray 65 char)>
2> (typedef utsname (struct utsname (sysname utsarray)
(nodename utsarray)
... |
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... | #Phix | Phix | --
-- demo\rosetta\BrilliantNumbers.exw
-- =================================
--
with javascript_semantics
requires("1.0.2") -- (for in)
atom t0 = time()
function get_primes_by_digits(integer limit)
sequence primes = get_primes_le(power(10,limit)),
primes_by_digits = {}
integer p = 10
while len... |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
W... | #11l | 11l | F getitem(=s, depth = 0)
V out = [‘’]
L s != ‘’
V c = String(s[0])
I depth & (c == ‘,’ | c == ‘}’)
R (out, s)
I c == ‘{’
V x = getgroup(s[1..], depth + 1)
I !x[0].empty
out = multiloop(out, x[0], (a, b) -> a‘’b)
s = x[1]
L.continue
... |
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... | #ALGOL_W | ALGOL W | BEGIN
INTEGER WIDTH, YEAR;
INTEGER COLS, LEAD, GAP;
STRING(2) ARRAY WDAYS (0::6);
RECORD MONTH ( STRING(9) MNAME; INTEGER DAYS, START_WDAY, AT_POS );
REFERENCE(MONTH) ARRAY MONTHS(0::11);
WIDTH := 80; YEAR := 1969;
BEGIN
WDAYS(0) := "Su"; WDAYS(1) := "Mo"; WDAYS(2) := "Tu";
... |
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... | #Common_Lisp | Common Lisp | (defpackage :funky
;; only these symbols are public
(:export :widget :get-wobbliness)
;; for convenience, bring common lisp symbols into funky
(:use :cl))
;; switch reader to funky package: all symbols that are
;; not from the CL package are interned in FUNKY.
(in-package :funky)
(defclass widget ()
;; ... |
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... | #D | D | module breakingprivacy;
struct Foo
{
int[] arr;
private:
int x;
string str;
float f;
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere wi... | #Applesoft_BASIC | Applesoft BASIC | 0GOSUB2:FORQ=0TOTSTEP0:X=A:Y=B:FORO=0TOTSTEP0:XDRAWTATX,Y:X=INT(RND(T)*J)*Z:Y=INT(RND(T)*H):XDRAWTATX,Y:O=PEEK(C)>0:NEXTO:FORP=0TOTSTEP0:A=X:B=Y:R=INT(RND(T)*E):X=X+X(R):Y=Y+Y(R):IFX<0ORX>MORY<0ORY>NTHENNEXTQ
1 XDRAW T AT X,Y:P = NOT PEEK (C): XDRAW T AT A,B: NEXT P: XDRAW T AT X,Y:Q = A = 0 OR A = M OR B = 0 OR B ... |
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... | #AppleScript | AppleScript | on pickNumber()
set theNumber to ""
repeat 4 times
set theDigit to (random number from 1 to 9) as string
repeat while (offset of theDigit in theNumber) > 0
set theDigit to (random number from 1 to 9) as string
end repeat
set theNumber to theNumber & theDigit
end repeat
end pickNumber
to bulls of theGues... |
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... | #Kotlin | Kotlin | // Version 1.2.60
const val STX = "\u0002"
const val ETX = "\u0003"
fun bwt(s: String): String {
if (s.contains(STX) || s.contains(ETX)) {
throw RuntimeException("String can't contain STX or ETX")
}
val ss = STX + s + ETX
val table = Array<String>(ss.length) { ss.substring(it) + ss.substring... |
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... | #Arc | Arc |
(= rot (fn (L N)
(if
(and (<= 65 L) (>= 90 L))
(do
(= L (- L 65))
(= L (mod (+ N L) 26))
(= L (+ L 65)))
(and (<= 97 L) (>= 122 L))
(do
(= L (- L 97))
(= L (mod (+ N L) 26))
(= L (+ L 97))))
L))
(= caesar (fn (text (o shift))
(unless shift (= shift 13))
... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #EDSAC_order_code | EDSAC order code |
[Calculate e]
[EDSAC program, Initial Orders 2]
[Library subroutine M3. Prints header and is then overwritten]
[Here, last character sets teleprinter to figures]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
@&*CALCULATION!OF!E@&#
..PZ [blank tape, needed to mark end of header text]
[Library subroutine D6.... |
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... | #Factor | Factor | USING: arrays combinators.short-circuit formatting fry io kernel
math math.combinatorics math.functions math.order math.parser
math.ranges random regexp sequences sets splitting ;
: bulls ( seq1 seq2 -- n ) [ = 1 0 ? ] 2map sum ;
: cows ( seq1 seq2 -- n ) [ intersect length ] [ bulls - ] 2bi ;
: score ( seq1 seq2 -- ... |
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... | #Go | Go | PACKAGE MAIN
IMPORT (
"FMT"
"TIME"
)
CONST PAGEWIDTH = 80
FUNC MAIN() {
PRINTCAL(1969)
}
FUNC PRINTCAL(YEAR INT) {
THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)
VAR (
DAYARR [12][7][6]INT // MONTH, WEEKDAY, WEEK
MONTH, LASTMONTH TIME.MONTH
... |
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... | #Lua | Lua | local ffi = require("ffi")
ffi.cdef[[
char * strndup(const char * s, size_t n);
int strlen(const char *s);
]]
local s1 = "Hello, world!"
print("Original: " .. s1)
local s_s1 = ffi.C.strlen(s1)
print("strlen: " .. s_s1)
local s2 = ffi.string(ffi.C.strndup(s1, s_s1), s_s1)
print("Copy: " .. s2)
print("strlen: " .. ff... |
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... | #C.23 | C# |
/* a function that has no argument */
public int MyFunction();
/* a function with a fixed number of arguments */
FunctionWithArguments(4, 3, 2);
/* a function with optional arguments */
public void OptArg();
public static void Main()
{
OptArg(1);
OptArg(1, 2);
OptArg(1, 2, 3);
}
public void Examp... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
5 >ps
3 tps 1 - power var w
"#" 1 get nip w repeat var line
ps> for
3 swap 1 - power
w over / int var step
true >ps
for var j
tps not if
step for var k
line 32 j 1 - step * k + set var line
endfor
endif
ps> not >ps
... |
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... | #zkl | zkl | var BN=Import("zklBigNum"), bi=BN(0); // gonna recycle bi
primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61);
var p2,p3;
cs:=[[(p1,h3,d); primes; { [2..p1 - 1] }; // list comprehension
{ [1..h3 + p1 - 1] },
{ ((h3 + p1)*(p1 - 1)%d == 0 and ((-p1*p1):mod(_,h3) == d%h3)) },//guard
{ (p2=1 + (p1 - 1)*(h3... |
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: ... | #Oforth | Oforth | [ 1, 2, 3, 4, 5 ] reduce(#max)
[ "abc", "def", "gfi" ] reduce(#+) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Wren | Wren | var dog = "Benjamin"
var Dog = "Samba"
var DOG = "Bernie"
System.print("The three dogs are named %(dog), %(Dog) and %(DOG).") |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #XBS | XBS | set dog="Benjamin";
set DOG="Samba";
set Dog="Bernie";
log(`The three dogs are named {dog}, {DOG} and {Dog}.`); |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #R | R |
one_w_many <- function(one, many) lapply(many, function(x) c(one,x))
# Let's define an infix operator to perform a cartesian product.
"%p%" <- function( a, b ) {
p = c( sapply(a, function (x) one_w_many(x, b) ) )
if (is.null(unlist(p))) list() else p}
display_prod <-
function (xs) { for (x in xs) cat( pas... |
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.