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/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #EasyLang | EasyLang | color3 0 1 1
len f[] 200 * 200
move 50 50
rect 0.5 0.5
f[100 * 200 + 100] = 1
n = 9000
while i < n
repeat
x = random 200
y = random 200
until f[y * 200 + x] <> 1
.
while 1 = 1
xo = x
yo = y
x += random 3 - 1
y += random 3 - 1
if x < 0 or y < 0 or x >= 200 or y >= 200
break 1
.
if f[y * 200 + x] = 1
move xo / 2 yo / 2
rect 0.5 0.5
f[yo * 200 + xo] = 1
i += 1
if i mod 16 = 0
color3 0.2 + i / n 1 1
sleep 0
.
break 1
.
.
. |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #C | C | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>
#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18
int yp=LINE_BEGIN, xp=0;
char number[5];
char guess[5];
#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
va_list args;
char buf[MAX_STR];
va_start(args, fmt);
vsprintf(buf, fmt, args);
move(y, x);
clrtoeol();
addstr(buf);
va_end(args);
}
void ask_for_a_number()
{
int i=0;
char symbols[] = "123456789";
move(5,0); clrtoeol();
addstr("Enter four digits: ");
while(i<4) {
int c = getch();
if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
addch(c);
symbols[c-'1'] = 0;
guess[i++] = c;
}
}
}
void choose_the_number()
{
int i=0, j;
char symbols[] = "123456789";
while(i<4) {
j = rand() % 9;
if ( symbols[j] != 0 ) {
number[i++] = symbols[j];
symbols[j] = 0;
}
}
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Ruby | Ruby | STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
ss = ss.rotate(-1)
end
table = table.sort
return table.map{ |e| e[-1] }.join
end
def ibwt(r)
len = r.length
table = [""] * len
for i in 0 .. len - 1
for j in 0 .. len - 1
table[j] = r[j] + table[j]
end
table = table.sort
end
for row in table
if row[-1] == ETX then
return row[1 .. -2]
end
end
return ""
end
def makePrintable(s)
s = s.gsub(STX, "^")
return s.gsub(ETX, "|")
end
def main
tests = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
]
for test in tests
print makePrintable(test), "\n"
print " --> "
begin
t = bwt(test)
print makePrintable(t), "\n"
r = ibwt(t)
print " --> ", r, "\n\n"
rescue ArgumentError => e
print e.message, "\n"
print " -->\n\n"
end
end
end
main() |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #bash | bash |
caesar_cipher() {
# michaeltd 2019-11-30
# https://en.wikipedia.org/wiki/Caesar_cipher
# E n ( x ) = ( x + n ) mod 26.
# D n ( x ) = ( x − n ) mod 26.
local -a _ABC=( "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" )
local -a _abc=( "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" )
local _out
if (( $# < 3 )) || [[ "$1" != "-e" && "$1" != "-d" ]] || (( $2 < 1 || $2 > 25 )); then
echo "Usage: ${FUNCNAME[0]} -e|-d rotation (1-25) argument[(s)...]" >&2
return 1
fi
_func="${1}"; shift
_rotval="${1}"; shift
while [[ -n "${1}" ]]; do
for (( i = 0; i < ${#1}; i++ )); do
for (( x = 0; x < ${#_abc[*]}; x++ )); do
case "${_func}" in
"-e")
[[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x + _rotval ) % 26 ))]}" && break
[[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x + _rotval ) % 26 ))]}" && break;;
"-d")
[[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x - _rotval ) % 26 ))]}" && break
[[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x - _rotval ) % 26 ))]}" && break;;
esac
# If char has not been found by now lets add it as is.
(( x == ${#_abc[*]} - 1 )) && _out+="${1:$i:1}"
done
done
_out+=" "
shift
done
echo "${_out[*]}"
}
|
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
| #Groovy | Groovy | def ε = 1.0e-15
def φ = 1/ε
def generateAddends = {
def addends = []
def n = 0.0
def fact = 1.0
while (true) {
fact *= (n < 2 ? 1.0 : n) as double
addends << 1.0/fact
if (fact > φ) break // any further addends would not pass the tolerance test
n++
}
addends.sort(false) // smallest addends first for better response to rounding error
}
def e = generateAddends().sum() |
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
| #Haskell | Haskell | ------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
eApprox :: Int -> Double
eApprox n =
(sum . take n) $ (1 /) <$> scanl (*) 1 [1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main = print $ eApprox 20 |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | bullCow={Count[#1-#2,0],Length[#1\[Intersection]#2]-Count[#1-#2,0]}&;
Module[{r,input,candidates=Permutations[Range[9],{4}]},
While[True,
r=InputString[];
If[r===$Canceled,Break[],
input=ToExpression/@StringSplit@r;
If[Length@input!=3,Print["Input the guess, number of bulls, number of cows, delimited by space."],
candidates=Select[candidates,bullCow[ToCharacterCode@StringJoin[ToString/@#],ToCharacterCode@ToString@input[[1]]]==input[[2;;3]]&];
candidates=SortBy[candidates,{-3,-1}.bullCow[ToCharacterCode@StringJoin[ToString/@#],ToCharacterCode@ToString@input[[1]]]&];
If[candidates==={},Print["No more candidates."];Break[]];
If[Length@candidates==1,Print["Must be: "<>StringJoin[ToString/@candidates[[1]]]];Break[]];
Print[ToString@Length@candidates<>" candidates remaining."];
Print["Can try "<>StringJoin[ToString/@First@candidates]<>"."];
]]]] |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Perl | Perl | $PROGRAM = '\'
MY @START_DOW = (3, 6, 6, 2, 4, 0,
2, 5, 1, 3, 6, 1);
MY @DAYS = (31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31);
MY @MONTHS;
FOREACH MY $M (0 .. 11) {
FOREACH MY $R (0 .. 5) {
$MONTHS[$M][$R] = JOIN " ",
MAP { $_ < 1 || $_ > $DAYS[$M] ? " " : SPRINTF "%2D", $_ }
MAP { $_ - $START_DOW[$M] + 1 }
$R * 7 .. $R * 7 + 6;
}
}
SUB P { WARN $_[0], "\\N" }
P UC " [INSERT SNOOPY HERE]";
P " 1969";
P "";
FOREACH (UC(" JANUARY FEBRUARY MARCH APRIL MAY JUNE"),
UC(" JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER")) {
P $_;
MY @MS = SPLICE @MONTHS, 0, 6;
P JOIN " ", ((UC "SU MO TU WE TH FR SA") X 6);
P JOIN " ", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5;
}
\'';
# LOWERCASE LETTERS
$E = '%' | '@';
$C = '#' | '@';
$H = '(' | '@';
$O = '/' | '@';
$T = '4' | '@';
$R = '2' | '@';
$A = '!' | '@';
$Z = ':' | '@';
$P = '0' | '@';
$L = ',' | '@';
`${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #PARI.2FGP | PARI/GP | use Inline C => q{
char *copy;
char * c_dup(char *orig) {
return copy = strdup(orig);
}
void c_free() {
free(copy);
}
};
print c_dup('Hello'), "\n";
c_free(); |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Pascal | Pascal | use Inline C => q{
char *copy;
char * c_dup(char *orig) {
return copy = strdup(orig);
}
void c_free() {
free(copy);
}
};
print c_dup('Hello'), "\n";
c_free(); |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Delphi | Delphi | foo() |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Smalltalk | Smalltalk | Object subclass: CantorSet [
| intervals |
CantorSet class >> new
[^self basicNew
initialize;
yourself]
initialize
[intervals := Array with: (CantorInterval
from: 0
to: 1)]
split
[intervals := intervals gather: [:each | each split]]
displayOn: aStream atScale: aNumber
[| current |
current := 0.
intervals do:
[:each |
(each start - current) * aNumber timesRepeat: [aStream space].
each length * aNumber timesRepeat: [aStream nextPut: $#].
current := each stop].
aStream nl]
]
Interval subclass: CantorInterval [
split
[| oneThird left right |
oneThird := self length / 3.
left := self class
from: start
to: start + oneThird.
right := self class
from: stop - oneThird
to: stop.
^Array
with: left
with: right]
start [^start]
stop [^stop]
length [^stop - start]
printOn: aStream
[aStream << ('%1[%2,%3]' % {self class name. start. stop})]
]
Object subclass: TestCantor [
TestCantor class >> iterations: anInteger
[| cantorset scale count |
scale := 3 raisedTo: anInteger. "Make smallest interval 1"
count := 0.
cantorset := CantorSet new.
[cantorset
displayOn: Transcript
atScale: scale.
count < anInteger] whileTrue:
[cantorset split.
count := count + 1]]
]
TestCantor iterations: 4. |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Racket | Racket |
#lang racket
(define (fold f xs init)
(if (empty? xs)
init
(f (first xs)
(fold f (rest xs) init))))
(fold + '(1 2 3) 0) ; the result is 6
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Raku | Raku | my @list = 1..10;
say [+] @list;
say [*] @list;
say [~] @list;
say min @list;
say max @list;
say [lcm] @list; |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Sidef | Sidef | cartesian([[1,2], [3,4], [5,6]]).say
cartesian([[1,2], [3,4], [5,6]], {|*arr| say arr }) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Harbour | Harbour |
PROCEDURE Main()
LOCAL i
FOR i := 0 to 15
? PadL( i, 2 ) + ": " + hb_StrFormat("%d", Catalan( i ))
NEXT
RETURN
STATIC FUNCTION Catalan( n )
LOCAL i, nCatalan := 1
FOR i := 1 TO n
nCatalan := nCatalan * 2 * (2 * i - 1) / (i + 1)
NEXT
RETURN nCatalan
|
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Haskell | Haskell | import qualified Text.Parsec as P
showExpansion :: String -> String
showExpansion =
(<>) . (<> "\n-->\n") <*> (either show unlines . P.parse parser [])
parser :: P.Parsec String u [String]
parser = expansion P.anyChar
expansion :: P.Parsec String u Char -> P.Parsec String u [String]
expansion =
fmap expand .
P.many .
((P.try alts P.<|> P.try alt1 P.<|> escape) P.<|>) . fmap (pure . pure)
expand :: [[String]] -> [String]
expand = foldr ((<*>) . fmap (<>)) [[]]
alts :: P.Parsec String u [String]
alts = concat <$> P.between (P.char '{') (P.char '}') (alt `sepBy2` P.char ',')
alt :: P.Parsec String u [String]
alt = expansion (P.noneOf ",}")
alt1 :: P.Parsec String u [String]
alt1 =
(\x -> ['{' : (x <> "}")]) <$>
P.between (P.char '{') (P.char '}') (P.many $ P.noneOf ",{}")
sepBy2 :: P.Parsec String u a -> P.Parsec String u b -> P.Parsec String u [a]
p `sepBy2` sep = (:) <$> p <*> P.many1 (sep >> p)
escape :: P.Parsec String u [String]
escape = pure <$> sequence [P.char '\\', P.anyChar]
main :: IO ()
main =
mapM_
(putStrLn . showExpansion)
[ "~/{Downloads,Pictures}/*.{jpg,gif,png}"
, "It{{em,alic}iz,erat}e{d,}, please."
, "{,{,gotta have{ ,\\, again\\, }}more }cowbell!"
, "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
] |
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 representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #D | D | import std.stdio;
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0) return true;
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true;
}
}
return false;
}
bool isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
void main() {
foreach (kind; ["", "odd ", "prime "]) {
bool quiet = false;
int BigLim = 99999;
int limit = 20;
writefln("First %s %sBrazillion numbers:", limit, kind);
int c = 0;
int n = 7;
while (c < BigLim) {
if (isBrazilian(n)) {
if (!quiet) write(n, ' ');
if (++c == limit) {
writeln("\n");
quiet = true;
}
}
if (quiet && kind != "") continue;
switch (kind) {
case "": n++; break;
case "odd ": n += 2; break;
case "prime ":
while (true) {
n += 2;
if (isPrime(n)) break;
}
break;
default: assert(false);
}
}
if (kind == "") writefln("The %sth Brazillian number is: %s\n", BigLim + 1, n);
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class calender
{
public:
void drawCalender( int y )
{
year = y;
for( int i = 0; i < 12; i++ )
firstdays[i] = getfirstday( i );
isleapyear();
build();
}
private:
void isleapyear()
{
isleap = false;
if( !( year % 4 ) )
{
if( year % 100 ) isleap = true;
else if( !( year % 400 ) ) isleap = true;
}
}
int getfirstday( int m )
{
int y = year;
int f = y + 1 + 3 * m - 1;
m++;
if( m < 3 ) y--;
else f -= int( .4 * m + 2.3 );
f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 );
f %= 7;
return f;
}
void build()
{
int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0;
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
COORD pos = { 0, ystr };
draw();
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 3; j++ )
{
int d = firstdays[fd++], dm = days[m++];
pos.X = d * 3 + start;
SetConsoleCursorPosition( h, pos );
for( int dd = 0; dd < dm; dd++ )
{
if( dd < 9 ) cout << 0 << dd + 1 << " ";
else cout << dd + 1 << " ";
pos.X += 3;
if( pos.X - start > 20 )
{
pos.X = start; pos.Y++;
SetConsoleCursorPosition( h, pos );
}
}
start += 23;
pos.X = start; pos.Y = ystr;
SetConsoleCursorPosition( h, pos );
}
ystr += 9; start = 2;
pos.Y = ystr;
}
}
void draw()
{
system( "cls" );
cout << "+--------------------------------------------------------------------+" << endl;
cout << "| [SNOOPY] |" << endl;
cout << "| |" << endl;
cout << "| == " << year << " == |" << endl;
cout << "+----------------------+----------------------+----------------------+" << endl;
cout << "| JANUARY | FEBRUARY | MARCH |" << endl;
cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "+----------------------+----------------------+----------------------+" << endl;
cout << "| APRIL | MAY | JUNE |" << endl;
cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "+----------------------+----------------------+----------------------+" << endl;
cout << "| JULY | AUGUST | SEPTEMBER |" << endl;
cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "+----------------------+----------------------+----------------------+" << endl;
cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl;
cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "| | | |" << endl;
cout << "+----------------------+----------------------+----------------------+" << endl;
}
int firstdays[12], year;
bool isleap;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
int y;
calender cal;
while( true )
{
system( "cls" );
cout << "Enter the year( yyyy ) --- ( 0 to quit ): ";
cin >> y;
if( !y ) return 0;
cal.drawCalender( y );
cout << endl << endl << endl << endl << endl << endl << endl << endl;
system( "pause" );
}
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #PHP | PHP | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
// var_export() expects class to contain __set_state() method which would import
// data from array. But let's ignore this and remove from result the method which
// sets state and just leave data which can be used everywhere...
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['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 barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #PicoLisp | PicoLisp | (class +Example)
# "_name"
(dm T (Name)
(=: "_name" Name) )
(dm string> ()
(pack "Hello, I am " (: "_name")) )
(====) # Close transient scope
(setq Foo (new '(+Example) "Eric")) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Python | Python | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>> |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Factor | Factor | USING: accessors images images.loader kernel literals math
math.vectors random sets ;
FROM: sets => in? ;
EXCLUDE: sequences => move ;
IN: rosetta-code.brownian-tree
CONSTANT: size 512
CONSTANT: num-particles 30000
CONSTANT: seed { 256 256 }
CONSTANT: spawns { { 10 10 } { 502 10 } { 10 502 } { 502 502 } }
CONSTANT: bg-color B{ 0 0 0 255 }
CONSTANT: fg-color B{ 255 255 255 255 }
: in-bounds? ( loc -- ? )
dup { 0 0 } ${ size 1 - dup } vclamp = ;
: move ( loc -- loc' )
dup 2 [ { 1 -1 } random ] replicate v+ dup in-bounds?
[ nip ] [ drop ] if ;
: grow ( particles -- particles' )
spawns random dup
[ 2over swap in? ] [ drop dup move swap ] until nip
swap [ adjoin ] keep ;
: brownian-data ( -- seq )
HS{ $ seed } clone num-particles 1 - [ grow ] times { }
set-like ;
: blank-bitmap ( -- bitmap )
size sq [ bg-color ] replicate B{ } concat-as ;
: init-img ( -- img )
<image>
${ size size } >>dim
BGRA >>component-order
ubyte-components >>component-type
blank-bitmap >>bitmap ;
: brownian-img ( -- img )
init-img dup brownian-data
[ swap [ fg-color swap first2 ] dip set-pixel-at ] with each
;
: save-brownian-tree-image ( -- )
brownian-img "brownian.png" save-graphic-image ;
MAIN: save-brownian-tree-image |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #C.23 | C# | using System;
namespace BullsnCows
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
KnuthShuffle<int>(ref nums);
int[] chosenNum = new int[4];
Array.Copy(nums, chosenNum, 4);
Console.WriteLine("Your Guess ?");
while (!game(Console.ReadLine(), chosenNum))
{
Console.WriteLine("Your next Guess ?");
}
Console.ReadKey();
}
public static void KnuthShuffle<T>(ref T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(array.Length);
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
public static bool game(string guess, int[] num)
{
char[] guessed = guess.ToCharArray();
int bullsCount = 0, cowsCount = 0;
if (guessed.Length != 4)
{
Console.WriteLine("Not a valid guess.");
return false;
}
for (int i = 0; i < 4; i++)
{
int curguess = (int) char.GetNumericValue(guessed[i]);
if (curguess < 1 || curguess > 9)
{
Console.WriteLine("Digit must be ge greater 0 and lower 10.");
return false;
}
if (curguess == num[i])
{
bullsCount++;
}
else
{
for (int j = 0; j < 4; j++)
{
if (curguess == num[j])
cowsCount++;
}
}
}
if (bullsCount == 4)
{
Console.WriteLine("Congratulations! You have won!");
return true;
}
else
{
Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
return false;
}
}
}
}
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Rust | Rust |
use core::cmp::Ordering;
const STX: char = '\u{0002}';
const ETX: char = '\u{0003}';
// this compare uses simple alphabetical sort, but for the special characters (ETX, STX)
// it sorts them later than alphanumeric characters
pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering {
let mut iter1 = lhs.chars();
let mut iter2 = rhs.chars();
loop {
match (iter1.next(), iter2.next()) {
(Some(lhs), Some(rhs)) => {
if lhs != rhs {
let is_lhs_special = lhs == ETX || lhs == STX;
let is_rhs_special = rhs == ETX || rhs == STX;
let result = if is_lhs_special == is_rhs_special {
lhs.cmp(&rhs)
} else if is_lhs_special {
Ordering::Greater
} else {
Ordering::Less
};
return result;
}
}
(Some(_), None) => return Ordering::Greater,
(None, Some(_)) => return Ordering::Less,
(None, None) => return lhs.cmp(&rhs),
}
}
}
fn burrows_wheeler_transform(input: &str) -> String {
let mut table: Vec<String> = vec![];
// add markers for the start and end
let input_string = format!("{}{}{}", STX, input, ETX);
// create all possible rotations
for (i, _) in input_string.char_indices() {
table.push(format!(
"{}{}",
&input_string[input_string.len() - 1 - i..],
&input_string[0..input_string.len() - 1 - i]
));
}
// sort rows alphabetically
table.sort_unstable_by(|lhs, rhs| special_cmp(&lhs, &rhs));
// return the last column
table
.iter()
.map(|s| s.chars().nth_back(0).unwrap())
.collect::<String>()
}
fn inverse_burrows_wheeler_transform(input: &str) -> String {
let mut table: Vec<String> = vec![String::new(); input.len()];
for _ in 0..input.len() {
// insert the charatcers of the encoded input as a first column for each row
for (j, s) in table.iter_mut().enumerate() {
*s = format!("{}{}", input.chars().nth(j).unwrap(), s);
}
// sort rows alphabetically
table.sort_unstable_by(|lhs, rhs| special_cmp(&lhs, &rhs));
}
// return the row which has the end marker at the last position
table
.into_iter()
.filter(|s| s.ends_with(ETX))
.collect::<String>()
// remove start and markers
.replace(STX, "")
.replace(ETX, "")
}
fn main() {
let input = [
"banana",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
];
for s in input.iter() {
let bwt = burrows_wheeler_transform(s);
let ibwt = inverse_burrows_wheeler_transform(&bwt);
println!("Input: {}", s);
println!("\tBWT: {}", bwt.replace(STX, "^").replace(ETX, "|"));
println!("\tInverse BWT: {}", ibwt);
}
}
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Scala | Scala | import scala.collection.mutable.ArrayBuffer
object BWT {
val STX = '\u0002'
val ETX = '\u0003'
def bwt(s: String): String = {
if (s.contains(STX) || s.contains(ETX)) {
throw new RuntimeException("String can't contain STX or ETX")
}
var ss = STX + s + ETX
var table = new ArrayBuffer[String]()
(0 until ss.length).foreach(_ => {
table += ss
ss = ss.substring(1) + ss.charAt(0)
})
table.sorted.map(a => a.last).mkString
}
def ibwt(r: String): String = {
var table = Array.fill(r.length)("")
(0 until r.length).foreach(_ => {
(0 until r.length).foreach(i => {
table(i) = r.charAt(i) + table(i)
})
table = table.sorted
})
table.indices.foreach(i => {
val row = table(i)
if (row.last == ETX) {
return row.substring(1, row.length - 1)
}
})
""
}
def makePrintable(s: String): String = {
s.replace(STX, '^').replace(ETX, '|')
}
def main(args: Array[String]): Unit = {
val tests = Array("banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
)
tests.foreach(test => {
println(makePrintable(test))
print(" --> ")
try {
val t = bwt(test)
println(makePrintable(t))
val r = ibwt(t)
printf(" --> %s\n", r)
} catch {
case e: Exception => printf("ERROR: %s\n", e.getMessage)
}
println()
})
}
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #BASIC256 | BASIC256 |
# Caeser Cipher
# basic256 1.1.4.0
dec$ = ""
type$ = "cleartext "
input "If decrypting enter " + "<d> " + " -- else press enter > ",dec$ # it's a klooj I know...
input "Enter offset > ", iOffset
if dec$ = "d" then
iOffset = 26 - iOffset
type$ = "ciphertext "
end if
input "Enter " + type$ + "> ", str$
str$ = upper(str$) # a bit of a cheat really, however old school encryption is always upper case
len = length(str$)
for i = 1 to len
iTemp = asc(mid(str$,i,1))
if iTemp > 64 AND iTemp < 91 then
iTemp = ((iTemp - 65) + iOffset) % 26
print chr(iTemp + 65);
else
print chr(iTemp);
end if
next i
|
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
| #Icon_and_Unicon | Icon and Unicon | $define EPSILON 1.0e-15
procedure main()
local e0
local e := 2.0
local fact := 1
local n := 2
repeat {
e0 := e
fact *:= n
n +:= 1
e +:= (1.0 / fact)
if abs(e - e0) < EPSILON then break
}
write("computed e ", e)
write("keyword &e ", &e)
end |
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
| #IS-BASIC | IS-BASIC | 100 PROGRAM "e.bas"
110 LET E1=0:LET E,N,N1=1
120 DO WHILE E<>E1
130 LET E1=E:LET E=E+1/N
140 LET N1=N1+1:LET N=N*N1
150 LOOP
160 PRINT "The value of e =";E |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #MATLAB | MATLAB | function BullsAndCowsPlayer
% Plays the game Bulls and Cows as the player
% Generate list of all possible numbers
nDigits = 4;
lowVal = 1;
highVal = 9;
combs = nchoosek(lowVal:highVal, nDigits);
nCombs = size(combs, 1);
nPermsPerComb = factorial(nDigits);
gList = zeros(nCombs.*nPermsPerComb, nDigits);
for k = 1:nCombs
gList(nPermsPerComb*(k-1)+1:nPermsPerComb*k, :) = perms(combs(k, :));
end
% Prompt user
fprintf('Think of a number with:\n')
fprintf(' %d digits\n', nDigits)
fprintf(' Each digit between %d and %d inclusive\n', lowVal, highVal)
fprintf(' No repeated digits\n')
fprintf('I''ll try to guess that number and you score me:\n')
fprintf(' 1 Bull per correct digit in the correct place\n')
fprintf(' 1 Cow per correct digit in the wrong place\n')
fprintf('Think of your number and press Enter when ready\n')
pause
% Play game until all digits are correct
nBulls = 0;
nGuesses = 0;
while nBulls < 4 && ~isempty(gList)
nList = size(gList, 1);
g = gList(randi(nList), :); % Random guess from list
fprintf('My guess: %s?\n', sprintf('%d', g))
nBulls = input('How many bulls? ');
if nBulls < 4
nCows = input('How many cows? ');
del = false(nList, 1);
for k = 1:nList
del(k) = any([nBulls nCows] ~= CountBullsCows(g, gList(k, :)));
end
gList(del, :) = [];
end
nGuesses = nGuesses+1;
end
if isempty(gList)
fprintf('That''s bull! You messed up your scoring.\n')
else
fprintf('Yay, I won! Only took %d guesses.\n', nGuesses)
end
end
function score = CountBullsCows(guess, correct)
% Checks the guessed array of digits against the correct array to find the score
% Assumes arrays of same length and valid numbers
bulls = guess == correct;
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Phix | Phix | return repeat(' ',left)&s&repeat(' ',right)
|
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Perl | Perl | use Inline C => q{
char *copy;
char * c_dup(char *orig) {
return copy = strdup(orig);
}
void c_free() {
free(copy);
}
};
print c_dup('Hello'), "\n";
c_free(); |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Phix | Phix | without js -- not from a browser, mate!
constant shlwapi = open_dll("shlwapi.dll"),
kernel32 = open_dll("kernel32.dll")
constant xStrDup = define_c_func(shlwapi,"StrDupA",{C_PTR},C_PTR),
xLocalFree = define_c_func(kernel32,"LocalFree",{C_PTR},C_PTR)
constant HelloWorld = "Hello World!"
atom pMem = c_func(xStrDup,{HelloWorld})
?peek_string(pMem)
assert(c_func(xLocalFree,{pMem})==NULL)
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Dragon | Dragon | myMethod() |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Const WIDTH = 81
Const HEIGHT = 5
Dim lines(HEIGHT, WIDTH) As Char
Sub Init()
For i = 0 To HEIGHT - 1
For j = 0 To WIDTH - 1
lines(i, j) = "*"
Next
Next
End Sub
Sub Cantor(start As Integer, len As Integer, index As Integer)
Dim seg As Integer = len / 3
If seg = 0 Then
Return
End If
For i = index To HEIGHT - 1
For j = start + seg To start + seg * 2 - 1
lines(i, j) = " "
Next
Next
Cantor(start, seg, index + 1)
Cantor(start + seg * 2, seg, index + 1)
End Sub
Sub Main()
Init()
Cantor(0, WIDTH, 1)
For i = 0 To HEIGHT - 1
For j = 0 To WIDTH - 1
Console.Write(lines(i, j))
Next
Console.WriteLine()
Next
End Sub
End Module |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #REXX | REXX | /*REXX program demonstrates a method for catamorphism for some simple functions. */
@list= 1 2 3 4 5 6 7 8 9 10
say 'list:' fold(@list, "list")
say ' sum:' fold(@list, "+" )
say 'prod:' fold(@list, "*" )
say ' cat:' fold(@list, "||" )
say ' min:' fold(@list, "min" )
say ' max:' fold(@list, "max" )
say ' avg:' fold(@list, "avg" )
say ' GCD:' fold(@list, "GCD" )
say ' LCM:' fold(@list, "LCM" )
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fold: procedure; parse arg z; arg ,f; z = space(z); BIFs= 'MIN MAX LCM GCD'
za= translate(z, f, ' '); zf= f"("translate(z, ',' , " ")')'
if f== '+' | f=="*" then interpret "return" za
if f== '||' then return space(z, 0)
if f== 'AVG' then interpret "return" fold(z, '+') "/" words(z)
if wordpos(f, BIFs)\==0 then interpret "return" zf
if f=='LIST' | f=="SHOW" then return z
return 'illegal function:' arg(2)
/*──────────────────────────────────────────────────────────────────────────────────────*/
GCD: procedure; $=; do j=1 for arg(); $= $ arg(j)
end /*j*/
parse var $ x z .; if x=0 then x= z /* [↑] build an arg list.*/
x= abs(x)
do k=2 to words($); y= abs( word($, k)); if y=0 then iterate
do until _=0; _= x // y; x= y; y= _
end /*until*/
end /*k*/
return x
/*──────────────────────────────────────────────────────────────────────────────────────*/
LCM: procedure; $=; do j=1 for arg(); $= $ arg(j)
end /*j*/
x= abs(word($, 1)) /* [↑] build an arg list.*/
do k=2 to words($); != abs(word($, k)); if !=0 then return 0
x= x*! / GCD(x, !) /*GCD does the heavy work*/
end /*k*/
return x |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #SQL | SQL | -- set up list 1
CREATE TABLE L1 (VALUE INTEGER);
INSERT INTO L1 VALUES (1);
INSERT INTO L1 VALUES (2);
-- set up list 2
CREATE TABLE L2 (VALUE INTEGER);
INSERT INTO L2 VALUES (3);
INSERT INTO L2 VALUES (4);
-- get the product
SELECT * FROM L1, L2; |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Haskell | Haskell | -- Three infinite lists, corresponding to the three
-- definitions in the problem statement.
cats1 :: [Integer]
cats1 =
(div . product . (enumFromTo . (2 +) <*> (2 *)))
<*> (product . enumFromTo 1) <$> [0 ..]
cats2 :: [Integer]
cats2 =
1 :
fmap
(\n -> sum (zipWith (*) (reverse (take n cats2)) cats2))
[1 ..]
cats3 :: [Integer]
cats3 =
scanl
(\c n -> c * 2 * (2 * n - 1) `div` succ n)
1
[1 ..]
main :: IO ()
main = mapM_ (print . take 15) [cats1, cats2, cats3] |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #J | J |
NB. legit { , and } do not follow a legit backslash:
legit=: 1,_1}.4>(3;(_2[\"1".;._2]0 :0);('\';a.);0 _1 0 1)&;:&.(' '&,)
2 1 1 1 NB. result 0 or 1: initial state
2 2 1 2 NB. result 2 or 3: after receiving a non backslash
1 2 1 2 NB. result 4 or 5: after receiving a backslash
)
expand=:3 :0
Ch=. u:inv y
M=. N=. 1+>./ Ch
Ch=. Ch*-_1^legit y
delim=. 'left comma right'=. u:inv '{,}'
J=. i.K=. #Ch
while. M=. M+1 do.
candidates=. i.0 2
for_check.I. comma=Ch do.
begin=. >./I. left=check{. Ch
end=. check+<./I. right=check}. Ch
if. K>:end-begin do.
candidates=. candidates,begin,end
end.
end.
if. 0=#candidates do. break. end.
'begin end'=. candidates{~(i.>./) -/"1 candidates
ndx=. I.(begin<:J)*(end>:J)*Ch e. delim
Ch=. M ndx} Ch
end.
T=. ,<Ch
for_mark. |.N}.i.M do.
T=. ; mark divide each T
end.
u: each |each T
)
divide=:4 :0
if. -.x e. y do. ,<y return. end.
mask=. x=y
prefix=. < y #~ -.+./\ mask
suffix=. < y #~ -.+./\. mask
options=. }:mask <;._1 y
prefix,each options,each suffix
) |
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 representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #Delphi | Delphi |
program Brazilian_numbers;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TBrazilianNumber = record
private
FValue: Integer;
FIsBrazilian: Boolean;
FIsPrime: Boolean;
class function SameDigits(a, b: Integer): Boolean; static;
class function CheckIsBrazilian(a: Integer): Boolean; static;
class function CheckIsPrime(a: Integer): Boolean; static;
constructor Create(const Number: Integer);
procedure SetValue(const Value: Integer);
public
property Value: Integer read FValue write SetValue;
property IsBrazilian: Boolean read FIsBrazilian;
property IsPrime: Boolean read FIsPrime;
end;
{ TBrazilianNumber }
class function TBrazilianNumber.CheckIsBrazilian(a: Integer): Boolean;
var
b: Integer;
begin
if (a < 7) then
Exit(false);
if (a mod 2 = 0) then
Exit(true);
for b := 2 to a - 2 do
begin
if (sameDigits(a, b)) then
exit(True);
end;
Result := False;
end;
constructor TBrazilianNumber.Create(const Number: Integer);
begin
SetValue(Number);
end;
class function TBrazilianNumber.CheckIsPrime(a: Integer): Boolean;
var
d: Integer;
begin
if (a < 2) then
exit(False);
if (a mod 2) = 0 then
exit(a = 2);
if (a mod 3) = 0 then
exit(a = 3);
d := 5;
while (d * d <= a) do
begin
if (a mod d = 0) then
Exit(false);
inc(d, 2);
if (a mod d = 0) then
Exit(false);
inc(d, 4);
end;
Result := True;
end;
class function TBrazilianNumber.SameDigits(a, b: Integer): Boolean;
var
f: Integer;
begin
f := a mod b;
a := a div b;
while a > 0 do
begin
if (a mod b) <> f then
exit(False);
a := a div b;
end;
Result := True;
end;
procedure TBrazilianNumber.SetValue(const Value: Integer);
begin
if Value < 0 then
FValue := 0
else
FValue := Value;
FIsBrazilian := CheckIsBrazilian(FValue);
FIsPrime := CheckIsPrime(FValue);
end;
const
TextLabel: array[0..2] of string = ('', 'odd', 'prime');
var
Number: TBrazilianNumber;
Count: array[0..2] of Integer;
i, j, left, Num: Integer;
data: array[0..2] of string;
begin
left := 3;
for i := 0 to 99999 do
begin
if Number.Create(i).IsBrazilian then
for j := 0 to 2 do
begin
if (Count[j] >= 20) and (j > 0) then
continue;
case j of
0:
begin
inc(Count[j]);
Num := i;
if (Count[j] <= 20) then
data[j] := data[j] + i.ToString + ' '
else
Continue;
end;
1:
begin
if Odd(i) then
begin
inc(Count[j]);
data[j] := data[j] + i.ToString + ' ';
end;
end;
2:
begin
if Number.IsPrime then
begin
inc(Count[j]);
data[j] := data[j] + i.ToString + ' ';
end;
end;
end;
if Count[j] = 20 then
dec(left);
end;
if left = 0 then
Break;
end;
while Count[0] < 100000 do
begin
inc(Num);
if Number.Create(Num).IsBrazilian then
inc(Count[0]);
end;
for i := 0 to 2 do
begin
Writeln(#10'First 20 ' + TextLabel[i] + ' Brazilian numbers:');
Writeln(data[i]);
end;
Writeln('The 100,000th Brazilian number: ', Num);
readln;
end.
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Clojure | Clojure | (require '[clojure.string :only [join] :refer [join]])
(def day-row "Su Mo Tu We Th Fr Sa")
(def col-width (count day-row))
(defn month-to-word
"Translate a month from 0 to 11 into its word representation."
[month]
((vec (.getMonths (new java.text.DateFormatSymbols))) month))
(defn month [date]
(.get date (java.util.Calendar/MONTH)))
(defn total-days-in-month [date]
(.getActualMaximum date (java.util.Calendar/DAY_OF_MONTH)))
(defn first-weekday [date]
(.get date (java.util.Calendar/DAY_OF_WEEK)))
(defn normal-date-string
"Returns a formatted list of strings of the days of the month."
[date]
(map #(join " " %)
(partition 7
(concat
(repeat (dec (first-weekday date)) " ")
(map #(format "%2s" %)
(range 1 (inc (total-days-in-month date))))
(repeat (- 42 (total-days-in-month date)
(dec (first-weekday date)) ) " ")))))
(defn oct-1582-string
"Returns a formatted list of strings of the days of the month of October 1582."
[date]
(map #(join " " %)
(partition 7
(concat
(repeat (dec (first-weekday date)) " ")
(map #(format "%2s" %)
(concat (range 1 5)
(range 15 (inc (total-days-in-month date)))))
(repeat (- 42
(count (concat (range 1 5)
(range 15
(inc (total-days-in-month date)))))
(dec (first-weekday date)) ) " ")))))
(defn center-string
"Returns a string that is WIDTH long with STRING centered in it."
[string width]
(let [pad (- width (count string))
lpad (quot pad 2)
rpad (- pad (quot pad 2))]
(if (<= pad 0)
string
(str (apply str (repeat lpad " ")) ; remove vector
string
(apply str (repeat rpad " "))))))
(defn calc-columns
"Calculates the number of columns given the width in CHARACTERS and the
MARGIN SIZE."
[characters margin-size]
(loop [cols 0 excess characters ]
(if (>= excess col-width)
(recur (inc cols) (- excess (+ margin-size col-width)))
cols)))
(defn month-vector
"Returns a vector with the month name, day-row and days
formatted for printing."
[date]
(vec (concat
(vector (center-string (month-to-word (month date)) col-width))
(vector day-row)
(if (and (= 1582 (.get date (java.util.Calendar/YEAR)))
(= 9 (month date)))
(oct-1582-string date)
(normal-date-string date)))))
(defn year-vector [date]
"Returns a 2d vector of all the months in the year of DATE."
(loop [m [] c (month date)]
(if (= c 11 )
(conj m (month-vector date))
(recur (conj m (month-vector date))
(do (.add date (java.util.Calendar/MONTH ) 1)
(month date))))))
(defn print-months
"Prints the months to standard output with NCOLS and MARGIN."
[ v ncols margin]
(doseq [r (range (Math/ceil (/ 12 ncols)))]
(do (doseq [i (range 8)]
(do (doseq [c (range (* r ncols) (* (+ r 1) ncols))
:while (< c 12)]
(printf (str (apply str (repeat margin " ")) "%s")
(get-in v [c i])))
(println)))
(println))))
(defn print-cal
"(print-cal [year [width [margin]]])
Prints out the calendar for a given YEAR with WIDTH characters wide and
with MARGIN spaces between months."
([]
(print-cal 1969 80 2))
([year]
(print-cal year 80 2))
([year width]
(print-cal year width 2))
([year width margin]
(assert (>= width (count day-row)) "Width should be more than 20.")
(assert (> margin 0) "Margin needs to be more than 0.")
(let [date (new java.util.GregorianCalendar year 0 1)
column-count (calc-columns width margin)
total-size (+ (* column-count (count day-row))
(* (dec column-count) margin))]
(println (center-string "[Snoopy Picture]" total-size))
(println (center-string (str year) total-size))
(println)
(print-months (year-vector date) column-count margin)))) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Raku | Raku | class Foo {
has $!shyguy = 42;
}
my Foo $foo .= new;
say $foo.^attributes.first('$!shyguy').get_value($foo); |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Ruby | Ruby |
class Example
def initialize
@private_data = "nothing" # instance variables are always private
end
private
def hidden_method
"secret"
end
end
example = Example.new
p example.private_methods(false) # => [:hidden_method]
#p example.hidden_method # => NoMethodError: private method `name' called for #<Example:0x101308408>
p example.send(:hidden_method) # => "secret"
p example.instance_variables # => [:@private_data]
p example.instance_variable_get :@private_data # => "nothing"
p example.instance_variable_set :@private_data, 42 # => 42
p example.instance_variable_get :@private_data # => 42
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Scala | Scala | class Example(private var name: String) {
override def toString = s"Hello, I am $name"
}
object BreakPrivacy extends App {
val field = classOf[Example].getDeclaredField("name")
field.setAccessible(true)
val foo = new Example("Erik")
println(field.get(foo))
field.set(foo, "Edith")
println(foo)
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Fantom | Fantom |
using fwt
using gfx
class Main
{
public static Void main ()
{
particles := Particles (300, 200)
1000.times { particles.addParticle } // add 1000 particles
Window // open up a display for the final tree
{
title = "Brownian Tree"
EdgePane
{
center = ScrollPane { content = ParticleCanvas(particles) }
},
}.open
}
}
class Particles
{
Bool[][] image
Int height
Int width
new make (Int height, Int width)
{
this.height = height
this.width = width
// set up initial image as an array of booleans with one set cell
image = [,]
width.times |w|
{
row := [,]
height.times { row.add (false) }
image.add (row)
}
image[Int.random(0..<width)][Int.random(0..<height)] = true
}
Bool get (Int w, Int h) { return image[w][h] }
Void addParticle ()
{
x := Int.random(0..<width)
y := Int.random(0..<height)
Int dx := 0
Int dy := 0
while (!image[x][y]) // loop until hit existing part of the tree
{
dx = [-1,0,1].random
dy = [-1,0,1].random
if ((0..<width).contains(x + dx))
x += dx
else // did not change x, so set dx = 0
dx = 0
if ((0..<height).contains(y + dy))
y += dy
else
dy = 0
}
// put x,y back to just before move onto existing part of tree
x -= dx
y -= dy
image[x][y] = true
}
}
class ParticleCanvas : Canvas
{
Particles particles
new make (Particles particles) { this.particles = particles }
// provides canvas size for parent scrollpane
override Size prefSize(Hints hints := Hints.defVal)
{
Size(particles.width, particles.height)
}
// repaint the display
override Void onPaint (Graphics g)
{
g.brush = Color.black
g.fillRect(0, 0, size.w, size.h)
g.brush = Color.green
particles.width.times |w|
{
particles.height.times |h|
{
if (particles.get(w, h)) // draw a 1x1 square for each set particle
g.fillRect (w, h, 1, 1)
}
}
}
}
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
void game()
{
typedef std::string::size_type index;
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Sidef | Sidef | class BurrowsWheelerTransform (String L = "\002") {
method encode(String s) {
assert(!s.contains(L), "String cannot contain `#{L.dump}`")
s = (L + s)
s.len.of{|i| s.substr(i) + s.substr(0, i) }.sort.map{.last}.join
}
method decode(String s) {
var t = s.len.of("")
var c = s.chars
{ t = (c »+« t).sort } * s.len
t.first { .begins_with(L) }.substr(L.len)
}
}
var tests = [
"banana", "appellee", "dogwood", "TOBEORNOTTOBEORTOBEORNOT"
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
]
var bwt = BurrowsWheelerTransform(L: '$')
tests.each { |str|
var enc = bwt.encode(str)
var dec = bwt.decode(enc)
say "BWT(#{dec.dump}) = #{enc.dump}"
assert_eq(str, dec)
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #BBC_BASIC | BBC BASIC | plaintext$ = "Pack my box with five dozen liquor jugs"
PRINT plaintext$
key% = RND(25)
cyphertext$ = FNcaesar(plaintext$, key%)
PRINT cyphertext$
decyphered$ = FNcaesar(cyphertext$, 26-key%)
PRINT decyphered$
END
DEF FNcaesar(text$, key%)
LOCAL I%, C%
FOR I% = 1 TO LEN(text$)
C% = ASC(MID$(text$,I%))
IF (C% AND &1F) >= 1 AND (C% AND &1F) <= 26 THEN
C% = (C% AND &E0) OR (((C% AND &1F) + key% - 1) MOD 26 + 1)
MID$(text$, I%, 1) = CHR$(C%)
ENDIF
NEXT
= text$
|
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
| #J | J | NB. rational one half times pi to the first power
NB. pi to the power of negative two
NB. two oh in base 111
NB. complex number length 1, angle in degrees 180
1r2p1 1p_2 111b20 1ad270
1.5708 0.101321 222 0j_1
|
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
| #Java | Java | public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static void main(String[] args) {
long fact = 1;
double e = 2.0;
int n = 2;
double e0;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.abs(e - e0) >= EPSILON);
System.out.printf("e = %.15f\n", e);
}
} |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Nim | Nim | import parseutils
import random
import sequtils
import strformat
import strutils
const
Digits = "123456789"
DigitSet = {Digits[0]..Digits[^1]}
Size = 4
InvalidScore = -1
type
Digit = range['1'..'9']
Score = tuple[bulls, cows: int]
HistItem = tuple[guess: string, bulls, cows: int]
#---------------------------------------------------------------------------------------------------
proc buildChoices(digits: set[Digit]; size: Natural): seq[string] =
## Build the list of choices when starting the game.
if size == 0:
return @[""]
for d in digits:
for s in buildChoices(digits - {d}, size - 1):
result.add(d & s)
#---------------------------------------------------------------------------------------------------
proc getValues(): Score =
## Read the number of bulls and cows provided by the user.
let input = stdin.readLine().strip()
let fields = input.splitWhitespace()
if fields.len != 2 or
fields[0].parseInt(result.bulls, 0) == 0 or result.bulls notin 0..Size or
fields[1].parseInt(result.cows, 0) == 0 or result.cows notin 0..Size:
echo &"Wrong input; expected two number between 0 and {Size}"
return (InvalidScore, InvalidScore)
if result.bulls + result.cows > Size:
echo &"Total number of bulls and cows exceeds {Size}"
return (InvalidScore, InvalidScore)
#---------------------------------------------------------------------------------------------------
func score(value, guess: string): Score =
## Return the score of "guess" against "value".
for idx, digit in guess:
if digit == value[idx]:
inc result.bulls
elif digit in value:
inc result.cows
#---------------------------------------------------------------------------------------------------
proc findError(history: seq[HistItem]) =
## Find the scoring error.
var value: string
## Get the number to find.
while true:
stdout.write("What was the number to find? ")
value = stdin.readLine().strip()
if value.len == Size and allCharsInSet(value, DigitSet) and value.deduplicate.len == Size:
break
# Find inconsistencies.
for (guess, userbulls, usercows) in history:
let (bulls, cows) = score(guess, value)
if userbulls != bulls or usercows != cows:
echo &"For guess {guess}, score was wrong:"
echo &" Expected {bulls} / {cows}, got {userBulls} / {userCows}."
#---------------------------------------------------------------------------------------------------
func suffix(n: Positive): string =
## Return the suffix for an ordinal.
case n
of 1: "st"
of 2: "nd"
of 3: "rd"
else: "th"
#---------------------------------------------------------------------------------------------------
var history: seq[HistItem]
randomize()
var choices = buildChoices(DigitSet, Size)
choices.shuffle()
echo "Choose a number with four unique digits between 1 and 9."
echo "Give the number of bulls and cows separated by one or more spaces."
var guesses = 0
var remaining: seq[string]
while true:
inc guesses
var userbulls, usercows: int
let guess = choices.pop()
echo &"My {guesses}{suffix(guesses)} guess is {guess}"
# Get scoring.
while true:
stdout.write("How many bulls and cows? ")
(userbulls, usercows) = getValues()
if userbulls != InvalidScore and usercows != InvalidScore:
break
if userbulls == Size:
echo &"Victory! I found the number in {guesses} attempts."
break
history.add((guess, userbulls, usercows))
# Eliminate incompatible choices.
remaining.setLen(0)
for choice in choices:
let (bulls, cows) = score(guess, choice)
if bulls == userbulls and cows == usercows:
remaining.add(choice)
if remaining.len == 0:
echo &"There is an impossibility. For some guess you made an error in scoring."
history.findError()
break
choices.shallowCopy(remaining) |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #PHP | PHP | <?PHP
ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
JANUARY FEBRUARY MARCH APRIL MAY JUNE
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
31 30
JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
; // MAGICAL SEMICOLON |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #PicoLisp | PicoLisp | (load "@lib/gcc.l")
(gcc "str" NIL # The 'gcc' function passes all text
'duptest ) # until /**/ to the C compiler
any duptest(any ex) {
any x = evSym(cdr(ex)); // Accept a symbol (string)
char str[bufSize(x)]; // Create a buffer to unpack the name
char *s;
bufString(x, str); // Upack the string
s = strdup(str); // Make a duplicate
x = mkStr(s); // Build a new Lisp string
free(s); // Dispose the duplicate
return x;
}
/**/
(println 'Duplicate (duptest "Hello world!")) |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #PL.2FI | PL/I | declare strdup entry (character (30) varyingz) options (fastcall16);
put (strdup('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
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Dyalect | Dyalect | func foo() { }
foo() |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Vlang | Vlang | const (
width = 81
height = 5
)
fn cantor(mut lines [][]u8, start int, len int, index int) {
seg := len / 3
if seg == 0 {
return
}
for i in index.. height {
for j in start + seg..start + 2 * seg {
lines[i][j] = ' '[0]
}
}
cantor(mut lines, start, seg, index + 1)
cantor(mut lines, start + seg * 2, seg, index + 1)
}
fn main() {
mut lines := [][]u8{len:height, init: []u8{len:width, init:'*'[0]}}
cantor(mut lines, 0, width, 1)
for line in lines {
println(line.bytestr())
}
} |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Wren | Wren | var width = 81
var height = 5
var lines = [[]] * height
for (i in 0...height) lines[i] = ["*"] * width
var cantor // recursive so need to declare variable first
cantor = Fn.new { |start, len, index|
var seg = (len/3).floor
if (seg == 0) return
for (i in index...height) {
for (j in (start+seg)...(start+seg*2)) lines[i][j] = " "
}
cantor.call(start, seg, index + 1)
cantor.call(start + seg*2, seg, index + 1)
}
cantor.call(0, width, 1)
for (i in 0...height) System.print(lines[i].join()) |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Ring | Ring |
n = list(10)
for i = 1 to 10
n[i] = i
next
see " +: " + cat(10,"+") + nl+
" -: " + cat(10,"-") + nl +
" *: " + cat(10,"*") + nl +
" /: " + cat(10,"/") + nl+
" ^: " + cat(10,"^") + nl +
"min: " + cat(10,"min") + nl+
"max: " + cat(10,"max") + nl+
"avg: " + cat(10,"avg") + nl +
"cat: " + cat(10,"cat") + nl
func cat count,op
cat = n[1]
cat2 = ""
for i = 2 to count
switch op
on "+" cat += n[i]
on "-" cat -= n[i]
on "*" cat *= n[i]
on "/" cat /= n[i]
on "^" cat ^= n[i]
on "max" cat = max(cat,n[i])
on "min" cat = min(cat,n[i])
on "avg" cat += n[i]
on "cat" cat2 += string(n[i])
off
next
if op = "avg" cat = cat / count ok
if op = "cat" decimals(0) cat = string(n[1])+cat2 ok
return cat
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Ruby | Ruby | # sum:
p (1..10).inject(:+)
# smallest number divisible by all numbers from 1 to 20:
p (1..20).inject(:lcm) #lcm: lowest common multiple
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Standard_ML | Standard ML | fun prodList (nil, _) = nil
| prodList ((x::xs), ys) = map (fn y => (x,y)) ys @ prodList (xs, ys)
fun naryProdList zs = foldl (fn (xs, ys) => map op:: (prodList (xs, ys))) [[]] (rev zs) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every writes(catalan(0 to 14)," ")
end
procedure catalan(n) # return catalan(n) or fail
static M
initial M := table()
n=0 & return 1
if n > 0 then
return (n = 1) | \M[n] | ( M[n] := (2*(2*n-1)*catalan(n-1))/(n+1))
end |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Java | Java | public class BraceExpansion {
public static void main(String[] args) {
for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
System.out.println();
expand(s);
}
}
public static void expand(String s) {
expandR("", s, "");
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0;
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ");
StringBuilder sb = null;
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1;
sb = new StringBuilder(s);
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2);
depth = (c == '{') ? ++depth : depth;
depth = (c == '}') ? --depth : depth;
if (c == ',' && depth == 1) {
sb.setCharAt(i2, '\u0000');
} else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
break outer;
}
}
if (i1 == -1) {
if (suf.length() > 0)
expandR(pre + s, suf, "");
else
System.out.printf("%s%s%s%n", pre, s, suf);
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
}
}
} |
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 representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #F.23 | F# |
// Generate Brazilian sequence. Nigel Galloway: August 13th., 2019
let isBraz α=let mutable n,i,g=α,α+1,1 in (fun β->(while (i*g)<β do if g<α-1 then g<-g+1 else (n<-n*α; i<-n+i; g<-1)); β=i*g)
let Brazilian()=let rec fN n g=seq{if List.exists(fun α->α n) g then yield n
yield! fN (n+1) ((isBraz (n-1))::g)}
fN 4 [isBraz 2]
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. CALEND.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-DAY-NAMES-DEF.
03 FILLER PIC X(09) VALUE 'SUNDAY '.
03 FILLER PIC X(09) VALUE 'MONDAY '.
03 FILLER PIC X(09) VALUE 'TUESDAY '.
03 FILLER PIC X(09) VALUE 'WEDNESDAY'.
03 FILLER PIC X(09) VALUE 'THURSDAY '.
03 FILLER PIC X(09) VALUE 'FRIDAY '.
03 FILLER PIC X(09) VALUE 'SATURDAY '.
01 FILLER REDEFINES WS-DAY-NAMES-DEF.
03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES.
01 WS-MTH-INFO-DEF.
03 FILLER PIC X(11) VALUE 'JANUARY 31'.
03 FILLER PIC X(11) VALUE 'FEBRUARY 28'.
03 FILLER PIC X(11) VALUE 'MARCH 31'.
03 FILLER PIC X(11) VALUE 'APRIL 30'.
03 FILLER PIC X(11) VALUE 'MAY 31'.
03 FILLER PIC X(11) VALUE 'JUNE 30'.
03 FILLER PIC X(11) VALUE 'JULY 31'.
03 FILLER PIC X(11) VALUE 'AUGUST 31'.
03 FILLER PIC X(11) VALUE 'SEPTEMBER30'.
03 FILLER PIC X(11) VALUE 'OCTOBER 31'.
03 FILLER PIC X(11) VALUE 'NOVEMBER 30'.
03 FILLER PIC X(11) VALUE 'DECEMBER 31'.
01 FILLER REDEFINES WS-MTH-INFO-DEF.
03 WS-MTH-INFO-TABLE OCCURS 12 TIMES.
05 WS-MTH-INFO-NAME PIC X(09).
05 WS-MTH-INFO-DAYS PIC 9(02).
01 WS-MTH-AREA.
03 WS-MTH-DD PIC S99.
03 WS-DAY1 PIC 9.
03 WS-DAYS PIC 99.
03 WS-DD PIC 9.
03 WS-WK PIC 9.
03 WS-MM PIC 99.
03 WS-QQ PIC 99.
03 WS-MTH-MONTH OCCURS 12 TIMES.
05 WS-MTH-WEEK OCCURS 6 TIMES.
07 WS-DAY-FLD OCCURS 7 TIMES.
09 WS-DAY PIC ZZ.
01 INPDATE-RECORD.
05 INPD-YEAR PIC 9(04).
05 FILLER PIC X(01).
05 INPD-MONTH PIC 9(02).
05 FILLER PIC X(01).
05 INPD-DAY PIC 9(02).
01 WMS-DOW PIC 9(01).
01 WS-PRT PIC X(132).
01 WS-COL PIC 9(03) VALUE 0.
01 WS-PP PIC 9(03) VALUE 0.
01 WS-CFGN.
03 FILLER PIC 9(03) VALUE 80.
03 FILLER PIC 9(02) VALUE 5.
03 FILLER PIC 9(01) VALUE 1.
03 FILLER PIC 9(02) VALUE 5.
03 FILLER PIC 9(01) VALUE 2.
01 WS-CFGW.
03 FILLER PIC 9(03) VALUE 120.
03 FILLER PIC 9(02) VALUE 10.
03 FILLER PIC 9(01) VALUE 2.
03 FILLER PIC 9(02) VALUE 10.
03 FILLER PIC 9(01) VALUE 3.
01 WS-CFG.
03 WS-LS PIC 9(03) VALUE 120.
03 WS-LMAR PIC 9(02) VALUE 10.
03 WS-SPBD PIC 9(01) VALUE 2.
03 WS-SPBC PIC 9(02) VALUE 10.
03 WS-DNMW PIC 9(01) VALUE 3.
PROCEDURE DIVISION.
MOVE '1969-01-01' TO INPDATE-RECORD
MOVE WS-CFGN TO WS-CFG
IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0
OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0
AND
FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0))
MOVE 29 TO WS-MTH-INFO-DAYS (02)
ELSE
MOVE 28 TO WS-MTH-INFO-DAYS (02)
END-IF
PERFORM VARYING WS-MM FROM 1 BY +1
UNTIL WS-MM > 12
MOVE WS-MM TO INPD-MONTH
CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW
COMPUTE WS-MTH-DD = 1 - WMS-DOW
COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH)
PERFORM VARYING WS-WK FROM 1 BY +1
UNTIL WS-WK > 6
PERFORM VARYING WS-DD FROM 1 BY +1
UNTIL WS-DD > 7
COMPUTE WS-MTH-DD = WS-MTH-DD + 1
IF (WS-MTH-DD < 1)
OR (WS-MTH-DD > WS-DAYS)
MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD)
ELSE
MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD)
END-IF
END-PERFORM
END-PERFORM
END-PERFORM
COMPUTE WS-MM = 0
PERFORM VARYING WS-QQ FROM 1 BY +1
UNTIL WS-QQ > 4
INITIALIZE WS-PRT
COMPUTE WS-PP = 1
PERFORM VARYING WS-COL FROM 1 BY +1
UNTIL WS-COL > 3
COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL
IF WS-COL = 1
COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW
ELSE
COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW
END-IF
MOVE WS-MTH-INFO-NAME (WS-MM)
TO WS-PRT(WS-PP:9)
COMPUTE WS-PP
= WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1)
- 4
MOVE INPD-YEAR TO WS-PRT (WS-PP:4)
COMPUTE WS-PP = WS-PP + 4
END-PERFORM
DISPLAY WS-PRT (1:WS-LS)
INITIALIZE WS-PRT
COMPUTE WS-PP = 1
PERFORM VARYING WS-COL FROM 1 BY +1
UNTIL WS-COL > 3
COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL
IF WS-COL = 1
COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW
ELSE
COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW
END-IF
PERFORM VARYING WS-DD FROM 1 BY +1
UNTIL WS-DD > 7
IF WS-DD > 1
COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW
END-IF
MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW)
TO WS-PRT (WS-PP:WS-DNMW)
COMPUTE WS-PP = WS-PP + WS-DNMW
END-PERFORM
END-PERFORM
DISPLAY WS-PRT (1:WS-LS)
PERFORM VARYING WS-WK FROM 1 BY +1
UNTIL WS-WK > 6
INITIALIZE WS-PRT
COMPUTE WS-PP = 1
PERFORM VARYING WS-COL FROM 1 BY +1
UNTIL WS-COL > 3
COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL
IF WS-COL = 1
COMPUTE WS-PP = WS-PP + WS-LMAR
ELSE
COMPUTE WS-PP = WS-PP + WS-SPBC
END-IF
PERFORM VARYING WS-DD FROM 1 BY +1
UNTIL WS-DD > 7
IF WS-DD > 1
COMPUTE WS-PP = WS-PP + WS-SPBD
END-IF
MOVE WS-DAY (WS-MM, WS-WK, WS-DD)
TO WS-PRT (WS-PP:2)
COMPUTE WS-PP = WS-PP + 2
END-PERFORM
END-PERFORM
DISPLAY WS-PRT (1:WS-LS)
END-PERFORM
DISPLAY ' '
END-PERFORM
GOBACK
.
END PROGRAM CALEND.
IDENTIFICATION DIVISION.
PROGRAM-ID. DATE2DOW.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WMS-WORK-AREA.
03 WMS-YEAR PIC 9(04).
03 WMS-MONTH PIC 9(02).
03 WMS-CSYS PIC 9(01) VALUE 1.
03 WMS-SUM pic 9(04).
LINKAGE SECTION.
01 INPDATE-RECORD.
05 INPD-YEAR PIC 9(04).
05 FILLER PIC X(01).
05 INPD-MONTH PIC 9(02).
05 FILLER PIC X(01).
05 INPD-DAY PIC 9(02).
01 WMS-DOW PIC 9(01).
PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW.
1010-CONVERT-DATE-TO-DOW.
IF INPD-MONTH < 3
COMPUTE WMS-MONTH = INPD-MONTH + 12
COMPUTE WMS-YEAR = INPD-YEAR - 1
ELSE
COMPUTE WMS-MONTH = INPD-MONTH
COMPUTE WMS-YEAR = INPD-YEAR
END-IF
COMPUTE WMS-SUM =
( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR
+ FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10)
+ FUNCTION INTEGER ( WMS-YEAR / 4 )
- FUNCTION INTEGER ( WMS-YEAR / 100 )
+ FUNCTION INTEGER ( WMS-YEAR / 400 )
+ WMS-CSYS )
COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1
GOBACK
.
END PROGRAM DATE2DOW.
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Sidef | Sidef | class Example {
has public = "foo"
method init {
self{:private} = "secret"
}
}
var obj = Example();
# Access public attributes
say obj.public; #=> "foo"
say obj{:public}; #=> "foo"
# Access private attributes
say obj{:private}; #=> "secret" |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Swift | Swift | struct Example {
var notSoSecret = "Hello!"
private var secret = 42
}
let e = Example()
let mirror = Mirror(reflecting: e)
if let secret = mirror.children.filter({ $0.label == "secret" }).first?.value {
print("Value of the secret is \(secret)")
}
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create Example {
variable name
constructor n {set name $n}
method print {} {puts "Hello, I am $name"}
}
set e [Example new "Eric"]
$e print
set [info object namespace $e]::name "Edith"
$e print |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Reflection
' MyClass is a VB keyword.
Public Class MyClazz
Private answer As Integer = 42
End Class
Public Class Program
Public Shared Sub Main()
Dim myInstance = New MyClazz()
Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim answer = fieldInfo.GetValue(myInstance)
Console.WriteLine(answer)
End Sub
End Class |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Fortran | Fortran | program BrownianTree
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: num_particles = 1000
integer, parameter :: wsize = 800
integer, dimension(wsize, wsize) :: world
type(rgbimage) :: gworld
integer :: x, y
! init seed
call init_random_seed
world = 0
call draw_brownian_tree(world)
call alloc_img(gworld, wsize, wsize)
call fill_img(gworld, rgb(0,0,0))
do y = 1, wsize
do x = 1, wsize
if ( world(x, y) /= 0 ) then
call put_pixel(gworld, x, y, rgb(255, 255, 255))
end if
end do
end do
open(unit=10, file='browniantree.ppm', action='write')
call output_ppm(10, gworld)
close(10)
call free_img(gworld)
contains
! this code is taken from the GNU gfortran online doc
subroutine init_random_seed
integer :: i, n, clock
integer, dimension(:), allocatable :: seed
call random_seed(size = n)
allocate(seed(n))
call system_clock(count = clock)
seed = clock + 37 * (/ ( i - 1, i = 1, n) /)
call random_seed(put = seed)
deallocate(seed)
end subroutine init_random_seed
function randbetween(a, b) result(res) ! suppose a < b
integer, intent(in) :: a, b
integer :: res
real :: r
call random_number(r)
res = a + int((b-a)*r + 0.5)
end function randbetween
function bounded(v, ll, ul) result(res)
integer, intent(in) :: v, ll, ul
logical res
res = ( v >= ll ) .and. ( v <= ul )
end function bounded
subroutine draw_brownian_tree(w)
integer, dimension(:,:), intent(inout) :: w
integer :: px, py, dx, dy, i
integer :: xsize, ysize
xsize = size(w, 1)
ysize = size(w, 2)
w(randbetween(1, xsize), randbetween(1, ysize)) = 1
do i = 1, num_particles
px = randbetween(1, xsize)
py = randbetween(1, ysize)
do
dx = randbetween(-1, 1)
dy = randbetween(-1, 1)
if ( .not. bounded(dx+px, 1, xsize) .or. .not. bounded(dy+py, 1, ysize) ) then
px = randbetween(1, xsize)
py = randbetween(1, ysize)
else if ( w(px+dx, py+dy) /= 0 ) then
w(px, py) = 1
exit
else
py = py + dy
px = px + dx
end if
end do
end do
end subroutine draw_brownian_tree
end program |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
function generateDigits() =>
random.elements(1..9).distinct.take(4).sequence();
function validate(String guess) {
variable value ok = true;
if (!guess.every((Character element) => element.digit)) {
print("numbers only, please");
ok = false;
}
if ('0' in guess) {
print("only 1 to 9, please");
ok = false;
}
if (guess.distinct.shorterThan(guess.size)) {
print("no duplicates, please");
ok = false;
}
if (guess.size != 4) {
print("4 digits please");
ok = false;
}
return ok;
}
function score({Integer*} target, {Integer*} guess) {
variable value bulls = 0;
variable value cows = 0;
for ([a, b] in zipPairs(target, guess)) {
if (a == b) {
bulls++;
} else if (target.contains(b)) {
cows++;
}
}
return [bulls, cows];
}
while (true) {
value digits = generateDigits();
print("I have chosen my four digits, please guess what they are.
Use only the digits 1 to 9 with no duplicates and enter them with no spaces. eg 1234
Enter q or Q to quit.");
while (true) {
if (exists line = process.readLine()) {
if (line.uppercased == "Q") {
return;
}
if (validate(line)) {
value guessDigits = line.map((Character element) => Integer.parse(element.string)).narrow<Integer>();
value [bulls, cows] = score(digits, guessDigits);
if (bulls == 4) {
print("You win!");
break;
}
else {
print("Bulls: ``bulls``, Cows: ``cows``");
}
}
}
}
}
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Swift | Swift | import Foundation
private let stx = "\u{2}"
private let etx = "\u{3}"
func bwt(_ str: String) -> String? {
guard !str.contains(stx), !str.contains(etx) else {
return nil
}
let ss = stx + str + etx
let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()
return String(table.map({str in str.last!}))
}
func ibwt(_ str: String) -> String? {
let len = str.count
var table = Array(repeating: "", count: len)
for _ in 0..<len {
for i in 0..<len {
table[i] = String(str[str.index(str.startIndex, offsetBy: i)]) + table[i]
}
table.sort()
}
for row in table where row.hasSuffix(etx) {
return String(row.dropFirst().dropLast())
}
return nil
}
func readableBwt(_ str: String) -> String {
return str.replacingOccurrences(of: "\u{2}", with: "^").replacingOccurrences(of: "\u{3}", with: "|")
}
let testCases = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u{2}ABC\u{3}"
]
for test in testCases {
let b = bwt(test) ?? "error"
let c = ibwt(b) ?? "error"
print("\(readableBwt(test)) -> \(readableBwt(b)) -> \(readableBwt(c))")
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
ReadOnly STX As Char = Chr(&H2)
ReadOnly ETX As Char = Chr(&H3)
Sub Rotate(Of T)(a As T())
Dim o = a.Last
For i = a.Length - 1 To 1 Step -1
a(i) = a(i - 1)
Next
a(0) = o
End Sub
Private Function Compare(s1 As String, s2 As String) As Integer
Dim i = 0
While i < s1.Length AndAlso i < s2.Length
Dim a = s1(i)
Dim b = s2(i)
If a < b Then
Return -1
End If
If b < a Then
Return 1
End If
i += 1
End While
If s1.Length < s2.Length Then
Return -1
End If
If s2.Length < s1.Length Then
Return 1
End If
Return 0
End Function
Function Bwt(s As String) As String
If s.Any(Function(c) c = STX OrElse c = ETX) Then
Throw New ArgumentException("Input can't contain STX or ETX")
End If
Dim ss = (STX + s + ETX).ToCharArray
Dim table As New List(Of String)
For i = 0 To ss.Length - 1
table.Add(New String(ss))
Rotate(ss)
Next
table.Sort(Function(a As String, b As String) Compare(a, b))
Return New String(table.Select(Function(a) a.Last).ToArray)
End Function
Function Ibwt(r As String) As String
Dim len = r.Length
Dim sa(len - 1) As String
Dim table As New List(Of String)(sa)
For i = 0 To len - 1
For j = 0 To len - 1
table(j) = r(j) + table(j)
Next
table.Sort(Function(a As String, b As String) Compare(a, b))
Next
For Each row In table
If row.Last = ETX Then
Return row.Substring(1, len - 2)
End If
Next
Return ""
End Function
Function MakePrintable(s As String) As String
Return s.Replace(STX, "^").Replace(ETX, "|")
End Function
Sub Main()
Dim tests As String() = {
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
STX + "ABC" + ETX
}
For Each test In tests
Console.WriteLine(MakePrintable(test))
Console.Write(" --> ")
Dim t = ""
Try
t = Bwt(test)
Console.WriteLine(MakePrintable(t))
Catch ex As Exception
Console.WriteLine("ERROR: {0}", ex.Message)
End Try
Dim r = Ibwt(t)
Console.WriteLine(" --> {0}", r)
Console.WriteLine()
Next
End Sub
End Module |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Beads | Beads | beads 1 program 'Caesar cipher'
calc main_init
var str = "The five boxing wizards (🤖) jump quickly."
log "Plain: {str}"
str = Encrypt(str, 3)
log "Encrypted: {str}"
str = Decrypt(str, 3)
log "Decrypted: {str}"
// encrypt a string by shifting the letters over by a number of slots
// pass through any characters that are not in the Roman alphabet
calc Encrypt(
input:str --- string to encrypt
nshift --- number of characters to slide over
) : str --- encrypted string
var newStr = ""
loop from:1 to:str_len(input) count:myCount
var unicode : num = from_char(subset(input, from:myCount, len:1))
if unicode >= 65 and unicode <= 90
unicode = mod((unicode - 65 + nshift), 26) + 65
elif unicode >= 97 and unicode <= 122
unicode = mod((unicode - 97 + nshift), 26) + 97
newStr = newStr & to_char(unicode)
return newStr
// undo the encryption
calc Decrypt(
input:str
nshift
) : str
// we could also just shift by 26-nshift, same as going in reverse
return Encrypt(input, -nshift) |
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
| #JavaScript | JavaScript | (() => {
"use strict";
// - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --
// eApprox : Int -> Float
const eApprox = n =>
sum(
scanl(mul)(1)(
enumFromTo(1)(n)
)
.map(x => 1 / x)
);
// ---------------------- TEST -----------------------
const main = () =>
eApprox(20);
// ---------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// mul (*) :: Num a => a -> a -> a
const mul = a =>
// The arithmetic product of a and b.
b => a * b;
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl = f => startValue => xs =>
// The series of interim values arising
// from a catamorphism. Parallel to foldl.
xs.reduce((a, x) => {
const v = f(a[0])(x);
return [v, a[1].concat(v)];
}, [startValue, [startValue]])[1];
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use v5.10;
# Build a list of all possible solutions. The regular expression weeds
# out numbers containing zeroes or repeated digits. See how Perl
# automatically converts numbers to strings for us, just because we
# use them as if they were strings:
my @candidates = grep {not /0 | (\d) .* \1 /x} 1234 .. 9876;
# Repeatedly prompt for input until the user supplies a reasonable score.
# The regex validates the user's input and then returns two numbers,
# $+{BULLS} and $+{COWS}.
sub read_score($) {
(my $guess) = @_;
for (;;) {
say "My guess: $guess (from ", 0+@candidates, " possibilities)";
if (<> =~ / ^ \h* (?<BULLS> \d) \h* (?<COWS> \d) \h* $ /x and
$+{BULLS} + $+{COWS} <= 4) {
return ($+{BULLS}, $+{COWS});
}
say "Please specify the number of bulls and the number of cows";
}
}
sub score_correct($$$$) {
my ($a, $b, $bulls, $cows) = @_;
# Count the positions at which the digits match:
my $exact = () = grep {substr($a, $_, 1) eq substr($b, $_, 1)} 0 .. 3;
# Cross-match all digits in $a against all digits in $b, using a regex
# (specifically, a character class) instead of an explicit loop:
my $loose = () = $a =~ /[$b]/g;
return $bulls == $exact && $cows == $loose - $exact;
}
do {
# Pick a number, display it, get the score, and discard candidates
# that don't match the score:
my $guess = @candidates[rand @candidates];
my ($bulls, $cows) = read_score $guess;
@candidates = grep {score_correct $_, $guess, $bulls, $cows} @candidates;
} while (@candidates > 1);
say(@candidates?
"Your secret number is @candidates":
"I think you made a mistake with your scoring");
|
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #PicoLisp | PicoLisp | (DE CAL (YEAR)
(PRINL "====== " YEAR " ======")
(FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31))
(LET D (DATE DAT)
(TAB (3 3 4 8)
(WHEN (= 1 (CADDR D))
(GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) )
(CADDR D)
(DAY DAT `(INTERN (PACK (MAPCAR CHAR (42 68 97 121)))))
(WHEN (=0 (% (INC DAT) 7))
(PACK (CHAR 87) "EEk " (WEEK DAT)) ) ) ) ) )
(CAL 1969)
(BYE) |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Prolog | Prolog | :- module(plffi, [strdup/2]).
:- use_foreign_library(plffi). |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #PureBasic | PureBasic |
; Call_a_foreign_language_function.fasm -> Call_a_foreign_language_function.obj
; the assembler code...
; format COFF or
; format COFF64 classic (DJGPP) variants of COFF file
; format MS COFF or
; format MS COFF64 Microsoft's variants of COFF file
format MS COFF
include "Win32A.Inc"
section ".text" executable readable code
proc strucase stdcall str:dword
xor eax,eax
mov ebx,[str]
strucase_loop:
mov al,byte[ebx]
cmp al,0
jz strucase_is_null_byte
cmp al,'a'
jb strucase_skip
cmp al,'z'
ja strucase_skip
and al,11011111b
strucase_skip:
; mov byte[ebx],al
xchg al,byte[ebx]
inc ebx
jmp strucase_loop
strucase_is_null_byte:
xor eax,eax
mov eax,[str]
ret
endp
public strucase as "_strucase@4"
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | # all functions used are from the standard library
# calling a function with no arguments:
random-int
# calling a function with a fixed number of arguments:
+ 1 2
# calling a function with optional arguments:
# optional arguments are not really possible as such
# generally differently named functions are used:
sort [ 3 2 1 ]
sort-by @len [ "Hello" "World" "Bob" ]
# calling a function with a variable number of arguments:
# generally with a special terminator value, which one depends
# on the function called
concat( 1 2 3 )
[ 1 2 3 ]
set{ :foo :bar :spam }
# calling a function with named arguments: not possible
# using a function in first-class context within an expression
$ @-- @len # $ is "compose", so the function returned is "one less than the length"
# obtaining the return value of a function
# return values are always pushed on the stack, so you don't need anything special
random-int
# discarding the return value of a function
drop random-int
# method call:
local :do { :nuthin @pass }
do!nuthin
!import!fooModule # same as eva!import :fooModule
# arguments are passed by object-identity, like in Python and Lua
# partial application is not possible, due to the fact that
# a function's arity is a property of its behavior and not
# of its definition |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #XPL0 | XPL0 | proc Cantor(N, LineSeg, Len); \Delete middle third of LineSeg
int N; char LineSeg; int Len, Third, I;
[if N>0 and Len>1 then
[Third:= Len/3;
for I:= Third, 2*Third-1 do LineSeg(I):= ^ ;
Cantor(N-1, LineSeg, Third);
Cantor(N-1, LineSeg+2*Third, Third);
];
];
char LineSeg, N;
[LineSeg:=
"#################################################################################
";
for N:= 0 to 4 do
[Cantor(N, LineSeg, 81);
Text(0, LineSeg);
];
] |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #zkl | zkl | const WIDTH=81, HEIGHT=5;
var lines=HEIGHT.pump(List,List.createLong(WIDTH,"\U2588;").copy); // full block
fcn cantor(start,len,index){
(seg:=len/3) or return();
foreach i,j in ([index..HEIGHT-1], [start + seg .. start + seg*2 - 1]){
lines[i][j]=" ";
}
cantor(start, seg, index + 1);
cantor(start + seg*2, seg, index + 1);
}(0,WIDTH,1);
lines.pump(Console.println,"concat"); |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Run_BASIC | Run BASIC | for i = 1 to 10 :n(i) = i:next i
print " +: ";" ";cat(10,"+")
print " -: ";" ";cat(10,"-")
print " *: ";" ";cat(10,"*")
print " /: ";" ";cat(10,"/")
print " ^: ";" ";cat(10,"^")
print "min: ";" ";cat(10,"min")
print "max: ";" ";cat(10,"max")
print "avg: ";" ";cat(10,"avg")
print "cat: ";" ";cat(10,"cat")
function cat(count,op$)
cat = n(1)
for i = 2 to count
if op$ = "+" then cat = cat + n(i)
if op$ = "-" then cat = cat - n(i)
if op$ = "*" then cat = cat * n(i)
if op$ = "/" then cat = cat / n(i)
if op$ = "^" then cat = cat ^ n(i)
if op$ = "max" then cat = max(cat,n(i))
if op$ = "min" then cat = min(cat,n(i))
if op$ = "avg" then cat = cat + n(i)
if op$ = "cat" then cat$ = cat$ + str$(n(i))
next i
if op$ = "avg" then cat = cat / count
if op$ = "cat" then cat = val(str$(n(1))+cat$)
end function |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Rust | Rust | fn main() {
println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n));
println!("Product: {}", (1..10).fold(1, |acc, n| acc * n));
let chars = ['a', 'b', 'c', 'd', 'e'];
println!("Concatenation: {}",
chars.iter().map(|&c| (c as u8 + 1) as char).collect::<String>());
} |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Stata | Stata | . list
+-------+
| a b |
|-------|
1. | 1 3 |
2. | 2 4 |
+-------+
. fillin a b
. list
+-----------------+
| a b _fillin |
|-----------------|
1. | 1 3 0 |
2. | 1 4 1 |
3. | 2 3 1 |
4. | 2 4 0 |
+-----------------+ |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #J | J | ((! +:) % >:) i.15x
1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #JavaScript | JavaScript | (function () {
'use strict'
// Index of any closing brace matching the opening
// brace at iPosn,
// with the indices of any immediately-enclosed commas.
function bracePair(tkns, iPosn, iNest, lstCommas) {
if (iPosn >= tkns.length || iPosn < 0) return null;
var t = tkns[iPosn],
n = (t === '{') ? (
iNest + 1
) : (t === '}' ? (
iNest - 1
) : iNest),
lst = (t === ',' && iNest === 1) ? (
lstCommas.concat(iPosn)
) : lstCommas;
return n ? bracePair(tkns, iPosn + 1, n, lst) : {
close: iPosn,
commas: lst
};
}
// Parse of a SYNTAGM subtree
function andTree(dctSofar, tkns) {
if (!tkns.length) return [dctSofar, []];
var dctParse = dctSofar ? dctSofar : {
fn: and,
args: []
},
head = tkns[0],
tail = head ? tkns.slice(1) : [],
dctBrace = head === '{' ? bracePair(
tkns, 0, 0, []
) : null,
lstOR = dctBrace && (
dctBrace.close
) && dctBrace.commas.length ? (
splitAt(dctBrace.close + 1, tkns)
) : null;
return andTree({
fn: and,
args: dctParse.args.concat(
lstOR ? (
orTree(dctParse, lstOR[0], dctBrace.commas)
) : head
)
}, lstOR ? (
lstOR[1]
) : tail);
}
// Parse of a PARADIGM subtree
function orTree(dctSofar, tkns, lstCommas) {
if (!tkns.length) return [dctSofar, []];
var iLast = lstCommas.length;
return {
fn: or,
args: splitsAt(
lstCommas, tkns
).map(function (x, i) {
var ts = x.slice(
1, i === iLast ? (
-1
) : void 0
);
return ts.length ? ts : [''];
}).map(function (ts) {
return ts.length > 1 ? (
andTree(null, ts)[0]
) : ts[0];
})
};
}
// List of unescaped braces and commas, and remaining strings
function tokens(str) {
// Filter function excludes empty splitting artefacts
var toS = function (x) {
return x.toString();
};
return str.split(/(\\\\)/).filter(toS).reduce(function (a, s) {
return a.concat(s.charAt(0) === '\\' ? s : s.split(
/(\\*[{,}])/
).filter(toS));
}, []);
}
// PARSE TREE OPERATOR (1 of 2)
// Each possible head * each possible tail
function and(args) {
var lng = args.length,
head = lng ? args[0] : null,
lstHead = "string" === typeof head ? (
[head]
) : head;
return lng ? (
1 < lng ? lstHead.reduce(function (a, h) {
return a.concat(
and(args.slice(1)).map(function (t) {
return h + t;
})
);
}, []) : lstHead
) : [];
}
// PARSE TREE OPERATOR (2 of 2)
// Each option flattened
function or(args) {
return args.reduce(function (a, b) {
return a.concat(b);
}, []);
}
// One list split into two (first sublist length n)
function splitAt(n, lst) {
return n < lst.length + 1 ? [
lst.slice(0, n), lst.slice(n)
] : [lst, []];
}
// One list split into several (sublist lengths [n])
function splitsAt(lstN, lst) {
return lstN.reduceRight(function (a, x) {
return splitAt(x, a[0]).concat(a.slice(1));
}, [lst]);
}
// Value of the parse tree
function evaluated(e) {
return typeof e === 'string' ? e :
e.fn(e.args.map(evaluated));
}
// JSON prettyprint (for parse tree, token list etc)
function pp(e) {
return JSON.stringify(e, function (k, v) {
return typeof v === 'function' ? (
'[function ' + v.name + ']'
) : v;
}, 2)
}
// ----------------------- MAIN ------------------------
// s -> [s]
function expansions(s) {
// BRACE EXPRESSION PARSED
var dctParse = andTree(null, tokens(s))[0];
// ABSTRACT SYNTAX TREE LOGGED
console.log(pp(dctParse));
// AST EVALUATED TO LIST OF STRINGS
return evaluated(dctParse);
}
// Sample expressions,
// double-escaped for quotation in source code.
var lstTests = [
'~/{Downloads,Pictures}/*.{jpg,gif,png}',
'It{{em,alic}iz,erat}e{d,}, please.',
'{,{,gotta have{ ,\\, again\\, }}more }cowbell!',
'{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}'
];
// 1. Return each expression with an indented list of its expansions, while
// 2. logging each parse tree to the console.log() stream
return lstTests.map(function (s) {
return s + '\n\n' + expansions(s).map(function (x) {
return ' ' + x;
}).join('\n');
}).join('\n\n');
})(); |
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 representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #Factor | Factor | USING: combinators grouping io kernel lists lists.lazy math
math.parser math.primes.lists math.ranges namespaces prettyprint
prettyprint.config sequences ;
: (brazilian?) ( n -- ? )
2 over 2 - [a,b] [ >base all-equal? ] with find nip >boolean ;
: brazilian? ( n -- ? )
{
{ [ dup 7 < ] [ drop f ] }
{ [ dup even? ] [ drop t ] }
[ (brazilian?) ]
} cond ;
: .20-brazilians ( list -- )
[ 20 ] dip [ brazilian? ] lfilter ltake list>array . ;
100 margin set
1 lfrom "First 20 Brazilian numbers:"
1 [ 2 + ] lfrom-by "First 20 odd Brazilian numbers:"
lprimes "First 20 prime Brazilian numbers:"
[ print .20-brazilians nl ] 2tri@ |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Common_Lisp | Common Lisp | (ql:quickload '(date-calc))
(defparameter *day-row* "Su Mo Tu We Th Fr Sa")
(defparameter *calendar-margin* 3)
(defun month-to-word (month)
"Translate a MONTH from 1 to 12 into its word representation."
(svref #("January" "February" "March" "April"
"May" "June" "July" "August"
"September" "October" "November" "December")
(1- month)))
(defun month-strings (year month)
"Collect all of the strings that make up a calendar for a given
MONTH and YEAR."
`(,(date-calc:center (month-to-word month) (length *day-row*))
,*day-row*
;; We can assume that a month calendar will always fit into a 7 by 6 block
;; of values. This makes it easy to format the resulting strings.
,@ (let ((days (make-array (* 7 6) :initial-element nil)))
(loop :for i :from (date-calc:day-of-week year month 1)
:for day :from 1 :to (date-calc:days-in-month year month)
:do (setf (aref days i) day))
(loop :for i :from 0 :to 5
:collect
(format nil "~{~:[ ~;~2,d~]~^ ~}"
(loop :for day :across (subseq days (* i 7) (+ 7 (* i 7)))
:append (if day (list day day) (list day))))))))
(defun calc-columns (characters margin-size)
"Calculate the number of columns given the number of CHARACTERS per
column and the MARGIN-SIZE between them."
(multiple-value-bind (cols excess)
(truncate characters (+ margin-size (length *day-row*)))
(incf excess margin-size)
(if (>= excess (length *day-row*))
(1+ cols)
cols)))
(defun take (n list)
"Take the first N elements of a LIST."
(loop :repeat n :for x :in list :collect x))
(defun drop (n list)
"Drop the first N elements of a LIST."
(cond ((or (<= n 0) (null list)) list)
(t (drop (1- n) (cdr list)))))
(defun chunks-of (n list)
"Split the LIST into chunks of size N."
(assert (> n 0))
(loop :for x := list :then (drop n x)
:while x
:collect (take n x)))
(defun print-calendar (year &key (characters 80) (margin-size 3))
"Print out the calendar for a given YEAR, optionally specifying
a width limit in CHARACTERS and MARGIN-SIZE between months."
(assert (>= characters (length *day-row*)))
(assert (>= margin-size 0))
(let* ((calendars (loop :for month :from 1 :to 12
:collect (month-strings year month)))
(column-count (calc-columns characters margin-size))
(total-size (+ (* column-count (length *day-row*))
(* (1- column-count) margin-size)))
(format-string (concatenate 'string
"~{~a~^~" (write-to-string margin-size) ",0@T~}~%")))
(format t "~a~%~a~%~%"
(date-calc:center "[Snoopy]" total-size)
(date-calc:center (write-to-string year) total-size))
(loop :for row :in (chunks-of column-count calendars)
:do (apply 'mapcar
(lambda (&rest heads)
(format t format-string heads))
row)))) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Wren | Wren | class Safe {
construct new() { _safe = 42 } // the field _safe is private
safe { _safe } // provides public access to field
doubleSafe { notSoSafe_ } // another public method
notSoSafe_ { _safe * 2 } // intended only for private use but still accesible externally
}
var s = Safe.new()
var a = [s.safe, s.doubleSafe, s.notSoSafe_]
for (e in a) System.print(e) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #zkl | zkl | class C{var [private] v; fcn [private] f{123} class [private] D {}}
C.v; C.f; C.D; // all generate NotFoundError exceptions
However:
C.fcns //-->L(Fcn(nullFcn),Fcn(f))
C.fcns[1]() //-->123
C.classes //-->L(Class(D))
C.vars //-->L(L("",Void)) (name,value) pairs |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #FreeBASIC | FreeBASIC | ' version 16-03-2017
' compile with: fbc -s gui
Const As ULong w = 400
Const As ULong w1 = w -1
Dim As Long x, y, lastx, lasty
Dim As Long count, max = w * w \ 4
ScreenRes w, w, 8 ' windowsize 400 * 400, 8bit
' hit any key to stop or mouseclick on close window [X]
WindowTitle "hit any key to stop and close the window"
Palette 0, 0 ' black
Palette 1, RGB( 1, 1, 1) ' almost black
Palette 2, RGB(255, 255, 255) ' white
Palette 3, RGB( 0, 255, 0) ' green
Line (0, 0) - (w1, w1), 0, BF ' make field black
Line (0, 0) - (w1, w1), 1, B ' draw border in almost black color
Randomize Timer
x = Int(Rnd * 11) - 5
y = Int(Rnd * 11) - 5
PSet(w \ 2 + x, w \ 2 + y), 3 ' place seed near center
Do
Do ' create new particle
x = Int(Rnd * w1) + 1
y = Int(Rnd * w1) + 1
Loop Until Point(x, y) = 0 ' black
PSet(x, y), 2
Do
lastx = x
lasty = y
Do
x = lastx + Int(Rnd * 3) -1
y = lasty + Int(Rnd * 3) -1
Loop Until Point(x, y) <> 1
If Point(x, y) = 3 Then
PSet(lastx, lasty), 3
Exit Do ' exit do loop and create new particle
End If
PSet(lastx, lasty), 0
PSet(x,y), 2
If Inkey <> "" Or Inkey = Chr(255) + "k" Then
End
End If
Loop
count += 1
Loop Until count > max
Beep : Sleep 5000
End |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Clojure | Clojure |
(ns bulls-and-cows)
(defn bulls [guess solution]
(count (filter true? (map = guess solution))))
(defn cows [guess solution]
(-
(count (filter (set solution) guess))
(bulls guess solution)))
(defn valid-input?
"checks whether the string is a 4 digit number with unique digits"
[user-input]
(if (re-seq #"^(?!.*(\d).*\1)\d{4}$" user-input)
true
false))
(defn enter-guess []
"Let the user enter a guess. Verify the input. Repeat until valid.
returns a list of digits enters by the user (# # # #)"
(println "Enter your guess: ")
(let [guess (read-line)]
(if (valid-input? guess)
(map #(Character/digit % 10) guess)
(recur))))
(defn bulls-and-cows []
"generate a random 4 digit number from the list of (1 ... 9): no repeating digits
player tries to guess the number with bull and cows rules gameplay"
(let [solution ( take 4 (shuffle (range 1 10)))]
(println "lets play some bulls and cows!")
(loop [guess (enter-guess)]
(println (bulls guess solution) " bulls and " (cows guess solution) " cows.")
(if (not= guess solution)
(recur (enter-guess))
(println "You have won!")))))
(bulls-and-cows)
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Wren | Wren | import "/sort" for Sort
var stx = "\x02"
var etx = "\x03"
var bwt = Fn.new { |s|
if (s.indexOf(stx) >= 0 || s.indexOf(etx) >= 0) return null
s = stx + s + etx
var len = s.count
var table = [""] * len
table[0] = s
for (i in 1...len) table[i] = s[i..-1] + s[0...i]
Sort.quick(table)
var lastChars = [""] * len
for (i in 0...len) lastChars[i] = table[i][len-1]
return lastChars.join()
}
var ibwt = Fn.new { |r|
var len = r.count
var table = [""] * len
for (i in 0...len) {
for (j in 0...len) table[j] = r[j] + table[j]
Sort.quick(table)
}
for (row in table) {
if (row.endsWith(etx)) return row[1...len-1]
}
return ""
}
var makePrintable = Fn.new { |s|
// substitute ^ for STX and | for ETX to print results
s = s.replace(stx, "^")
return s.replace(etx, "|")
}
var tests = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\x02ABC\x03"
]
for (test in tests) {
System.print(makePrintable.call(test))
System.write(" --> ")
var t = bwt.call(test)
if (t == null) {
System.print("ERROR: String can't contain STX or ETX")
t = ""
} else {
System.print(makePrintable.call(t))
}
var r = ibwt.call(t)
System.print(" --> %(r)\n")
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Befunge | Befunge | 65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48 |
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
| #jq | jq | 1|exp #=> 2.718281828459045 |
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
| #Julia | Julia | module NeperConstant
export NeperConst
struct NeperConst{T}
val::T
end
Base.show(io::IO, nc::NeperConst{T}) where T = print(io, "ℯ (", T, ") = ", nc.val)
function NeperConst{T}() where T
local e::T = 2.0
local e2::T = 1.0
local den::(T ≡ BigFloat ? BigInt : Int128) = 1
local n::typeof(den) = 2
while e ≠ e2
e2 = e
den *= n
n += one(n)
e += 1.0 / den
end
return NeperConst{T}(e)
end
end # module NeperConstant |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Phix | Phix | with javascript_semantics
constant line = " +---------+-----------------------------+-------+------+\n",
digits = "123456789"
function mask(integer ch)
return power(2,ch-'1')
end function
function score(string guess, goal)
integer bits = 0, bulls = 0, cows = 0
for i=1 to length(guess) do
if guess[i]=goal[i] then
bulls += 1
else
bits += mask(goal[i])
end if
end for
for i=1 to length(guess) do
cows += (and_bits(bits,mask(guess[i]))!=0)
end for
return {bulls, cows}
end function
sequence list = {}
procedure pick(integer n, got, marker, string buf)
if got>=n then
list = append(list,buf)
else
integer bits = 1
for i=0 to length(digits)-1 do
if not and_bits(marker,bits) then
buf[got+1] = i+'1'
pick(n, got+1, or_bits(marker,bits), deep_copy(buf))
end if
bits *= 2
end for
end if
end procedure
procedure filter_list(string guess, integer bulls, cows)
integer idx = 0
sequence bc = {bulls,cows}
for i=1 to length(list) do
if score(guess,list[i])=bc then
idx += 1
list[idx] = list[i]
end if
end for
list = list[1..idx]
end procedure
procedure game(string tgt)
integer n = length(tgt), attempt = 1
pick(n,0,0,repeat('\0',n))
while true do
string guess = list[rand(length(list))]
integer {bulls, cows} = score(guess,tgt)
printf(1," | Guess %-2d| %9s %-14s | %d | %d |\n",
{attempt, guess, sprintf("(from %d)",length(list)), bulls, cows})
if bulls=n then exit end if
filter_list(guess, bulls, cows)
attempt += 1
end while
puts(1,line)
end procedure
constant N = 4
string secret = shuffle(digits)[1..N]
printf(1,"%s | Secret | %9s | BULLS | COWS |\n%s", {line, secret, line})
game(secret)
|
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #PL.2FI | PL/I | (SUBRG, SIZE, FOFL):
CALENDAR: PROCEDURE (YEAR) OPTIONS (MAIN);
DECLARE YEAR CHARACTER (4) VARYING;
DECLARE (A, B, C) (0:5,0:6) CHARACTER (3);
DECLARE NAME_MONTH(12) STATIC CHARACTER (9) VARYING INITIAL (
'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE',
'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER');
DECLARE I FIXED;
DECLARE (MM, MMP1, MMP2) PIC '99';
PUT EDIT (CENTER('CALENDAR FOR ' || YEAR, 67)) (A);
PUT SKIP (2);
DO MM = 1 TO 12 BY 3;
MMP1 = MM + 1; MMP2 = MM + 2;
CALL PREPARE_MONTH('01' || MM || YEAR, A);
CALL PREPARE_MONTH('01' || MMP1 || YEAR, B);
CALL PREPARE_MONTH('01' || MMP2 || YEAR, C);
PUT SKIP EDIT (CENTER(NAME_MONTH(MM), 23),
CENTER(NAME_MONTH(MMP1), 23),
CENTER(NAME_MONTH(MMP2), 23) ) (A);
PUT SKIP EDIT ((3)' M T W T F S S ') (A);
DO I = 0 TO 5;
PUT SKIP EDIT (A(I,*), B(I,*), C(I,*)) (7 A, X(2));
END;
END;
PREPARE_MONTH: PROCEDURE (START, MONTH);
DECLARE MONTH(0:5,0:6) CHARACTER (3);
DECLARE START CHARACTER (8);
DECLARE I PIC 'ZZ9';
DECLARE OFFSET FIXED;
DECLARE (J, DAY) FIXED BINARY (31);
DECLARE (THIS_MONTH, NEXT_MONTH, K) FIXED BINARY;
DAY = DAYS(START, 'DDMMYYYY');
OFFSET = WEEKDAY(DAY) - 1;
IF OFFSET = 0 THEN OFFSET = 7;
MONTH = '';
DO J = DAY BY 1;
THIS_MONTH = SUBSTR(DAYSTODATE(J, 'DDMMYYYY'), 3, 2);
NEXT_MONTH = SUBSTR(DAYSTODATE(J+1, 'DDMMYYYY'), 3, 2);
IF THIS_MONTH^= NEXT_MONTH THEN LEAVE;
END;
I = 1;
DO K = OFFSET-1 TO OFFSET+J-DAY-1;
MONTH(K/7, MOD(K,7)) = I; I = I + 1;
END;
END PREPARE_MONTH;
END CALENDAR; |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Python_2 | Python | import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def") # -1
libc.strcmp("hello", "hello") # 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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Racket | Racket |
#lang racket/base
(require ffi/unsafe)
(provide strdup)
;; Helper: create a Racket string from a C string pointer.
(define make-byte-string
(get-ffi-obj "scheme_make_byte_string" #f (_fun _pointer -> _scheme)))
;; Take special care not to allow NULL (#f) to be passed as an input,
;; as that will crash strdup.
(define _string/no-null
(make-ctype _pointer
(lambda (x)
(unless (string? x)
(raise-argument-error '_string/no-null "string" x))
(string->bytes/utf-8 x))
;; We don't use _string/no-null as an output type, so don't care:
(lambda (x) x)))
; Make a Scheme string from the C string, and free immediately.
(define _string/free
(make-ctype _pointer
;; We don't use this as an input type, so we don't care.
(lambda (x) x)
(lambda (x)
(cond
[x
(define s (bytes->string/utf-8 (make-byte-string x)))
(free x)
s]
[else
;; We should never get null from strdup unless we're out of
;; memory:
(error 'string/free "Out of memory")]))))
(define strdup
(get-ffi-obj "strdup" #f (_fun _string/no-null -> _string/free)))
;; Let's try it:
(strdup "Hello World!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.