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/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... | #Forth | Forth | : catalan ( n -- ) 1 swap 1+ 1 do dup cr . i 2* 1- 2* i 1+ */ loop drop ; |
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... | #VBA | VBA |
Option Explicit
Sub Method_1(Optional myStr As String)
Dim strTemp As String
If myStr <> "" Then strTemp = myStr
Debug.Print strTemp
End Sub
Static Sub Method_2(Optional myStr As String)
Dim strTemp As String
If myStr <> "" Then strTemp = myStr
Debug.Print strTemp
End Sub |
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... | #Wren | Wren | class MyClass {
construct new() {}
method() { System.print("instance method called") }
static method() { System.print("static method called") }
}
var mc = MyClass.new()
mc.method()
MyClass.method() |
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... | #Ursala | Ursala | #import std
#import flo
my_replacement = fleq/0.?/~& negative
abs = math.|fabs my_replacement |
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... | #VBA | VBA | function ffun(x, y)
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun
double precision :: x, y, ffun
ffun = x + y * y
end function |
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... | #Python | Python | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n... |
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... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
on braceExpansion(textForExpansion)
-- Massage the text to pass to a shell script: -
-- Single-quote it to render everything in it initially immune from brace and file-system expansion.
-- In... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #11l | 11l | F isPrime(n)
I n % 2 == 0
R n == 2
I n % 3 == 0
R n == 3
V d = 5
L d * d <= n
I n % d == 0
R 0B
I n % (d + 2) == 0
R 0B
d += 6
R 1B
F sameDigits(=n, b)
V d = n % b
n I/= b
I d == 0
R 0B
L n > 0
I n % b != d
R 0B
n I/... |
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... | #AutoHotkey | AutoHotkey | Calendar(Yr){
LastDay := [], Day := []
Titles =
(ltrim
______January_________________February_________________March_______
_______April____________________May____________________June________
________July___________________August_________________September_____
______October_________________November_______________... |
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... | #E | E | open System
open System.Reflection
type MyClass() =
let answer = 42
member this.GetAnswer
with get() = answer
[<EntryPoint>]
let main argv =
let myInstance = MyClass()
let fieldInfo = myInstance.GetType().GetField("answer", BindingFlags.NonPublic ||| BindingFlags.Instance)
let answer ... |
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... | #F.23 | F# | open System
open System.Reflection
type MyClass() =
let answer = 42
member this.GetAnswer
with get() = answer
[<EntryPoint>]
let main argv =
let myInstance = MyClass()
let fieldInfo = myInstance.GetType().GetField("answer", BindingFlags.NonPublic ||| BindingFlags.Instance)
let answer ... |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere wi... | #AutoHotkey | AutoHotkey | SetBatchLines -1
Process, Priority,, high
size := 400
D := .08
num := size * size * d
field:= Object()
field[size//2, size//2] := true ; set the seed
lost := 0
Loop % num
{
x := Rnd(1, size), y := Rnd(1, size)
Loop
{
oldX := X, oldY := Y
x += Rnd(-1, 1), y += Rnd(1, -1)
If ( field[x, y] )
{
field[ol... |
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... | #Arturo | Arturo | rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0
while [bulls <> 4][
bulls: new 0
cows: new 0
got: strip input "make a guess: "
if? or? not? numeric? got
4 <> size got -> print "Malformed answer. Try again!"
else [
loop.with:'i split got 'digit [
if? (to :... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Burrows–Wheeler transform
# # Variables:
#
export LC_COLLATE=POSIX
STX=\^ # start marker
ETX=\| # end marker
typeset -a str
str[0]='BANANA'
str[1]='appellee'
str[2]='dogwood'
str[3]='TO BE OR NOT TO BE OR WANT TO BE OR NOT?'
str[4]='SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES'
str[5]='|ABC^'
... |
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... | #Lua | Lua | STX = string.char(tonumber(2,16))
ETX = string.char(tonumber(3,16))
function bwt(s)
if s:find(STX, 1, true) then
error("String cannot contain STX")
end
if s:find(ETX, 1, true) then
error("String cannot contain ETX")
end
local ss = STX .. s .. ETX
local tbl = {}
for i=1,#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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ STRINGSIZE, 500
/* Initialized data ... |
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
| #Emacs_Lisp | Emacs Lisp | (defun factorial (i)
"Compute factorial of i."
(apply #'* (number-sequence 1 i)))
(defun compute-e (iter)
"Compute e."
(apply #'+ 1 (mapcar (lambda (x) (/ 1.0 x))
(mapcar #'factorial (number-sequence 1 iter)))))
(compute-e 20) |
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
| #Epoxy | Epoxy | fn CalculateE(P)
var E:1,F:1
loop I:1;I<=P;I+:1 do
F*:I
E+:1/F
cls
return E
cls
log(CalculateE(100))
log(math.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... | #Fortran | Fortran | module Player
implicit none
contains
subroutine Init(candidates)
integer, intent(in out) :: candidates(:)
integer :: a, b, c, d, n
n = 0
thousands: do a = 1, 9
hundreds: do b = 1, 9
tens: do c = 1, 9
units: do d = 1, 9
if (b == a) cycle hundreds
... |
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... | #GUISS | GUISS | RIGHTCLICK:CLOCK,ADJUST DATE AND TIME,BUTTON:CANCEL |
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... | #Luck | Luck | import "stdio.h";;
import "string.h";;
let s1:string = "Hello World!";;
let s2:char* = strdup(cstring(s1));;
puts(s2);;
free(s2 as void*) |
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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckCCall {
mybuf$=string$(chr$(0), 1000)
a$="Hello There 12345"+Chr$(0)
Print Len(a$)
Buffer Clear Mem as Byte*Len(a$)
\\ copy to Mem the converted a$ (from Utf-16Le to ANSI)
Return Mem, 0:=str$(a$)
Declare MyStrDup Lib C "msvcrt._strdup" { Long Ptr}
Decl... |
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.2B.2B | C++ |
/* function with no arguments */
foo();
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Python | Python | WIDTH = 81
HEIGHT = 5
lines=[]
def cantor(start, len, index):
seg = len / 3
if seg == 0:
return None
for it in xrange(HEIGHT-index):
i = index + it
for jt in xrange(seg):
j = start + seg + jt
pos = i * WIDTH + j
lines[pos] = ' '
cantor(start,... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR p=2 TO 61
20 LET n=p: GO SUB 1000
30 IF NOT n THEN GO TO 200
40 FOR h=1 TO p-1
50 FOR d=1 TO h-1+p
60 IF NOT (FN m((h+p)*(p-1),d)=0 AND FN w(-p*p,h)=FN m(d,h)) THEN GO TO 180
70 LET q=INT (1+((p-1)*(h+p)/d))
80 LET n=q: GO SUB 1000
90 IF NOT n THEN GO TO 180
100 LET r=INT (1+(p*q/h))
110 LET n=r: GO SUB 1000
120... |
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: ... | #PARI.2FGP | PARI/GP | reduce(f, v)={
my(t=v[1]);
for(i=2,#v,t=f(t,v[i]));
t
};
reduce((a,b)->a+b, [1,2,3,4,5,6,7,8,9,10]) |
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... | #XLISP | XLISP | (SETQ DOG 'BENJAMIN)
(SETQ Dog 'SAMBA)
(SETQ dog 'BERNIE)
(DISPLAY `(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... | #XPL0 | XPL0 |
dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
print "The three dogs are named ", dog$, ", ", Dog$, " and ", DOG$
end |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Yabasic | Yabasic |
dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
print "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... | #Racket | Racket | #lang racket/base
(require rackunit
;; usually, included in "racket", but we're using racket/base so we
;; show where this comes from
(only-in racket/list cartesian-product))
;; these tests will pass silently
(check-equal? (cartesian-product '(1 2) '(3 4))
'((1 3) (1 4) (2 3) (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... | #Fortran | Fortran | program main
!=======================================================================================
implicit none
!=== Local data
integer :: n
!=== External procedures
double precision, external :: catalan_numbers
!=== Execution =====================================... |
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... | #XBS | XBS | class MyClass {
construct=func(self,Props){
self:Props=Props;
}{Props={}}
GetProp=func(self,Name){
send self.Props[Name];
}
}
set Class = new MyClass with [{Name="MyClass Name"}];
log(Class::GetProp("Name")); |
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... | #XLISP | XLISP | (DEFINE-CLASS MY-CLASS)
(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
(DISPLAY "I am the class -- ")
(DISPLAY SELF)
(NEWLINE)
(DISPLAY "You sent me the parameter ")
(DISPLAY SOME-PARAMETER)
(NEWLINE))
(DEFINE-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
(DISPLA... |
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... | #Zig | Zig | const assert = @import("std").debug.assert;
pub const ID = struct {
name: []const u8,
age: u7,
const Self = @This();
pub fn init(name: []const u8, age: u7) Self {
return Self{
.name = name,
.age = age,
};
}
pub fn getAge(self: Self) u7 {
re... |
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... | #zkl | zkl | class C{var v; fcn f{v}}
C.f() // call function f in class C
C.v=5; c2:=C(); // create new instance of C
println(C.f()," ",c2.f()) //-->5 Void
C.f.isStatic //--> False
class [static] D{var v=123; fcn f{v}}
D.f(); D().f(); // both return 123
D.f.isStatic //-->False
class E{var v; fcn f{}} E.f.isStatic //-->True |
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... | #Wren | Wren | /* call_shared_library_function.wren */
var RTLD_LAZY = 1
foreign class DL {
construct open(file, mode) {}
foreign call(symbol, arg)
foreign close()
}
class My {
static openimage(s) {
System.print("internal openimage opens %(s)...")
if (!__handle) __handle = 0
__handle ... |
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... | #X86-64_Assembly | X86-64 Assembly |
option casemap:none
windows64 equ 1
linux64 equ 3
ifndef __LIB_CLASS__
__LIB_CLASS__ equ 1
if @Platform eq windows64
option dllimport:<kernel32>
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
Ge... |
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... | #Raku | Raku | use Lingua::EN::Numbers;
# Find an abundance of primes to use to generate brilliants
my %primes = (2..100000).grep( &is-prime ).categorize: { .chars };
# Generate brilliant numbers
my @brilliant = lazy flat (1..*).map: -> $digits {
sort flat (^%primes{$digits}).race.map: { %primes{$digits}[$_] X× (flat %primes{... |
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... | #Rust | Rust | // [dependencies]
// primal = "0.3"
// indexing = "0.4.1"
fn get_primes_by_digits(limit: usize) -> Vec<Vec<usize>> {
let mut primes_by_digits = Vec::new();
let mut power = 10;
let mut primes = Vec::new();
for prime in primal::Primes::all().take_while(|p| *p < limit) {
if prime > power {
... |
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... | #AutoHotkey | AutoHotkey | ;This one is a lot more simpler than the rest
BraceExp(string, del:="`n") {
Loop, Parse, string
if (A_LoopField = "{")
break
else
substring .= A_LoopField
substr := SubStr(string, InStr(string, "{")+1, InStr(string, "}")-InStr(string, "{")-1)
Loop, Parse, substr, `,
toreturn .= substring . A_LoopField . d... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Action.21 | Action! | INCLUDE "H6:SIEVE.ACT"
BYTE FUNC SameDigits(INT x,b)
INT d
d=x MOD b
x==/b
WHILE x>0
DO
IF x MOD b#d THEN
RETURN (0)
FI
x==/b
OD
RETURN (1)
BYTE FUNC IsBrazilian(INT x)
INT b
IF x<7 THEN RETURN (0) FI
IF x MOD 2=0 THEN RETURN (1) FI
FOR b=2 TO x-2
DO
IF SameDigits(x,b... |
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... | #AutoIt | AutoIt |
#include <Date.au3>
; Set the count of characters in each line, minimum is 20 - one month.
Global $iPrintSize = 132
; Set the count of months, you want to print side by side. With "0" it calculates automatically.
; The number will corrected, if it not allowed to print in an rectangle.
; If your print size is to s... |
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... | #Factor | Factor | ( scratchpad ) USING: sets sets.private ;
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
2 |
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... | #Forth | Forth | include FMS-SI.f
99 value x \ create a global variable named x
:class foo
ivar x \ this x is private to the class foo
:m init: 10 x ! ;m \ constructor
:m print x ? ;m
;class
foo f1 \ instantiate a foo object
f1 print \ 10 access the private x with the print message
x . \ 99 x is a globally sc... |
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... | #FreeBASIC | FreeBASIC | 'FB 1.05.0 Win64
#Undef Private
#Undef Protected
#Define Private Public
#Define Protected Public
Type MyType
Public :
x As Integer = 1
Protected :
y As Integer = 2
Private :
z As Integer = 3
End Type
Dim mt As MyType
Print mt.x, mt.y, mt.z
Print
Print "Press any key to quit"
Sleep |
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... | #BBC_BASIC | BBC BASIC | SYS "SetWindowText", @hwnd%, "Brownian Tree"
SIZE = 400
VDU 23,22,SIZE;SIZE;8,16,16,0
GCOL 10
REM set the seed:
PLOT SIZE, SIZE
OFF
REPEAT
REM set particle's initial position:
REPEAT
X% = RND(SIZE)-1
Y% = RND(SIZE)-1
UNT... |
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... | #AutoHotkey | AutoHotkey | length:=4, Code:="" ; settings
While StrLen(Code) < length {
Random, num, 1, 9
If !InStr(Code, num)
Code .= num
}
Gui, Add, Text, w83 vInfo, I'm thinking of a %length%-digit number with no duplicate digits.
Gui, Add, Edit, wp vGuess, Enter a guess...
Gui, Add, Button, wp Default vDefault, Submit
Gui, Add, Edit, y... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[BurrowWheeler, InverseBurrowWheeler]
BurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s},
s = Characters[bdelim <> sin <> edelim];
s = RotateLeft[s, #] & /@ Range[Length[s]];
StringJoin[LexicographicSort[s][[All, -1]]]
]
InverseBurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s, chars},... |
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... | #Nim | Nim | import algorithm
from sequtils import repeat
import strutils except repeat
const
Stx = '\2'
Etx = '\3'
#---------------------------------------------------------------------------------------------------
func bwTransform*(s: string): string =
## Apply Burrows–Wheeler transform to input string.
doAssert(... |
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... | #Arturo | Arturo | ia: to :integer `a`
iA: to :integer `A`
lowAZ: `a`..`z`
uppAZ: `A`..`Z`
caesar: function [s, xx][
k: (not? null? attr 'decode)? -> 26-xx -> xx
result: new ""
loop s 'i [
(in? i lowAZ)? -> 'result ++ to :char ia + (k + (to :integer i) - ia) % 26
[
(in? i uppAZ)? -> 'result ++ to... |
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
| #Excel | Excel | eApprox
=LAMBDA(n,
INDEX(
FOLDROW(
LAMBDA(efl,
LAMBDA(x,
LET(
flx, INDEX(efl, 2) * x,
e, INDEX(efl, 1),
CHOOSE(
{1;2},
e + (1 / fl... |
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... | #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Println(`Cows and bulls/player
You think of four digit number of unique digits in the range 1 to 9.
I guess. You score my guess:
A correct digit but not in the correct place is a cow.
A correct digit 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... | #Icon_and_Unicon | Icon and Unicon | $include "REALIZE.ICN"
LINK DATETIME
$define ISLEAPYEAR IsLeapYear
$define JULIAN julian
PROCEDURE MAIN(A)
PRINTCALENDAR(\A$<1$>|1969)
END
PROCEDURE PRINTCALENDAR(YEAR)
COLS := 3
MONS := $<$>
"JANUARY FEBRUARY MA... |
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... | #Maple | Maple | > strdup := define_external( strdup, s::string, RETURN::string, LIB = "/lib/libc.so.6" ):
> strdup( "foo" );
"foo"
|
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["NETLink`"];
externalstrdup = DefineDLLFunction["_strdup", "msvcrt.dll", "string", {"string"}];
Print["Duplicate: ", externalstrdup["Hello world!"]] |
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... | #COBOL | COBOL | CALL "No-Arguments"
*> Fixed number of arguments.
CALL "2-Arguments" USING Foo Bar
CALL "Optional-Arguments" USING Foo
CALL "Optional-Arguments" USING Foo Bar
*> If an optional argument is omitted and replaced with OMITTED, any following
*> arguments can still be specified.
CALL "Optional-Arguments" USING Foo OMITT... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #QB64 | QB64 | _Title "Cantor Set"
Dim Shared As Integer sw, sh, wide, high
sw = 800: sh = 200: wide = 729: high = 7
Dim Shared As Integer a(wide, high)
Screen _NewImage(sw, sh, 8)
Cls , 15: Color 0
Call calc(0, wide, 1)
Call CantorSet
Sleep
System
Sub calc (start As Integer, length As Integer, index As Integer)
Dim As ... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Quackery | Quackery | [ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "ABA" ] is A ( $ --> $ )
[ $ "BBB" ] is B ( $ --> $ )
[ char A = iff
[ char q ] else space
swap of echo$ ] is draw ( n c --> $ )
81 $ "A"
5 ... |
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: ... | #Pascal | Pascal | program reduceApp;
type
// tmyArray = array of LongInt;
tmyArray = array[-5..5] of LongInt;
tmyFunc = function (a,b:LongInt):LongInt;
function add(x,y:LongInt):LongInt;
begin
add := x+y;
end;
function sub(k,l:LongInt):LongInt;
begin
sub := k-l;
end;
function mul(r,t:LongInt):LongInt;
begin
mul := r*t... |
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... | #zkl | zkl | var dog = "Benjamin", Dog = "Samba", DOG = "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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET D$="Benjamin"
20 PRINT "There is just one dog named ";d$ |
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... | #Raku | Raku | # cartesian product of two lists using the X cross meta-operator
say (1, 2) X (3, 4);
say (3, 4) X (1, 2);
say (1, 2) X ( );
say ( ) X ( 1, 2 );
# cartesian product of variable number of lists using
# the [X] reduce cross meta-operator
say [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);
say [X] (1, 2, 3), (30), (5... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function factorial(n As UInteger) As UInteger
If n = 0 Then Return 1
Return n * factorial(n - 1)
End Function
Function catalan1(n As UInteger) As UInteger
Dim prod As UInteger = 1
For i As UInteger = n + 2 To 2 * n
prod *= i
Next
Return prod / factorial(n)
End Function
Function ... |
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... | #zkl | zkl | var BN=Import("zklBigNum");
BN(1)+2 //--> BN(3) |
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... | #Sidef | Sidef | func is_briliant_number(n) {
n.is_semiprime && (n.factor.map{.len}.uniq.len == 1)
}
func brilliant_numbers_count(n) {
var count = 0
var len = n.isqrt.len
for k in (1 .. len-1) {
var pi = prime_count(10**(k-1), 10**k - 1)
count += binomial(pi, 2)+pi
}
var min = (10**(len -... |
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... | #Swift | Swift | // Refs:
// https://www.geeksforgeeks.org/sieve-of-eratosthenes/?ref=leftbar-rightbar
// https://developer.apple.com/documentation/swift/array/init(repeating:count:)-5zvh4
// https://www.geeksforgeeks.org/brilliant-numbers/#:~:text=Brilliant%20Number%20is%20a%20number,25%2C%2035%2C%2049%E2%80%A6.
// Using Sieve of Er... |
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... | #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #ALGOL_W | ALGOL W | begin % find some Brazilian numbers - numbers N whose representation in some %
% base B ( 1 < B < N-1 ) has all the same digits %
% set b( 1 :: n ) to a sieve of Brazilian numbers where b( i ) is true %
% if i is Brazilian and false otherwise - n must be at least 8 %
... |
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... | #AWK | AWK |
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk
To change the output width, change the value assigned to variable pagewide
#!/bin/gawk -f
BEGIN{
wkdays = "Su Mo Tu We Th Fr Sa"
pagewide = 80
blank=" "
for (i=1; i<pagewide; i++) blank = blank " "
# month name accessed as substr(month,n... |
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... | #Go | Go | package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int // In Go identifiers that are capitalized are exported,
unexported int // while lowercase identifiers are not.
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&ob... |
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... | #C | C | #include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <FreeImage.h>
#define NUM_PARTICLES 1000
#define SIZE 800
void draw_brownian_tree(int world[SIZE][SIZE]){
int px, py; // particle values
int dx, dy; // offsets
int i;
// set the seed
world[rand() % SIZE][rand... |
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... | #AWK | AWK | # Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
srand()
secret = ""
for (i = 1; i <= 4; ) {
digit = int(9 * rand()) + 1
if (index(secret, digit) == 0) {
secret = secret digit
i++
}
}
print "Welcome to 'Bulls and Cows'!"
print "I thought of a 4-digit nu... |
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... | #Pascal | Pascal |
program BurrowsWheeler;
{$mode objfpc}{$H+} // Lazarus default mode; long strings
uses SysUtils; // only for console output
const STR_BASE = 1; // first character in a Pascal string has index [1].
type TComparison = -1..1;
procedure Encode( const input : string;
out encoded : string;
... |
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... | #Astro | Astro | fun caesar(s, k, decode: false):
if decode:
k = 26 - k
result = ''
for i in s.uppercase() where 65 <= ord(i) <= 90:
result.push! char(ord(i) - 65 + k) mod 26 + 65
return result
let message = "The quick brown fox jumped over the lazy dogs"
let encrypted = caesar(msg, 11)
let decrypted =... |
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
| #F.23 | F# |
// A function to generate the sequence 1/n!). Nigel Galloway: May 9th., 2018
let e = Seq.unfold(fun (n,g)->Some(n,(n/g,g+1N))) (1N,1N)
|
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
| #Factor | Factor | USING: math math.factorials prettyprint sequences ;
IN: rosetta-code.calculate-e
CONSTANT: terms 20
terms <iota> [ n! recip ] map-sum >float . |
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... | #Haskell | Haskell | import Data.List
import Control.Monad
import System.Random (randomRIO)
import Data.Char(digitToInt)
combinationsOf 0 _ = [[]]
combinationsOf _ [] = []
combinationsOf k (x:xs) = map (x:) (combinationsOf (k-1) xs) ++ combinationsOf k xs
player = do
let ps = concatMap permutations $ combinationsOf 4 ['1'..'9']
pla... |
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... | #J | J | B=: + 4 100 400 -/@:<.@:%~ <:
M=: 28+ 3, (10$5$3 2),~ 0 ~:/@:= 4 100 400 | ]
R=: (7 -@| B+ 0, +/\@}:@M) |."0 1 (0,#\#~41) (]&:>: *"1 >/)~ M
H=. _3(_11&{.)\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
H=. 'SU MO TU WE TH FR SA',:"1~H
C=: H <@,"(2) 12 6 21 }."1@($,) (' ',3 ":,.#\#~31) {~ R
D=: 0 ": -@<.@%&21@+&1@[ ]\ C@]
L=: ... |
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... | #Maxima | Maxima | /* Maxima is written in Lisp and can call Lisp functions.
Use load("funcs.lisp"), or inside Maxima: */
to_lisp();
> (defun $f (a b) (+ a b))
> (to-maxima)
f(5, 6);
11 |
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... | #Mercury | Mercury | :- module test_ffi.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
% The actual FFI code begins here.
:- pragma foreign_decl("C", "#include <string.h>").
:- func strdup(string::in) = (string::out) is det.
:- pragma foreign_proc("C", strdup(S::in) = (SD::out),
... |
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... | #Clojure | Clojure |
(defn one []
"Function that takes no arguments and returns 1"
1)
(one); => 1
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #R | R |
cantorSet <- function() {
depth <- 6L
cs <- vector('list', depth)
cs[[1L]] <- c(0, 1)
for(k in seq_len(depth)) {
cs[[k + 1L]] <- unlist(sapply(seq_len(length(cs[[k]]) / 2L), function(j) {
p <- cs[[k]][2L] / 3
h <- 2L * (j - 1L)
c(
cs[[k]][h + 1L] + c(0, p),
cs[[k]][h + 2L... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Racket | Racket | #lang racket/base
;; {trans|Kotlin}}
(define current-width (make-parameter 81))
(define current-height (make-parameter 5))
(define (Cantor_set (w (current-width)) (h (current-height)))
(define lines (build-list h (λ (_) (make-bytes w (char->integer #\#)))))
(define (cantor start len index)
(let* ((seg (qu... |
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: ... | #Perl | Perl | use List::Util 'reduce';
# note the use of the odd $a and $b globals
print +(reduce {$a + $b} 1 .. 10), "\n";
# first argument is really an anon function; you could also do this:
sub func { $b & 1 ? "$a $b" : "$b $a" }
print +(reduce \&func, 1 .. 10), "\n" |
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: ... | #Phix | Phix | with javascript_semantics
function add(integer a, b) return a + b end function
function sub(integer a, b) return a - b end function
function mul(integer a, b) return a * b end function
function reduce(integer rid, sequence s)
object res = s[1]
for i=2 to length(s) do
res = rid(res,s[i])
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... | #REXX | REXX | /*REXX program calculates the Cartesian product of two arbitrary-sized lists. */
@.= /*assign the default value to @. array*/
parse arg @.1 /*obtain the optional value of @.1 */
if @.1='' then do; @.1= "{1,2} {3,4}" ... |
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... | #Frink | Frink | catalan[n] := binomial[2n,n]/(n+1)
for n = 0 to 15
println[catalan[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... | #Wren | Wren | import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt
var primes = Int.primeSieve(1e7-1)
var getBrilliant = Fn.new { |digits, limit, countOnly|
var brilliant = []
var count = 0
var pow = 1
var next = Num.maxSafeInteger
for (k in 1..digits) {
var s = primes.where { |p| p >... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(e... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #AppleScript | AppleScript | on isBrazilian(n)
repeat with b from 2 to n - 2
set d to n mod b
set temp to n div b
repeat while (temp mod b = d) -- ((temp > 0) and (temp mod b = d))
set temp to temp div b
end repeat
if (temp = 0) then return true
end repeat
return false
end isBrazili... |
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... | #BaCon | BaCon | DECLARE month$[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }
DECLARE month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
year$ = "1969"
' Leap year
INCR month[1], IIF(MOD(VAL(year$), 4) = 0 OR MOD(VAL(year$), 100) = 0 AND MOD(VA... |
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... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
(x := foo(1,2,3)).print() # create and show a foo
printf("Fieldnames of foo x : ") # show fieldnames
every printf(" %i",fieldnames(x)) # __s (self), __m (methods), vars
printf("\n")
printf("var 1 of foo x = %i\n", x.var1) # read var1 from ... |
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... | #J | J | import java.lang.reflect.*;
class Example {
private String _name;
public Example(String name) { _name = name; }
public String toString() { return "Hello, I am " + _name; }
}
public class BreakPrivacy {
public static final void main(String[] args) throws Exception {
Example foo = new Example("Eric");
for (... |
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... | #C.23 | C# | using System;
using System.Drawing;
namespace BrownianTree
{
class Program
{
static Bitmap BrownianTree(int size, int numparticles)
{
Bitmap bmp = new Bitmap(size, size);
Rectangle bounds = new Rectangle { X = 0, Y = 0, Size = bmp.Size };
using (Graphics g =... |
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... | #BASIC | BASIC | DEFINT A-Z
DIM secret AS STRING
DIM guess AS STRING
DIM c AS STRING
DIM bulls, cows, guesses, i
RANDOMIZE TIMER
DO WHILE LEN(secret) < 4
c = CHR$(INT(RND * 10) + 48)
IF INSTR(secret, c) = 0 THEN secret = secret + c
LOOP
guesses = 0
DO
INPUT "Guess a 4-digit number with no duplicate digits: "; gu... |
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... | #Perl | Perl | use utf8;
binmode STDOUT, ":utf8";
use constant STX => '👍 ';
sub transform {
my($s) = @_;
my($t);
warn "String can't contain STX character." and exit if $s =~ /STX/;
$s = STX . $s;
$t .= substr($_,-1,1) for sort map { rotate($s,$_) } 1..length($s);
return $t;
}
sub rotate { my($s,$n) = @_... |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to... | #AutoHotkey | AutoHotkey | n=2
s=HI
t:=&s
While *t
o.=Chr(Mod(*t-65+n,26)+65),t+=2
MsgBox % o |
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
| #FOCAL | FOCAL | 1.1 S K=1; S E=0
1.2 F X=1,10; D 2
1.3 Q
2.1 S E=E+1/K
2.2 S K=K*X
2.3 T %2,X,%6.5,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
| #Forth | Forth | 100 constant #digits
: int-array create cells allot does> swap cells + ;
#digits 1+ int-array e-digits[]
: init-e ( -- )
[ #digits 1+ ] literal 0 DO
1 i e-digits[] !
LOOP
." = 2." ;
: .e ( -- )
init-e
[ #digits 1- ] literal 0 DO
0 \ carry
0 #digits DO
i e-digits[] d... |
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... | #J | J | require'misc'
poss=:1+~.4{."1 (i.!9)A.i.9
fmt=: ' ' -.~ ":
play=:3 :0
while.1<#poss=.poss do.
smoutput'guessing ',fmt guess=.({~ ?@#)poss
bc=.+/\_".prompt 'how many bull and cows? '
poss=.poss #~({.bc)=guess+/@:="1 poss
poss=.poss #~({:bc)=guess+/@e."1 poss
end.
if.#poss do.
'the answer i... |
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.