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.
| #Nim | Nim | import random
import imageman
const
Size = 400 # Area size.
MaxXY = Size - 1 # Maximum possible value for x and y.
NPart = 25_000 # Number of particles.
Background = ColorRGBU [byte 0, 0, 0] # Background color.
Foreground = ColorRGBU [byte 50, 150, 255] # Foreground color.
randomize()
var image = initImage[ColorRGBU](Size, Size)
image.fill(Background)
image[Size div 2, Size div 2] = Foreground
for _ in 1..NPart:
block ProcessParticle:
while true: # Repeat until the particle is freezed.
# Choose position of particle.
var x, y = rand(MaxXY)
if image[x, y] == Foreground:
continue # Not free. Try again.
# Move the particle.
while true:
# Choose a motion.
let dx, dy = rand(-1..1)
inc x, dx
inc y, dy
if x notin 0..MaxXY or y notin 0..MaxXY:
break # Out of limits. Try again.
# Valid move.
if image[x, y] == Foreground:
# Not free. Freeze the particle at its previous position.
image[x - dx, y - dy] = Foreground
break ProcessParticle # Done. Process next particle.
# Save into a PNG file.
image.savePNG("brownian.png", compression = 9) |
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
| #Factor | Factor | USING: accessors assocs combinators fry grouping hashtables kernel
locals math math.parser math.ranges random sequences strings
io ascii ;
IN: bullsncows
TUPLE: score bulls cows ;
: <score> ( -- score ) 0 0 score boa ;
TUPLE: cow ;
: <cow> ( -- cow ) cow new ;
TUPLE: bull ;
: <bull> ( -- bull ) bull new ;
: inc-bulls ( score -- score ) dup bulls>> 1 + >>bulls ;
: inc-cows ( score -- score ) dup cows>> 1 + >>cows ;
: random-nums ( -- seq ) 9 [1,b] 4 sample ;
: add-digits ( seq -- n ) 0 [ swap 10 * + ] reduce number>string ;
: new-number ( -- n narr ) random-nums dup add-digits ;
: narr>nhash ( narr -- nhash ) { 1 2 3 4 } swap zip ;
: num>hash ( n -- hash )
[ 1string string>number ] { } map-as narr>nhash ;
:: cow-or-bull ( n g -- arr )
{
{ [ n first g at n second = ] [ <bull> ] }
{ [ n second g value? ] [ <cow> ] }
[ f ]
} cond ;
: add-to-score ( arr -- score )
<score> [ bull? [ inc-bulls ] [ inc-cows ] if ] reduce ;
: check-win ( score -- ? ) bulls>> 4 = ;
: sum-score ( n g -- score ? )
'[ _ cow-or-bull ] map sift add-to-score dup check-win ;
: print-sum ( score -- str )
dup bulls>> number>string "Bulls: " swap append swap cows>> number>string
" Cows: " swap 3append "\n" append ;
: (validate-readln) ( str -- ? ) dup length 4 = not swap [ letter? ] all? or ;
: validate-readln ( -- str )
readln dup (validate-readln)
[ "Invalid input.\nPlease enter a valid 4 digit number: "
write flush drop validate-readln ]
when ;
: win ( -- ) "\nYou've won! Good job. You're so smart." print flush ;
: main-loop ( x -- )
"Enter a 4 digit number: " write flush validate-readln num>hash swap
[ sum-score swap print-sum print flush ] keep swap not
[ main-loop ] [ drop win ] if ;
: main ( -- ) new-number drop narr>nhash main-loop ; |
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
| #Dart | Dart | class Caesar {
int _key;
Caesar(this._key);
int _toCharCode(String s) {
return s.charCodeAt(0);
}
String _fromCharCode(int ch) {
return new String.fromCharCodes([ch]);
}
String _process(String msg, int offset) {
StringBuffer sb=new StringBuffer();
for(int i=0;i<msg.length;i++) {
int ch=msg.charCodeAt(i);
if(ch>=_toCharCode('A')&&ch<=_toCharCode('Z')) {
sb.add(_fromCharCode(_toCharCode("A")+(ch-_toCharCode("A")+offset)%26));
}
else if(ch>=_toCharCode('a')&&ch<=_toCharCode('z')) {
sb.add(_fromCharCode(_toCharCode("a")+(ch-_toCharCode("a")+offset)%26));
} else {
sb.add(msg[i]);
}
}
return sb.toString();
}
String encrypt(String msg) {
return _process(msg, _key);
}
String decrypt(String msg) {
return _process(msg, 26-_key);
}
}
void trip(String msg) {
Caesar cipher=new Caesar(10);
String enc=cipher.encrypt(msg);
String dec=cipher.decrypt(enc);
print("\"$msg\" encrypts to:");
print("\"$enc\" decrypts to:");
print("\"$dec\"");
Expect.equals(msg,dec);
}
main() {
Caesar c2=new Caesar(2);
print(c2.encrypt("HI"));
Caesar c20=new Caesar(20);
print(c20.encrypt("HI"));
// try a few roundtrips
trip("");
trip("A");
trip("z");
trip("Caesar cipher");
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
} |
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
| #R | R |
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19)))
|
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
| #Quackery | Quackery | $ "bigrat.qky" loadfile
[ swap number$
tuck size -
times sp echo$ ] is echo-rj ( n n --> )
[ 2dup swap
say " First " echo
say " approximations of e by sum of 1/n! displayed to "
echo say " decimal places." cr
cr
temp put
1 n->v rot
1 swap times
[ i^ 1+ *
dup n->v 1/v
rot dip
[ v+ 2dup
i^ 1+ 5 echo-rj
say " : "
temp share point$ echo$
cr ] ]
3 times drop temp release ] is approximate-e ( n n --> )
55 70 approximate-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)
| #Shale | Shale | #!/usr/local/bin/shale
maths library
file library
string library
lista var
listb var
firstTimeThrough var
guess var
guess0 var
guess1 var
guess2 var
guess3 var
bulls var
cows var
init dup var {
count a:: var
count b:: var
} =
randomDigit dup var {
random maths::() 18 >> 9 % 1 +
} =
makeGuess dup var {
firstTimeThrough {
guess0 randomDigit() =
guess1 randomDigit() =
{ guess1 guess0 == } { guess1 randomDigit() = } while
guess2 randomDigit() =
{ guess2 guess0 == guess2 guess1 == or } { guess2 randomDigit() = } while
guess3 randomDigit() =
{ guess3 guess0 == guess3 guess1 == guess3 guess2 == or or } { guess3 randomDigit() = } while
guess guess3 1000 * guess2 100 * guess1 10 * guess0 + + + =
} {
i var
i random maths::() count lista->:: % =
guess i.value lista->:: value =
guess0 guess 10 % =
guess1 guess 10 / 10 % =
guess2 guess 100 / 10 % =
guess3 guess 1000 / =
} if
} =
getAnswer dup var {
stdin file:: fgets file::() {
atoi string::()
} {
0 exit
} if
} =
getScore dup var {
haveBulls dup var false =
haveCows dup var false =
ans var
{ haveBulls not } {
"Bulls: " print
ans getAnswer() =
ans 0 < ans 4 > and {
"Please try again" println
} {
bulls ans =
haveBulls true =
} if
} while
{ haveCows not } {
"Cows: " print
ans getAnswer() =
ans 0 < ans 4 > and {
"Please try again" println
} {
cows ans =
haveCows true =
} if
} while
} =
check dup var {
d0 dup var swap = // units
d1 dup var swap =
d2 dup var swap =
d3 dup var swap = // thousands
b dup var 0 =
c dup var 0 =
d0 guess0 == { b++ } { d0 guess1 == { d0 guess2 == { d0 guess3 == } or } or { c++ } ifthen } if
d1 guess1 == { b++ } { d1 guess0 == { d1 guess2 == { d1 guess3 == } or } or { c++ } ifthen } if
d2 guess2 == { b++ } { d2 guess0 == { d2 guess1 == { d2 guess3 == } or } or { c++ } ifthen } if
d3 guess3 == { b++ } { d3 guess0 == { d3 guess1 == { d3 guess2 == } or } or { c++ } ifthen } if
b bulls >= c cows >= and
} =
add dup var {
n dup var swap =
n guess != { // never put our own guess back in the list.
i var
i count listb->:: =
i.value listb->:: defined not {
i.value listb->:: var
} ifthen
i.value listb->:: n =
count listb->::++
} ifthen
} =
filterList dup var {
firstTimeThrough {
a var
b var
c var
d var
a 1 =
{ a 10 < } {
b 1 =
{ b 10 < } {
b a != {
c 1 =
{ c 10 < } {
c a != c b != and {
d 1 =
{ d 10 < } {
d a != { d b != d c != and } and {
a b c d check() {
a 1000 * b 100 * c 10 * d + + + add()
} ifthen
} ifthen
d++
} while
} ifthen
c++
} while
} ifthen
b++
} while
a++
} while
} {
i var
j var
n var
count listb->:: 0 =
i 0 =
{ i count lista->:: < } {
n i.value lista->:: =
n 1000 / n 100 / 10 % n 10 / 10 % n 10 % check() {
n.value add()
} ifthen
i++
} while
} if
} =
solve dup var {
t var
f var
n var
lista a &=
listb b &=
firstTimeThrough true =
count a:: 0 =
count b:: 0 =
n 1 =
f 1 =
{ f } {
makeGuess()
guess0 guess1 guess2 guess3 n "\nGuess %d: %d %d %d %d\n" printf
getScore()
bulls 4 == {
"WooHoo, I won!" println
break
} ifthen
filterList()
f count listb->:: =
t lista =
lista listb =
listb t =
firstTimeThrough false =
n++
} while
count lista->:: 0 == {
"I've run out of numbers to choose from." println
} ifthen
} =
init()
{ true } {
solve()
} while |
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.
| #XLISP | XLISP | (SETQ YR 1969)
(SETQ M #("JANUARY" "FEBRUARY" "MARCH" "APRIL" "MAY" "JUNE" "JULY" "AUGUST" "SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER"))
(SETQ ML #(31 28 31 30 31 30 31 31 30 31 30 31))
(SETQ WD #("SU" "MO" "TU" "WE" "TH" "FR" "SA"))
(IF (AND (= (REM YR 4) 0) (OR (/= (REM YR 100) 0) (= (REM YR 400) 0))) (VECTOR-SET! ML 1 29))
(SETQ D (REM (+ 1 (+ (* 5 (REM (- YR 1) 4)) (* 4 (REM (- YR 1) 100)) (* 6 (REM (- YR 1) 400)))) 7))
(TERPRI)
(DO ((I 0 (+ I 1))) ((> I 60))
(PRINC " "))
(PRINC "SNOOPY CALENDAR ")
(PRINC YR)
(TERPRI)
(DO ((I 0 (+ I 1))) ((> I 11))
(TERPRI)
(DO ((J 0 (+ J 1))) ((> J 65))
(PRINC " "))
(PRINC (VECTOR-REF M I))
(TERPRI)
(PRINC " ")
(DO ((J 0 (+ J 1))) ((> J 6))
(DO ((K 0 (+ K 1))) ((> K 14))
(PRINC " "))
(PRINC (VECTOR-REF WD J))
(PRINC " "))
(TERPRI)
(DO ((J 0 (+ J 1))) ((> J 6))
(IF (< J D) (DO ((K 0 (+ K 1))) ((> K 18)) (PRINC " "))))
(DO ((J 1 (+ J 1))) ((> J (VECTOR-REF ML I)))
(PRINC " ")
(IF (< J 10) (PRINC " "))
(DO ((K 0 (+ K 1))) ((> K 14))
(PRINC " "))
(PRINC J)
(SETQ D (+ D 1))
(IF (> D 6) (TERPRI))
(IF (> D 6) (SETQ D 0)))) |
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.
| #i | i | //The type of the function argument determines whether or not the value is passed by reference or not.
//Eg. numbers are passed by value and lists/arrays are passed by reference.
software {
print() //Calling a function with no arguments.
print("Input a number!") //Calling a function with fixed arguments.
print(1,2,3,4,5,6,7,8,9,0) //Calling a function with variable arguments.
input = read() //Obtaining the return value of a function.
myprint = print
myprint("It was: ", input) //Calling first class functions, the same as calling ordinary functions.
//The only distinction that can be made between two functions is if they are 'real' or not.
if type(myprint) = concept
print("myprint is a not a real function")
else if type(myprint) = function
print("myprint is a real function")
end
//Partial functions can be created with static parts.
DebugPrint = print["[DEBUG] ", text]
DebugPrint("partial function!") //This would output '[DEBUG] partial function!'
if type(DebugPrint) = concept
print("DebugPrint is a not a real function")
else if type(DebugPrint) = function
print("DebugPrint is a real function")
end
}
|
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
| #Maxima | Maxima | /* The following is an array function, hence the square brackets. It uses memoization automatically */
cata[n] := sum(cata[i]*cata[n - 1 - i], i, 0, n - 1)$
cata[0]: 1$
cata2(n) := binomial(2*n, n)/(n + 1)$
makelist(cata[n], n, 0, 14);
makelist(cata2(n), n, 0, 14);
/* both return [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
| #Rust | Rust | const OPEN_CHAR: char = '{';
const CLOSE_CHAR: char = '}';
const SEPARATOR: char = ',';
const ESCAPE: char = '\\';
#[derive(Debug, PartialEq, Clone)]
enum Token {
Open,
Close,
Separator,
Payload(String),
Branches(Branches),
}
impl From<char> for Token {
fn from(ch: char) -> Token {
match ch {
OPEN_CHAR => Token::Open,
CLOSE_CHAR => Token::Close,
SEPARATOR => Token::Separator,
_ => panic!("Non tokenizable char!"),
}
}
}
#[derive(Debug, PartialEq, Clone)]
struct Branches {
tokens: Vec<Vec<Token>>,
}
impl Branches {
fn new() -> Branches {
Branches{
tokens: Vec::new(),
}
}
fn add_branch(&mut self, branch: Vec<Token>) {
self.tokens.push(branch);
}
fn from(tokens: &Vec<Token>) -> Branches {
let mut branches = Branches::new();
let mut tail = tokens.clone();
while let Some(pos) = tail.iter().position(|token| { *token == Token::Separator }) {
let mut rest = tail.split_off(pos);
branches.add_branch(tail);
rest.remove(0);
tail = rest;
}
branches.add_branch(tail);
branches
}
}
impl From<Branches> for Token {
fn from(branches: Branches) -> Token {
Token::Branches(branches)
}
}
impl From<Vec<Token>> for Branches {
fn from(tokens: Vec<Token>) -> Branches {
Branches::from(&tokens)
}
}
impl From<Token> for String {
fn from(token: Token) -> String {
match token {
Token::Branches(_) => panic!("Cannot convert to String!"),
Token::Payload(text) => text,
Token::Open => OPEN_CHAR.to_string(),
Token::Close => CLOSE_CHAR.to_string(),
Token::Separator => SEPARATOR.to_string(),
}
}
}
impl From<Branches> for Vec<String> {
fn from(branches: Branches) -> Vec<String> {
let Branches{ tokens: token_lines } = branches;
let mut vec: Vec<String> = Vec::new();
let braces = { if token_lines.len() == 1 { true } else { false } };
for tokens in token_lines {
let mut vec_string = output(tokens);
vec.append(&mut vec_string);
}
if braces {
vec.iter()
.map(|line| {
format!("{}{}{}", OPEN_CHAR, line, CLOSE_CHAR)
}).
collect::<Vec<String>>()
} else {
vec
}
}
}
impl From<Token> for Vec<String> {
fn from(token: Token) -> Vec<String> {
match token {
Token::Branches(branches) => {
branches.into()
},
_ => {
let frag: String = token.into();
vec![frag]
},
}
}
}
fn tokenize(string: &str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec::new();
let mut chars = string.chars();
let mut payload = String::new();
while let Some(ch) = chars.next() {
match ch {
OPEN_CHAR | SEPARATOR | CLOSE_CHAR => {
if payload.len() > 0 {
tokens.push(Token::Payload(payload));
}
payload = String::new();
if ch == CLOSE_CHAR {
let pos = tokens.iter().rposition(|token| *token == Token::Open);
if let Some(pos) = pos {
let branches: Branches = {
let mut to_branches = tokens.split_off(pos);
to_branches.remove(0);
to_branches
}.into();
tokens.push(branches.into());
} else {
tokens.push(ch.into());
}
} else {
tokens.push(ch.into());
}
},
ESCAPE => {
payload.push(ch);
if let Some(next_char) = chars.next() {
payload.push(next_char);
}
},
_ => payload.push(ch),
}
}
let payload = payload.trim_end();
if payload.len() > 0 {
tokens.push(Token::Payload(payload.into()));
}
tokens
}
fn output(tokens: Vec<Token>) -> Vec<String> {
let mut output: Vec<String> = vec![String::new()];
for token in tokens {
let mut aux: Vec<String> = Vec::new();
let strings: Vec<String> = token.into();
for root in &output {
for string in &strings {
aux.push({format!("{}{}", root, string)});
}
}
output = aux;
}
output
}
fn main() {
let mut input: String = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let tokens: Vec<Token> = tokenize(&input);
// println!("Tokens:\n{:#?}", tokens);
let output = output(tokens);
for line in &output {
println!("{}", line);
}
} |
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
| #Scala | Scala |
import collection.mutable.ListBuffer
case class State(isChild: Boolean, alts: ListBuffer[String], rem: List[Char])
def expand(s: String): Seq[String] = {
def parseGroup(s: State): State = s.rem match {
case Nil => s.copy(alts = ListBuffer("{" + s.alts.mkString(",")))
case ('{' | ',')::sp =>
val newS = State(true, ListBuffer(""), rem = sp)
val elem = parseElem(newS)
elem.rem match {
case Nil => elem.copy(alts = elem.alts.map(a => "{" + s.alts.map(_ + ",").mkString("") + a))
case elemrem => parseGroup(s.copy(alts = (s.alts ++= elem.alts), rem = elem.rem))
}
case '}'::sp =>
if (s.alts.isEmpty) s.copy(alts = ListBuffer("{}"), rem = sp)
else if(s.alts.length == 1) s.copy(alts = ListBuffer("{"+s.alts.head + "}"), rem = sp)
else s.copy(rem = sp)
case _ => throw new Exception("parseGroup should be called only with delimitors")
}
def parseElem(s: State): State = s.rem match {
case Nil => s
case '{'::sp =>
val ys = parseGroup(State(true, ListBuffer(), s.rem))
val newAlts = for { x <- s.alts; y <- ys.alts} yield x + y
parseElem(s.copy(alts = newAlts, rem = ys.rem))
case (',' | '}')::_ if s.isChild => s
case '\\'::c::sp => parseElem(s.copy(alts = s.alts.map(_ + '\\' + c), rem = sp))
case c::sp => parseElem(s.copy(alts = s.alts.map(_ + c), rem = sp))
}
parseElem(State(false, ListBuffer(""), s.toList)).alts
}
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | brazilianQ[n_Integer /; n>6 ] := AnyTrue[
Range[2, n-2],
MatchQ[IntegerDigits[n, #], {x_ ...}] &
]
Select[Range[100], brazilianQ, 20]
Select[Range[100], brazilianQ@# && OddQ@# &, 20]
Select[Range[10000], brazilianQ@# && PrimeQ@# &, 20]
|
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
| #JavaScript | JavaScript | /**
* Given a width, return a function that takes a string, and
* pads it at both ends to the given width
* @param {number} width
* @returns {function(string): string}
*/
const printCenter = width =>
s => s.padStart(width / 2 + s.length / 2, ' ').padEnd(width);
/**
* Given an locale string and options, return a function that takes a date
* object, and retrurns the date formatted to the locale and options.
* @param {string} locale
* @param {DateTimeFormatOptions} options
* @returns {function(Date): string}
*/
const localeName = (locale, options) => {
const formatter = new Intl.DateTimeFormat(locale, options);
return date => formatter.format(date);
};
/**
* Increment the date by number.
* @param {Date} date
* @param {number} inc
* @returns {Date}
*/
const addDay = (date, inc = 1) => {
const res = new Date(date.valueOf());
res.setDate(date.getDate() + inc);
return res;
}
/**
* Given a date, build a string of the week, and return it along with
* the mutated date object.
* @param {Date} date
* @returns {[boolean, Date, string]}
*/
const makeWeek = date => {
const month = date.getMonth();
let [wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
const line = Array(7).fill(' ').map((e, i) => {
if (i === wdi && m === month) {
const result = (md + '').padStart(2, ' ');
date = addDay(date);
[wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
return result;
} else {
return e;
}
}).join(' ');
return [month !== m, date, line];
}
/**
* Print a nicely formatted calender for the given year in the given locale.
* @param {number} year The required year of the calender
* @param {string} locale The locale string. Defaults to US English.
* @param {number} cols The number of columns for the months. Defaults to 3.
* @param {number} coll_space The space between the columns. Defaults to 5.
*/
const cal = (year, locale = 'en-US', cols = 3, coll_space = 5) => {
const MONTH_LINES = 9; // Number of lines that make up a month.
const MONTH_COL_WIDTH = 20; // Character width of a month
const COL_SPACE = ' '.padStart(coll_space);
const FULL_WIDTH = MONTH_COL_WIDTH * cols + coll_space * (cols - 1);
const collArr = Array(cols).fill('');
const monthName = localeName(locale, {month: 'long'});
const weekDayShort = localeName(locale, {weekday: 'short'});
const monthCenter = printCenter(MONTH_COL_WIDTH);
const pageCenter = printCenter(FULL_WIDTH);
// Get the weekday in the given locale.
const sun = new Date(Date.UTC(2017, 0, 1)); // A sunday
const weekdays = Array(7).fill('').map((e, i) =>
weekDayShort(addDay(sun, i)).padStart(2, ' ').substring(0, 2)).join(' ');
// The start date.
let date = new Date(Date.UTC(year, 0, 1, 0, 0, 0));
let nextMonth = true;
let line = '';
const fullYear = date.getUTCFullYear();
// The array into which each of the lines are populated.
const accumulate = [];
// Populate the month table heading and columns.
const preAmble = date => {
accumulate.push(monthCenter(' '))
accumulate.push(monthCenter(monthName(date)));
accumulate.push(weekdays);
};
// Accumulate the week lines for the year.
while (date.getUTCFullYear() === fullYear) {
if (nextMonth) {
if (accumulate.length % MONTH_LINES !== 0) {
accumulate.push(monthCenter(' '))
}
preAmble(date);
}
[nextMonth, date, line] = makeWeek(date);
accumulate.push(line);
}
// Print the calendar.
console.log(pageCenter(String.fromCodePoint(0x1F436)));
console.log(pageCenter(`--- ${fullYear} ---`));
accumulate.reduce((p, e, i) => {
if (!p.includes(i)) {
const indexes = collArr.map((e, ci) => i + ci * MONTH_LINES);
console.log(indexes.map(e => accumulate[e]).join(COL_SPACE));
p.push(...indexes);
}
return p;
}, []);
};
cal(1969, 'en-US', 3);
|
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.
| #OCaml | OCaml | let world_width = 400
let world_height = 400
let num_particles = 20_000
let () =
assert(num_particles > 0);
assert(world_width * world_height > num_particles);
;;
let dla ~world =
(* put the tree seed *)
world.(world_height / 2).(world_width / 2) <- 1;
for i = 1 to num_particles do
(* looping helper function *)
let rec aux px py =
(* randomly choose a direction *)
let dx = (Random.int 3) - 1 (* offsets *)
and dy = (Random.int 3) - 1 in
if dx + px < 0 || dx + px >= world_width ||
dy + py < 0 || dy + py >= world_height then
(* plop the particle into some other random location *)
aux (Random.int world_width) (Random.int world_height)
else if world.(py + dy).(px + dx) <> 0 then
(* bumped into something, particle set *)
world.(py).(px) <- 1
else
aux (px + dx) (py + dy)
in
(* set particle's initial position *)
aux (Random.int world_width) (Random.int world_height)
done
let to_pbm ~world =
print_endline "P1"; (* Type=Portable bitmap, Encoding=ASCII *)
Printf.printf "%d %d\n" world_width world_height;
Array.iter (fun line ->
Array.iter print_int line;
print_newline()
) world
let () =
Random.self_init();
let world = Array.make_matrix world_width world_height 0 in
dla ~world;
to_pbm ~world;
;; |
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
| #Fan | Fan | **
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
class BullsAndCows
{
Void main()
{
digits := [1,2,3,4,5,6,7,8,9]
size := 4
chosen := [,]
size.times { chosen.add(digits.removeAt(Int.random(0..<digits.size))) }
echo("I've chosen $size unique digits from 1 to 9 at random.
Try to guess my number!")
guesses := 0
while (true) // game loop
{
guesses += 1
guess := Int[,]
while (true) // input loop
{
// get a good guess
Sys.out.print("\nNext guess [$guesses]: ")
Sys.out.flush
inString := Sys.in.readLine?.trim ?: ""
inString.each |ch|
{ if (ch >= '1' && ch <= '9' && !guess.contains(ch)) guess.add(ch-'0') }
if (guess.size == 4)
break // input loop
echo("Oops, try again. You need to enter $size unique digits from 1 to 9")
}
if (guess.all |v, i->Bool| { return v == chosen[i] })
{
echo("\nCongratulations! You guessed correctly in $guesses guesses")
break // game loop
}
bulls := 0
cows := 0
(0 ..< size).each |i|
{
if (guess[i] == chosen[i])
bulls += 1
else if (chosen.contains(guess[i]))
cows += 1
}
echo("\n $bulls Bulls\n $cows Cows")
}
}
} |
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
| #Delphi | Delphi | func Char.Encrypt(code) {
if !this.IsLetter() {
return this
}
var offset = (this.IsUpper() ? 'A' : 'a').Order()
return Char((this.Order() + code - offset) % 26 + offset)
}
func String.Encrypt(code) {
var xs = []
for c in this {
xs.Add(c.Encrypt(code))
}
return String.Concat(values: xs)
}
func String.Decrypt(code) {
this.Encrypt(26 - code);
}
var str = "Pack my box with five dozen liquor jugs."
print(str)
str = str.Encrypt(5)
print("Encrypted: \(str)")
str = str.Decrypt(5)
print("Decrypted: \(str)") |
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
| #Racket | Racket | #lang racket
(require math/number-theory)
(define (calculate-e (terms 20))
(apply + (map (compose / factorial) (range terms))))
(module+ main
(let ((e (calculate-e)))
(displayln e)
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string (- (exp 1) e) 20)))) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Raku | Raku | # If you need high precision: Sum of a Taylor series method.
# Adjust the terms parameter to suit. Theoretically the
# terms could be ∞. Practically, calculating an infinite
# series takes an awfully long time so limit to 500.
sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] }
sub 𝑒 (Int $terms) { sum map { FatRat.new(1,.!) }, ^$terms }
say 𝑒(500).comb(80).join: "\n";
say '';
# Or, if you don't need high precision, it's a built-in.
say 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)
| #Sidef | Sidef | # Build a list of all possible solutions. The regular expression weeds
# out numbers containing zeroes or repeated digits.
var candidates = (1234..9876 -> grep {|n| !("#{n}" =~ /0 | (\d) .*? \1 /x) }.map{.digits});
# Repeatedly prompt for input until the user supplies a reasonable score.
# The regex validates the user's input and then returns two numbers.
func read_score(guess) {
loop {
"My guess: %s (from %d possibilities)\n" \
-> printf(guess.join, candidates.len);
if (var m = (Sys.scanln("bulls cows: ") =~ /^\h*(\d)\h*(\d)\h*$/)) {
var (bulls, cows) = m.cap.map{.to_i}...;
bulls+cows <= 4 && return(bulls, cows);
}
say "Please specify the number of bulls and the number of cows";
}
}
func score_correct(a, b, bulls, cows) {
var (exact, loose) = (0, 0);
for i in ^4 {
a[i] == b[i] ? ++exact
: (a[i]~~b && ++loose)
}
(bulls == exact) && (cows == loose)
}
# Pick a number, display it, get the score, and discard candidates
# that don't match the score:
loop {
var guess = candidates.pick;
var (bulls, cows) = read_score(guess);
candidates.grep!{|n| score_correct(n, guess, bulls, cows) }
candidates.len > 1 || break
}
# Print the secret number or the error message
(
candidates.len == 1 ? ("Your secret number is: %d" % candidates[0].join)
: ("I think you made a mistake with your scoring")
)->say |
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.
| #zkl | zkl | VAR [CONST] D=TIME.DATE, DAYS="SU MO TU WE TH FR SA";
FCN CENTER(TEXT,M) { STRING(" "*((M-TEXT.LEN())/2),TEXT) }
FCN ONEMONTH(YEAR,MONTH){
DAY1:=D.ZELLER(YEAR,MONTH,1); //1969-1-1 -->3 (WED, ISO 8601)
DAYZ:=D.DAYSINMONTH(YEAR,MONTH); //1969-1 -->31
LIST(CENTER(D.MONTHNAMES[MONTH],DAYS.LEN()),DAYS).EXTEND(
(1).PUMP(DAYZ,(0).PUMP(DAY1,LIST,T(VOID,""))).APPLY("%2S ".FMT)
.PUMP(LIST,T(VOID.READ,DAYS.LEN()/3,FALSE),STRING.CREATE));
}
... |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main() # demonstrate and describe function calling syntax and semantics
# normal procedure/function calling
f() # no arguments, also command context
f(x) # fixed number of arguments
f(x,h,w) # variable number of arguments (varargs)
y := f(x) # Obtaining the returned value of a function
# procedures as first class values and string invocation
f!L # Alternate calling syntax using a list as args
(if \x then f else g)() # call (f or g)()
f := write # assign a procedure
f("Write is now called") # ... and call it
"f"() # string invocation, procedure
"-"(1) # string invocation, operator
# Co-expressions
f{e1,e2} # parallel evaluation co-expression call
# equivalent to f([create e1, create e2])
expr @ coexp # transmission of a single value to a coexpression
[e1,e2]@coexp # ... of multiple values (list) to a coexpression
coexp(e1,e2) # ... same as above but only in Unicon
# Other
f("x:=",1,"y:=",2) # named parameters (user defined)
end |
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
| #Modula-2 | Modula-2 | MODULE CatalanNumbers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE binomial(m,n : LONGCARD) : LONGCARD;
VAR r,d : LONGCARD;
BEGIN
r := 1;
d := m - n;
IF d>n THEN
n := d;
d := m - n;
END;
WHILE m>n DO
r := r * m;
DEC(m);
WHILE (d>1) AND NOT (r MOD d # 0) DO
r := r DIV d;
DEC(d)
END
END;
RETURN r
END binomial;
PROCEDURE catalan1(n : LONGCARD) : LONGCARD;
BEGIN
RETURN binomial(2*n,n) DIV (1+n)
END catalan1;
PROCEDURE catalan2(n : LONGCARD) : LONGCARD;
VAR i,sum : LONGCARD;
BEGIN
IF n>1 THEN
sum := 0;
FOR i:=0 TO n-1 DO
sum := sum + catalan2(i) * catalan2(n - 1 - i)
END;
RETURN sum
ELSE
RETURN 1
END
END catalan2;
PROCEDURE catalan3(n : LONGCARD) : LONGCARD;
BEGIN
IF n#0 THEN
RETURN 2 *(2 * n - 1) * catalan3(n - 1) DIV (1 + n)
ELSE
RETURN 1
END
END catalan3;
VAR
blah : LONGCARD = 123;
buf : ARRAY[0..63] OF CHAR;
i : LONGCARD;
BEGIN
FormatString("\tdirect\tsumming\tfrac\n", buf);
WriteString(buf);
FOR i:=0 TO 15 DO
FormatString("%u\t%u\t%u\t%u\n", buf, i, catalan1(i), catalan2(i), catalan3(i));
WriteString(buf)
END;
ReadChar
END CatalanNumbers. |
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
| #Scheme | Scheme |
(define (parse-brackets str)
;; We parse the bracketed strings using an accumulator and a stack
;;
;; lst is the stream of tokens
;; acc is the accumulated list of "bits" in this branch
;; stk is a list of partially completed accumulators
;;
(let go ((lst (string->list str))
(acc '())
(stk '()))
(cond ((null? lst)
(unless (null? stk)
(error "parse-brackets" 'non-empty-stack))
(comma-sep acc))
((eq? (car lst) #\{)
(go (cdr lst)
'()
(cons acc stk)))
((eq? (car lst) #\})
(when (null? stk)
(error "parse-brackets" 'empty-stack))
(go (cdr lst)
(cons (comma-sep acc) (car stk))
(cdr stk)))
(else
(go (cdr lst)
(cons (car lst) acc)
stk)))))
(define (comma-sep lst)
;; This function is applied to the accumulator, it does three things:
;; - it reverses the list
;; - joins characters into short strings
;; - splits the strings based on commas
;;
(let go ((lst lst)
(acc '())
(rst '()))
(if (null? lst)
(cons (list->string acc) rst)
(cond ((eq? #\, (car lst))
(go (cdr lst)
'()
(cons (list->string acc) rst)))
((char? (car lst))
(go (cdr lst)
(cons (car lst) acc)
rst))
(else
(go (cdr lst)
'()
(cons (car lst)
(cons (list->string acc)
rst))))))))
;; We use the list monad for the nondeterminism needed to expand out every possible bracket option
(define (concatenate lists)
(apply append lists))
(define (return x)
(list x))
(define (>>= l f)
(concatenate (map f l)))
(define (sequence lsts)
(if (null? lsts)
(return '())
(>>= (car lsts)
(lambda (option)
(>>= (sequence (cdr lsts))
(lambda (tail)
(return (cons option tail))))))))
(define (expand-inner tree)
(if (string? tree)
(return tree)
(>>= tree
(lambda (option)
(expand-inner option)))))
(define (expand tree)
(define (string-append* lst) (apply string-append lst))
(map string-append* (sequence (map expand-inner tree))))
(define (bracket-expand str)
(expand (parse-brackets str)))
(bracket-expand "It{{em,alic}iz,erat}e{d,}")
;; '("Ited" "Ite" "Itemed" "Iteme" "Italiced" "Italice" "Itized" "Itize" "Iterated" "Iterate")
|
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
| #Nim | Nim | proc isPrime(n: Positive): bool =
## Check if a number is prime.
if n mod 2 == 0:
return n == 2
if n mod 3 == 0:
return n == 3
var d = 5
while d * d <= n:
if n mod d == 0:
return false
if n mod (d + 2) == 0:
return false
inc d, 6
result = true
proc sameDigits(n, b: Positive): bool =
## Check if the digits of "n" in base "b" are all the same.
var d = n mod b
var n = n div b
if d == 0:
return false
while n > 0:
if n mod b != d:
return false
n = n div b
result = true
proc isBrazilian(n: Positive): bool =
## Check if a number is brazilian.
if n < 7:
return false
if (n and 1) == 0:
return true
for b in 2..(n - 2):
if sameDigits(n, b):
return true
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import strutils
template printList(title: string; findNextToCheck: untyped) =
## Template to print a list of brazilians numbers.
## "findNextTocheck" is a list of instructions to find the
## next candidate starting for the current one "n".
block:
echo '\n' & title
var n {.inject.} = 7
var list: seq[int]
while true:
if n.isBrazilian():
list.add(n)
if list.len == 20: break
findNextToCheck
echo list.join(", ")
printList("First 20 Brazilian numbers:"):
inc n
printList("First 20 odd Brazilian numbers:"):
inc n, 2
printList("First 20 prime Brazilian numbers:"):
inc n, 2
while not n.isPrime():
inc n, 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
| #Julia | Julia |
using Dates
const pagesizes = Dict( "lpr" => [132, 66], "tn3270" => [80, 43])
pagefit(prn) = haskey(pagesizes, prn) ?
[div(pagesizes[prn][1], 22), div(pagesizes[prn][2], 12)] : [1, 1]
pagecols(prn) = haskey(pagesizes, prn) ? pagesizes[prn][1] : 20
function centerobject(x, cols)
content = string(x)
rpad(lpad(content, div(cols + length(content), 2)), cols)
end
function ljustlines(x, cols)
arr = Vector{String}()
for s in split(x, "\n")
push!(arr, rpad(s, cols)[1:cols])
end
join(arr, "\n")
end
function formatmonth(yr, mo)
dt = Date("$yr-$mo-01")
dayofweekfirst = dayofweek(dt)
numweeklines = 1
str = centerobject(monthname(dt), 20) * "\nMo Tu We Th Fr Sa Su\n"
str *= " " ^ (3 * (dayofweekfirst - 1)) * lpad(string(1), 2)
for i = 2:daysinmonth(dt)
if (i + dayofweekfirst + 5) % 7 == 0
str *= "\n" * lpad(i, 2)
numweeklines += 1
else
str *= lpad(string(i), 3)
end
end
str *= numweeklines < 6 ? "\n\n\n" : "\n\n"
ljustlines(str, 20)
end
function formatyear(displayyear, printertype)
calmonths = [formatmonth(displayyear, mo) for mo in 1:12]
columns = pagecols(printertype)
monthsperline = pagefit(printertype)[1]
joinspaces = max( (monthsperline > 1) ?
div(columns - monthsperline * 20, monthsperline - 1) : 1, 1)
str = "\n" * centerobject(displayyear, columns) * "\n"
monthcal = [split(formatmonth(displayyear, i), "\n") for i in 1:12]
for i in 1:monthsperline:length(calmonths) - 1
for j in 1:length(monthcal[1])
monthlines = map(x->monthcal[x][j], i:i + monthsperline - 1)
str *= rpad(join(monthlines, " " ^ joinspaces), columns) * "\n"
end
str *= "\n"
end
str
end
function lineprintcalendar(years)
for year in years, printer in keys(pagesizes)
println(formatyear(year, printer))
end
end
lineprintcalendar(1969)
|
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.
| #Octave | Octave | function r = browniantree(xsize, ysize = xsize, numparticle = 1000)
r = zeros(xsize, ysize, "uint8");
r(unidrnd(xsize), unidrnd(ysize)) = 1;
for i = 1:numparticle
px = unidrnd(xsize-1)+1;
py = unidrnd(ysize-1)+1;
while(1)
dx = unidrnd(2) - 1;
dy = unidrnd(2) - 1;
if ( (dx+px < 1) || (dx+px > xsize) || (dy+py < 1) || (dy+py > ysize) )
px = unidrnd(xsize-1)+1;
py = unidrnd(ysize-1)+1;
elseif ( r(px+dx, py+dy) != 0 )
r(px, py) = 1;
break;
else
px += dx;
py += dy;
endif
endwhile
endfor
endfunction
r = browniantree(200);
r( r > 0 ) = 255;
jpgwrite("browniantree.jpg", r, 100); % image package |
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
| #FOCAL | FOCAL | 01.10 T %1,"BULLS AND COWS"!"----- --- ----"!!
01.20 S T=0;D 3
01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!!
01.40 I (B-4)1.3
01.50 T "YOU WON! GUESSES",%4,T,!!
01.60 Q
02.10 A "GUESS",A
02.20 F X=0,3;S B=FITR(A/10);S G(3-X)=A-B*10;S A=B
02.30 S A=1
02.40 F X=0,3;S A=A*G(X)
02.50 I (-A)2.6;T "NEED FOUR NONZERO DIGITS"!;G 2.1
02.60 F X=0,2;F Y=X+1,3;S A=A*(FABS(G(X)-G(Y)))
02.70 I (-A)2.8;T "NO DUPLICATES ALLOWED"!;G 2.1
02.80 R
03.10 F X=0,3;S S(X)=0
03.20 F X=0,3;D 4;S S(X)=A
04.10 S A=10*FRAN();S A=FITR(1+9*(A-FITR(A)))
04.20 S Z=1
04.30 F Y=0,3;S Z=Z*(FABS(A-S(Y)))
04.40 I (-Z)4.5,4.1
04.50 R
05.10 S B=0
05.20 F X=0,3;D 5.6
05.30 S C=-B
05.40 F X=0,3;F Y=0,3;D 5.7
05.50 R
05.60 I (-FABS(S(X)-G(X)))5.5,5.8
05.70 I (-FABS(S(X)-G(Y)))5.5,5.9
05.80 S B=B+1
05.90 S C=C+1 |
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
| #Dyalect | Dyalect | func Char.Encrypt(code) {
if !this.IsLetter() {
return this
}
var offset = (this.IsUpper() ? 'A' : 'a').Order()
return Char((this.Order() + code - offset) % 26 + offset)
}
func String.Encrypt(code) {
var xs = []
for c in this {
xs.Add(c.Encrypt(code))
}
return String.Concat(values: xs)
}
func String.Decrypt(code) {
this.Encrypt(26 - code);
}
var str = "Pack my box with five dozen liquor jugs."
print(str)
str = str.Encrypt(5)
print("Encrypted: \(str)")
str = str.Decrypt(5)
print("Decrypted: \(str)") |
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
| #REXX | REXX | ╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ║
║ 1 1 1 1 1 1 1 ║
║ e = ─── + ─── + ─── + ─── + ─── + ─── + ─── + ∙∙∙ ║
║ 0! 1! 2! 3! 4! 5! 6! ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
|
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
| #Ring | Ring |
# Project : Calculating the value of e
decimals(14)
for n = 1 to 100000
e = pow((1 + 1/n),n)
next
see "Calculating the value of e with method #1:" + nl
see "e = " + e + nl
e = 0
for n = 0 to 12
e = e + (1 / factorial(n))
next
see "Calculating the value of e with method #2:" + nl
see "e = " + e + nl
func factorial(n)
if n = 0 or n = 1
return 1
else
return n * factorial(n-1)
ok
|
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)
| #Tcl | Tcl | package require struct::list
package require struct::set
proc scorecalc {guess chosen} {
set bulls 0
set cows 0
foreach g $guess c $chosen {
if {$g eq $c} {
incr bulls
} elseif {$g in $chosen} {
incr cows
}
}
return [list $bulls $cows]
}
# Allow override on command line
set size [expr {$argc ? int($argv) : 4}]
set choices {}
struct::list foreachperm p [split 123456789 ""] {
struct::set include choices [lrange $p 1 $size]
}
set answers {}
set scores {}
puts "Playing Bulls & Cows with $size unique digits\n"
fconfigure stdout -buffering none
while 1 {
set ans [lindex $choices [expr {int(rand()*[llength $choices])}]]
lappend answers $ans
puts -nonewline \
"Guess [llength $answers] is [join $ans {}]. Answer (Bulls, cows)? "
set score [scan [gets stdin] %d,%d]
lappend scores $score
if {$score eq {$size 0}} {
puts "Ye-haw!"
break
}
foreach c $choices[set choices {}] {
if {[scorecalc $c $ans] eq $score} {
lappend choices $c
}
}
if {![llength $choices]} {
puts "Bad scoring? nothing fits those scores you gave:"
foreach a $answers s $scores {
puts " [join $a {}] -> ([lindex $s 0], [lindex $s 1])"
}
break
}
} |
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.
| #J | J | verb noun
noun verb noun |
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
| #Nim | Nim | import math
import strformat
proc catalan1(n: int): int =
binom(2 * n, n) div (n + 1)
proc catalan2(n: int): int =
if n == 0:
return 1
for i in 0..<n:
result += catalan2(i) * catalan2(n - 1 - i)
proc catalan3(n: int): int =
if n > 0: 2 * (2 * n - 1) * catalan3(n - 1) div (1 + n)
else: 1
for i in 0..15:
echo &"{i:7} {catalan1(i):7} {catalan2(i):7} {catalan3(i):7}" |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: expandBraces (in string: stri) is func
local
var boolean: escaped is FALSE;
var integer: depth is 0;
var array integer: bracePoints is 0 times 0;
var array integer: bracesToParse is 0 times 0;
var string: prefix is "";
var string: suffix is "";
var string: option is "";
var integer: idx is 0;
begin
for key idx range stri do
case stri[idx] of
when {'\\'}:
escaped := not escaped;
when {'{'}:
incr(depth);
if not escaped and depth = 1 then
bracePoints := [] (idx);
end if;
when {','}:
if not escaped and depth = 1 then
bracePoints &:= idx;
end if;
when {'}'}:
if not escaped and depth = 1 and length(bracePoints) >= 2 then
bracesToParse := bracePoints & [] (idx);
end if;
decr(depth);
end case;
if stri[idx] <> '\\' then
escaped := FALSE;
end if;
end for;
if length(bracesToParse) <> 0 then
prefix := stri[.. pred(bracesToParse[1])];
suffix := stri[succ(bracesToParse[length(bracesToParse)]) ..];
for idx range 1 to pred(length(bracesToParse)) do
option := stri[succ(bracesToParse[idx]) .. pred(bracesToParse[succ(idx)])];
expandBraces(prefix & option & suffix);
end for;
else
writeln(stri);
end if;
end func;
const proc: main is func
local
var string: stri is "";
begin
for stri range [] ("It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}") do
writeln;
expandBraces(stri);
end for;
end func; |
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
| #Pascal | Pascal | program brazilianNumbers;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,All}
{$CODEALIGN proc=32,loop=4}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils;
const
//Must not be a prime
PrimeMarker = 0;
SquareMarker = PrimeMarker + 1;
//MAX = 110468;// 1E5 brazilian
//MAX = 1084566;// 1E6 brazilian
//MAX = 10708453;// 1E7 brazilian
//MAX = 106091516;// 1E8 brazilian
MAX = 1053421821;// 1E9 brazilian
var
isprime: array of word;
procedure MarkSmallestFactor;
//sieve of erathotenes
//but saving the smallest factor
var
i, j, lmt: NativeUint;
begin
lmt := High(isPrime);
fillWord(isPrime[0], lmt + 1, PrimeMarker);
//mark even numbers
i := 2;
j := i * i;
isPrime[j] := SquareMarker;
Inc(j, 2);
while j <= lmt do
begin
isPrime[j] := 2;
Inc(j, 2);
end;
//mark 3 but not 2
i := 3;
j := i * i;
isPrime[j] := SquareMarker;
Inc(j, 6);
while j <= lmt do
begin
isPrime[j] := 3;
Inc(j, 6);
end;
i := 5;
while i * i <= lmt do
begin
if isPrime[i] = 0 then
begin
j := lmt div i;
if not (odd(j)) then
Dec(j);
while j > i do
begin
if isPrime[j] = 0 then
isPrime[i * j] := i;
Dec(j, 2);
end;
//mark square prime
isPrime[i * i] := SquareMarker;
end;
Inc(i, 2);
end;
end;
procedure OutFactors(n: NativeUint);
var
divisor, Next, rest: NativeUint;
pot: NativeUint;
begin
divisor := 2;
Next := 3;
rest := n;
Write(n: 10, ' = ');
while (rest <> 1) do
begin
if (rest mod divisor = 0) then
begin
Write(divisor);
pot := 0;
repeat
rest := rest div divisor;
Inc(pot)
until rest mod divisor <> 0;
if pot > 1 then
Write('^', pot);
if rest > 1 then
Write('*');
end;
divisor := Next;
Next := Next + 2;
// cut condition: avoid many useless iterations
if (rest <> 1) and (rest < divisor * divisor) then
begin
Write(rest);
rest := 1;
end;
end;
Write(' ', #9#9#9);
end;
procedure OutToBase(number, base: NativeUint);
var
BaseDgt: array[0..63] of NativeUint;
i, rest: NativeINt;
begin
OutFactors(number);
i := 0;
while number <> 0 do
begin
rest := number div base;
BaseDgt[i] := number - rest * base;
number := rest;
Inc(i);
end;
while i > 1 do
begin
Dec(i);
Write(BaseDgt[i]);
end;
writeln(BaseDgt[0], ' to base ', base);
end;
function PrimeBase(number: NativeUint): NativeUint;
var
lnN: extended;
i, exponent, n: NativeUint;
begin
// primes are only brazilian if 111...11 to base > 2
// the count of "1" must be odd , because brazilian primes are odd
lnN := ln(number);
exponent := 4;
//result := exponent.th root of number
Result := trunc(exp(lnN*0.25));
while result >2 do
Begin
// calc sum(i= 0 to exponent ) base^i;
n := Result + 1;
i := 2;
repeat
Inc(i);
n := n*result + 1;
until i > exponent;
if n = number then
EXIT;
Inc(exponent,2);
Result := trunc(exp(lnN/exponent));
end;
//not brazilian
Result := 0;
end;
function GetPrimeBrazilianBase(number: NativeUint): NativeUint;
//result is base
begin
// prime of 2^n - 1
if (Number and (number + 1)) = 0 then
Result := 2
else
begin
Result := trunc(sqrt(number));
//most of the brazilian primes are of this type base^2+base+1
IF (sqr(result)+result+1) <> number then
result := PrimeBase(number);
end;
end;
function GetBrazilianBase(number: NativeUInt): NativeUint; inline;
begin
Result := isPrime[number];
if Result > SquareMarker then
Result := (number div Result) - 1
else
begin
if Result = SquareMarker then
begin
if number = 121 then
Result := 3
else
Result := 0;
end
else
Result := GetPrimeBrazilianBase(number);
end;
end;
procedure First20Brazilian;
var
i, n, cnt: NativeUInt;
begin
writeln('first 20 brazilian numbers');
i := 7;
cnt := 0;
while cnt < 20 do
begin
n := GetBrazilianBase(i);
if n <> 0 then
begin
Inc(cnt);
OutToBase(i, n);
end;
Inc(i);
end;
writeln;
end;
procedure First33OddBrazilian;
var
i, n, cnt: NativeUInt;
begin
writeln('first 33 odd brazilian numbers');
i := 7;
cnt := 0;
while cnt < 33 do
begin
n := GetBrazilianBase(i);
if N <> 0 then
begin
Inc(cnt);
OutToBase(i, n);
end;
Inc(i, 2);
end;
writeln;
end;
procedure First20BrazilianPrimes;
var
i, n, cnt: NativeUInt;
begin
writeln('first 20 brazilian prime numbers');
i := 7;
cnt := 0;
while cnt < 20 do
begin
IF isPrime[i] = PrimeMarker then
Begin
n := GetBrazilianBase(i);
if n <> 0 then
begin
Inc(cnt);
OutToBase(i, n);
end;
end;
Inc(i);
end;
writeln;
end;
var
T1, T0: TDateTime;
i, n, cnt, lmt: NativeUInt;
begin
lmt := MAX;
setlength(isPrime, lmt + 1);
MarkSmallestFactor;
First20Brazilian;
First33OddBrazilian;
First20BrazilianPrimes;
Write('count brazilian numbers up to ', lmt, ' = ');
T0 := now;
i := 7;
cnt := 0;
n := 0;
while (i <= lmt) do
begin
Inc(n, Ord(isPrime[i] = PrimeMarker));
if GetBrazilianBase(i) <> 0 then
Inc(cnt);
Inc(i);
end;
T1 := now;
writeln(cnt);
writeln('Count of primes ', n: 11+13);
writeln((T1 - T0) * 86400 * 1000: 10: 0, ' ms');
setlength(isPrime, 0);
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
| #Kotlin | Kotlin | import java.io.PrintStream
import java.text.DateFormatSymbols
import java.text.MessageFormat
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Locale
internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) {
if (nCols < 1 || nCols > 12)
throw IllegalArgumentException("Illegal column width.")
val w = nCols * 24
val nRows = Math.ceil(12.0 / nCols).toInt()
val date = GregorianCalendar(year, 0, 1)
var offs = date.get(Calendar.DAY_OF_WEEK) - 1
val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ")
val mons = Array(12) { Array(8) { "" } }
DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name ->
val len = 11 + name.length / 2
val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len)
mons[m][0] = String.format(format, name, "")
mons[m][1] = days
val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH)
for (d in 1..42) {
val isDay = d > offs && d <= offs + dim
val entry = if (isDay) String.format(" %2s", d - offs) else " "
if (d % 7 == 1)
mons[m][2 + (d - 1) / 7] = entry
else
mons[m][2 + (d - 1) / 7] += entry
}
offs = (offs + dim) % 7
date.add(Calendar.MONTH, 1)
}
printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]")
printf("%" + (w / 2 + 4) + "s%n%n", year)
for (r in 0 until nRows) {
for (i in 0..7) {
var c = r * nCols
while (c < (r + 1) * nCols && c < 12) {
printf(" %s", mons[c][i])
c++
}
println()
}
println()
}
}
fun main(args: Array<String>) {
System.out.printCalendar(1969, 3, Locale.US)
} |
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.
| #PARI.2FGP | PARI/GP |
\\ 2 old plotting helper functions 3/2/16 aev
\\ insm(): Check if x,y are inside matrix mat (+/- p deep).
insm(mat,x,y,p=0)={my(xz=#mat[1,],yz=#mat[,1]);
return(x+p>0 && x+p<=xz && y+p>0 && y+p<=yz && x-p>0 && x-p<=xz && y-p>0 && y-p<=yz)}
\\ plotmat(): Simple plotting using a square matrix mat (filled with 0/1).
plotmat(mat)={
my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,x,y);
for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j))));
print(" *** matrix(",xz,"x",yz,") ",#vy, " DOTS");
plothraw(Vec(vx),Vec(vy));
}
\\ 2 new plotting helper functions 11/27/16 aev
\\ wrtmat(): Writing file fn containing X,Y coordinates from matrix mat.
\\ Created primarily for using file in Gnuplot, also for re-plotting.
wrtmat(mat, fn)={
my(xz=#mat[1,],yz=#mat[,1],ws,d=0);
for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, d++; ws=Str(i," ",j); write(fn,ws))));
print(" *** matrix(",xz,"x",yz,") ",d, " DOTS put in ",fn);
}
\\ plotff(): Plotting from a file written by the wrtmat().
\\ Saving possibly huge generation time if re-plotting needed.
plotff(fn)={
my(F,nf,vx=List(),vy=vx,Vr);
F=readstr(fn); nf=#F;
print(" *** Plotting from: ", fn, " - ", nf, " DOTS");
for(i=1,nf, Vr=stok(F[i],","); listput(vx,eval(Vr[1])); listput(vy,eval(Vr[2])));
plothraw(Vec(vx),Vec(vy));
}
|
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
| #Forth | Forth | include random.fs
create hidden 4 allot
: ok? ( str -- ? )
dup 4 <> if 2drop false exit then
1 9 lshift 1- -rot
bounds do
i c@ '1 -
dup 0 9 within 0= if 2drop false leave then
1 swap lshift over and
dup 0= if nip leave then
xor
loop 0<> ;
: init
begin
hidden 4 bounds do 9 random '1 + i c! loop
hidden 4 ok?
until ;
: check? ( addr -- solved? )
0
4 0 do
over i + c@
4 0 do
dup hidden i + c@ = if swap
i j = if 8 else 1 then + swap
then
loop drop
loop nip
8 /mod tuck . ." bulls, " . ." cows"
4 = ;
: guess: ( "1234" -- )
bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
drop check? if cr ." You guessed it!" then ; |
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
| #EDSAC_order_code | EDSAC order code |
[Caesar cipher for Rosetta Code.
EDSAC program, Initial Orders 2.]
[Table for converting alphabetic position 0..25 to EDSAC code.
The EDSAC code is in the high 5 bits.]
T 54 K [access table via C parameter]
P 56 F
T 56 K
AFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZF
[Table for converting 5-bit EDSAC code to alphabetic position 0..25.
Computed at run time (so the programmer doesn't need to know the EDSAC codes).
32 entries; entry is -1 if the EDSAC code does not represent a letter.]
T 53 K [access table via B parameter]
P 82 F
[Subroutine to read string from input and
store with char codes in high 5 bits.
String is terminated by blank row of tape, which is stored.
Input: 0F holds address of string in address field (bits 1..11).
22 locations; workspace: 4D]
T 114 K
GKA3FT19@AFA20@T10@I5FA4DR16FT4DA4FUFE14@A21@G18@T5FA10@A2FE4@T5FEFUFK2048F
[Subroutine to print string with character codes in high 5 bits.
String is terminated by blank row of tape, which is not printed.
Input: 0F holds address of string in address field (bits 1..11).
18 locations; orkspace: 4F]
T 136 K
GKA3FT16@AFA2@T5@AFU4FE10@A17@G15@O4FT4FA5@A2FG4@TFEFK2048F
[Define start of user message]
T 47 K [access message via M parameter]
P 350 F [address of message]
T 154 K
G K
[Constants]
[0] P M [address of user message]
[1] A B
[2] A C
[3] T B
[4] P 25 F
[5] P 26 F
[6] P 31 F
[7] K 2048 F [(1) letter shift (2) used in test for
blank row of tape at end of message]
[8] @ F [carriage return]
[9] & F [line feed]
[10] K 4096 F [null char]
[Constant messages. Each includes new line at the end.]
[11] TF EF SF TF IF NF GF @F &F K4096F
[21] P 11 @
[22] EF NF TF EF RF !F MF EF SF SF AF GF EF @F &F K4096F
[38] P 22 @
[39] MF UF SF TF !F SF TF AF RF TF !F WF IF TF HF !F BF !F TF OF !F ZF @F &F K4096F
[64] P 39 @
[Subroutine to convert EDSAC code to alphabetic position.
Input: 4F holds EDSAC code in high 5 bits
Output: 4F holds alphabetic position (0..25, or -1 if not a letter).
Workspace: 5F]
[65] A 3 F [make jump for return]
T 75 @ [plant in code]
A 4 F [load EDSAC code]
R 512 F [shift code into address field]
T 5 F [temp store]
C 5 F [acc := address bits only]
A 1 @ [make order to load alphabetic position]
T 73 @ [plant in code]
[73] A B [load alphabetic position]
T 4 F [store in 4F]
[75] E F [return]
[Subroutine to encipher or decipher a message by Caesar shift.
Input: Message is accessed by the M parameter, and
terminated by a blank row of tape.
Output: 0F = error flag: 0 if OK, < 0 if error (bad message prefix)
Workspace 4F.]
[76] A 3 F [make jump for return]
T 119 @ [plant in code]
A 80 @ [load order to access first char]
T 95 @ [plant in code]
[80] A M [load first char of message]
T 4 F [pass to subroutine]
[82] A 82 @ [get alphabetic position]
G 65 @
A 4 F [load alphabetic position]
U F [to 0F for use as shift]
S 2 F [check it's not 0 or -1]
G 118 @ [error exit if it is]
T 1 F [clear acc]
S F [load negative of shift]
G 108 @ [jump to store first char
and convert rest of message]
[Here after skipping non-letter]
[91] T 4 F [clear acc]
[Here after converting letter]
[92] A 95 @ [load order to read character]
A 2 F [inc address to next character]
T 95 @ [store back]
[95] A M [load char from message (in top 5 bits)]
E 100 @ [if >= 0 then not blank row]
A 7 @ [if < 0, test for blank row]
G 117 @ [jump out if so]
S 7 @ [restore after test]
[100] T 4 F [character to 4F for subroutine]
[101] A 101 @ [for return from subroutine]
G 65 @ [sets 4F := alphabetic position]
A 4 F [to acc]
G 91 @ [if < 0 then not a letter; don't change it]
A F [apply Caesar shift]
[Subtract 26 if required, so result is in range 0..25]
S 5 @ [subtract 26]
E 109 @ [skip next if result >= 0]
[108] A 5 @ [add 26]
[109] A 2 @ [make order to read EDSAC letter at that position]
T 114 @ [plant in code]
A 95 @ [load A order from above]
A 14 C [add 'O F' to make T order]
T 115 @ [plant in code]
[114] A C [load enciphered letter]
[115] T M [overwrite original letter]
E 92 @ [loop back]
[117] T F [flag = 0 for OK]
[118] T F [flag to 0F: 0 if OK, < 0 if error]
[119] E F [return with acc = 0]
[Subroutine to print encipered or deciphered message, plus new line]
[120] A 3 F [make jump order for return]
T 128 @ [plant in code]
A @ [load address of message]
T F [to 0F for print subroutine]
[124] A 124 @
G 136 F [print message, clears acc]
O 8 @ [print new line]
O 9 @
[128] E F [return with acc = 0]
[Main routine]
[129] O 7 @ [set letter shift]
H 6 @ [mult reg has this value throughout;
selects bits 1..5 of 17-bit value]
[Build inverse table from direct table
First initialize all 32 locations to -1]
A 6 @ [work backwards]
[132] A 3 @ [make T order for inverse table]
T 135 @ [plant in code]
S 2 F [make -1 in address field]
[135] T B [store in inverse table]
A 135 @ [get T order]
S 2 F [dec address]
S 3 @ [compare with start of table]
E 132 @ [loop till done]
[Now fill in entries by reversing direct table]
T F [clear acc]
A 4 @ [work backwards]
[142] U 5 F [index in 5F]
A 2 @ [make A order for direct table]
T 145 @ [plant in code]
[145] A C [load entry from direct table, code in top 5 bits]
R 512 F [shift 11 right, 5-bit code to address field]
T 4 F [temp store]
C 4 F [pick out 5-bit code]
A 3 @ [make T order for inverse table]
T 152 @ [plant in code]
A 5 F [load index]
[152] T B [store in inverse table]
A 5 F [load index again]
S 2 F [update index]
E 142 @ [loop back]
[Here when inverse table is complete]
[156] T F [clear acc]
[157] A 21 @ [load address of "testing" message]
T F [to 0F for print subroutine]
[159] A 159 @
G 136 F [print "testing message"]
E 168 @ [jump to read from end of this file]
[Loop back here to get message from user]
[162] A 38 @ [load address of prompt]
T F [to 0F for print subroutine]
[164] A 164 @
G 136 F [print prompt]
O 10 @ [print null to flush teleprinter buffer]
Z F [stop]
[First time here, read message from end of this file.
Later times, read message from file chosen by the user.]
[168] A @ [load address of message]
T F [to 0F for input]
[170] A 170 @
G 114 F [read message]
[172] A 172 @
G 120 @ [print message]
[174] A 174 @
G 76 @ [call Caesar shift subroutine]
A F [load error flag]
E 184 @ [jump if OK]
T F [error, clear acc]
A 64 @ [load address of error message]
T F
[181] A 181 @
G 136 F [print error message]
E 162 @ [back to try again]
[Here if message was enciphered without error]
[184] A 184 @
G 120 @ [print enciphered message]
[186] A 186 @
G 76 @ [call Caesar shift subroutine]
[188] A 188 @
G 120 @ [print deciphered message]
E 162 @ [back for another message]
E 129 Z [define entry point]
P F [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
|
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
| #Ruby | Ruby |
fact = 1
e = 2
e0 = 0
n = 2
until (e - e0).abs < Float::EPSILON do
e0 = e
fact *= n
n += 1
e += 1.0 / fact
end
puts 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)
| #VBA | VBA |
Option Explicit
Sub Main_Bulls_And_Cows_Player()
Dim collSoluces As New Collection, Elem As Variant, Soluce As String
Dim strNumber As String, cpt As Byte, p As Byte
Dim i As Byte, Bulls() As Boolean, NbBulls As Byte, Cows As Byte, Poss As Long
Const NUMBER_OF_DIGITS As Byte = 4
strNumber = CreateNb(NUMBER_OF_DIGITS)
Debug.Print "TOSS : " & StrConv(strNumber, vbUnicode)
Debug.Print "---------- START ------------"
Set collSoluces = CollOfPossibleNumbers
Poss = collSoluces.Count
For Each Elem In collSoluces
'Debug.Print "Number of possibilities : " & Poss
Debug.Print "Attempt : " & StrConv(Elem, vbUnicode)
NbBulls = 0: Soluce = Elem
ReDim Bulls(NUMBER_OF_DIGITS - 1)
For i = 1 To NUMBER_OF_DIGITS
If IsBull(strNumber, Mid(Elem, i, 1), i) Then
Bulls(i - 1) = True: NbBulls = NbBulls + 1
RemoveIfNotBull collSoluces, Mid(Elem, i, 1), i
End If
Next i
Cows = 0
For i = 1 To NUMBER_OF_DIGITS
If Not Bulls(i - 1) Then
If IsCow(collSoluces, strNumber, Mid(Elem, i, 1), p) Then
If Not Bulls(p - 1) Then Cows = Cows + 1
End If
End If
Next i
Poss = collSoluces.Count
Debug.Print "Bulls : " & NbBulls & ", Cows : " & Cows
If Poss = 1 Then Exit For
Next
Debug.Print "---------- THE END ------------"
Debug.Print "TOSS WAS : " & StrConv(strNumber, vbUnicode) & " We found : " & StrConv(Soluce, vbUnicode)
End Sub
Function CreateNb(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
CreateNb = strTemp
End Function
Function CollOfPossibleNumbers() As Collection
Dim TempColl As New Collection
Dim x As String
Dim i As Long
Dim Flag As Boolean
Dim b As Byte
For i = 1234 To 9876
Flag = False
For b = 1 To 4
x = CStr(i)
If Len(Replace(x, Mid(x, b, 1), "")) < 3 Then
Flag = True: Exit For
End If
Next
If Not Flag Then TempColl.Add x, x
Next i
Set CollOfPossibleNumbers = TempColl
End Function
Function IsBull(strgNb As String, Digit As String, place As Byte) As Boolean
IsBull = (Mid(strgNb, place, 1) = Digit)
End Function
Function IsCow(C As Collection, strgNb As String, Digit As String, place As Byte) As Boolean
If (InStr(strgNb, Digit) > 0) Then
IsCow = True: place = InStr(strgNb, Digit)
RemoveIfNotCow C, Digit
End If
End Function
Sub RemoveIfNotBull(C As Collection, Digit As String, place As Byte)
Dim E As Variant
For Each E In C
If Mid(E, place, 1) <> Digit Then C.Remove E
Next
End Sub
Sub RemoveIfNotCow(C As Collection, Digit As String)
Dim E As Variant
For Each E In C
If (InStr(E, Digit) = 0) Then C.Remove E
Next
End Sub
|
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.
| #Java | Java | myMethod() |
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
| #OCaml | OCaml | let imp_catalan n =
let return = ref 1 in
for i = 1 to n do
return := !return * 2 * (2 * i - 1) / (i + 1)
done;
!return
let rec catalan = function
| 0 -> 1
| n -> catalan (n - 1) * 2 * (2 * n - 1) / (n + 1)
let memoize f =
let cache = Hashtbl.create 20 in
fun n ->
match Hashtbl.find_opt cache n with
| None ->
let x = f n in
Hashtbl.replace cache n x;
x
| Some x -> x
let catalan_cache = Hashtbl.create 20
let rec memo_catalan n =
if n = 0 then 1 else
match Hashtbl.find_opt catalan_cache n with
| None ->
let x = memo_catalan (n - 1) * 2 * (2 * n - 1) / (n + 1) in
Hashtbl.replace catalan_cache n x;
x
| Some x -> x
let () =
if not !Sys.interactive then
let bench label f n times =
let start = Unix.gettimeofday () in
begin
for i = 1 to times do f n done;
let stop = Unix.gettimeofday () in
Printf.printf "%s (%d runs) : %.3f\n"
label times (stop -. start)
end in
let show f g h f' n =
for i = 0 to n do
Printf.printf "%2d %7d %7d %7d %7d\n"
i (f i) (g i) (h i) (f' i)
done
in
List.iter (fun (l, f) -> bench l f 15 10_000_000)
["imperative", imp_catalan;
"recursive", catalan;
"hand-memoized", memo_catalan;
"memoized", (memoize catalan)];
show imp_catalan catalan memo_catalan (memoize catalan) 15
|
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
| #Sidef | Sidef | func brace_expand (input) {
var current = ['']
var stack = [[current]]
loop {
var t = input.match(
/\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx
)[0] \\ break
if (t == '{') {
stack << [current = ['']]
}
elsif ((t == ',') && (stack.len > 1)) {
stack[-1] << (current = [''])
}
elsif ((t == '}') && (stack.len > 1)) {
var group = stack.pop
current = stack[-1][-1]
# handle the case of brace pairs without commas:
group[0][] = group[0].map{ '{'+_+'}' }... if (group.len == 1)
current[] = current.map { |c|
group.map { .map { c + _ }... }...
}...
}
else {
current[] = current.map { _ + t }...
}
}
# handle the case of missing closing braces:
while (stack.len > 1) {
var right = stack[-1].pop
var sep = ','
if (stack[-1].is_empty) {
sep = '{'
stack.pop
}
current = stack[-1][-1]
current[] = current.map { |c|
right.map { c + sep + _ }...
}...
}
return current
}
DATA.each { |line|
say line
brace_expand(line).each { "\t#{_}".say }
say ''
}
__DATA__
~/{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
| #Perl | Perl | use strict;
use warnings;
use ntheory qw<is_prime>;
use constant Inf => 1e10;
sub is_Brazilian {
my($n) = @_;
return 1 if $n > 6 && 0 == $n%2;
LOOP: for (my $base = 2; $base < $n - 1; ++$base) {
my $digit;
my $nn = $n;
while (1) {
my $x = $nn % $base;
$digit //= $x;
next LOOP if $digit != $x;
$nn = int $nn / $base;
if ($nn < $base) {
return 1 if $digit == $nn;
next LOOP;
}
}
}
}
my $upto = 20;
print "First $upto Brazilian numbers:\n";
my $n = 0;
print do { $n < $upto ? (is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;
print "\n\nFirst $upto odd Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!($_%2) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;
print "\n\nFirst $upto prime Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!is_prime($_) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf; |
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
| #Liberty_BASIC | Liberty BASIC |
rem Adapted from LB examples included with software
[start]
prompt "Enter year(yyyy)?";year
if year<1900 then notice "1900 or later":goto [start]
ax=1:gx=8:ay=3:gy=10
locate 52,1:print year
for mr = 0 to 3
for mc = 0 to 2
mt=mt+1
aDate$ = str$(mt)+"/01/"+str$(year)
px = ax+mc*gx
py = ay+mr*gy
gosub [printout]
next mc
next mr
gosub [snoopy]
end
[printout]
locate 4*px-3+int((30-len(monthname$(aDate$)))/2),py
print monthname$(aDate$)
FirstDay=date$(word$(aDate$,1,"/")+"/1/"+word$(aDate$,3,"/"))
LastDay$=date$(date$(word$(date$(FirstDay+32),1,"/")+"/1/"+word$(date$(FirstDay+32),3,"/"))-1)
dow=val(word$("3 4 5 x 6 7 x 1 2",int((FirstDay/7-int(FirstDay/7))*10)+1))
locate px*4-3, py+1
print " Su Mo Tu We Th Fr Sa"
for i=1 to val(mid$(LastDay$,4,2))
y=int((i+dow-2)/7)
x=px+(i+dow-2)-y*7
x=4*x
locate x-4,py+y+2
print using("###",i)
next i
return
[snoopy]
locate ax, ay+4*gy
print space$(4*gx);" ,-~~-.___."
print space$(4*gx);" / ()=(() \"
print space$(4*gx);" ( ( 0"
print space$(4*gx);" \._\, ,----'"
print space$(4*gx);" ##XXXxxxxxxx"
print space$(4*gx);" / ---'~;"
print space$(4*gx);" / /~|-"
print space$(4*gx);" _____=( ~~ |______ "
print space$(4*gx);" /_____________________\ "
print space$(4*gx);" /_______________________\"
print space$(4*gx);" /_________________________\"
print space$(4*gx);"/___________________________\"
print space$(4*gx);" |____________________|"
print space$(4*gx);" |____________________|"
print space$(4*gx);" |____________________|"
print space$(4*gx);" | |"
return
function monthname$(aDate$)
month=val(aDate$)
monthname$=word$("January February March April May June July August September October November December",month)
end function
|
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.
| #Perl | Perl | sub PI() { atan2(1,1) * 4 } # The, er, pi
sub STEP() { .5 } # How far does the particle move each step. Affects
# both speed and accuracy greatly
sub STOP_RADIUS() { 100 } # When the tree reaches this far from center, end
# At each step, move this much towards center. Bigger numbers help the speed because
# particles are less likely to wander off, but greatly affects tree shape.
# Should be between 0 and 1 ish. Set to 0 for pain.
sub ATTRACT() { .2 }
my @particles = map([ map([], 0 .. 2 * STOP_RADIUS) ], 0 .. 2 * STOP_RADIUS);
push @{ $particles[STOP_RADIUS][STOP_RADIUS] }, [0, 0];
my $r_start = 3;
my $max_dist = 0;
sub dist2 {
my ($dx, $dy) = ($_[0][0] - $_[1][0], $_[0][1] - $_[1][1]);
$dx * $dx + $dy * $dy
}
sub move {
my $p = shift;
# moved too far, kill particle
# return if dist2($p, [0, 0]) > 2 * $r_start * $r_start;
$p->[0] += 2 * $r_start while $p->[0] < -$r_start;
$p->[0] -= 2 * $r_start while $p->[0] > $r_start;
$p->[1] += 2 * $r_start while $p->[1] < -$r_start;
$p->[1] -= 2 * $r_start while $p->[1] > $r_start;
my ($ix, $iy) = (int($p->[0]), int($p->[1]));
my $dist = 2 * $r_start * $r_start;
my $nearest;
# see if the particle is close enough to stick to an exist one
for ($ix - 1 .. $ix + 1) {
my $idx = STOP_RADIUS + $_;
next if $idx > 2 * STOP_RADIUS || $idx < 0;
my $xs = $particles[ $idx ];
for ($iy - 1 .. $iy + 1) {
my $idx = STOP_RADIUS + $_;
next if $idx > 2 * STOP_RADIUS || $idx < 0;
for (@{ $xs->[ $idx ] }) {
my $d = dist2($p, $_);
next if $d > 2;
next if $d > $dist;
$dist = $d;
$nearest = $_;
}
}
}
# yes, found one
if ($nearest) {
my $displace = [ $p->[0] - $nearest->[0],
$p->[1] - $nearest->[1] ];
my $angle = atan2($displace->[1], $displace->[0]);
$p->[0] = $nearest->[0] + cos($angle);
$p->[1] = $nearest->[1] + sin($angle);
push @{$particles[$ix + STOP_RADIUS][$iy + STOP_RADIUS]}, [ @$p ];
$dist = sqrt dist2($p);
if ($dist + 10 > $r_start && $r_start < STOP_RADIUS + 10) {
$r_start = $dist + 10
}
if (int($dist + 1) > $max_dist) {
$max_dist = int($dist + 1);
# write_eps();
# system('pstopnm -portrait -xborder 0 -yborder 0 test.eps 2> /dev/null');
# system('pnmtopng test.eps001.ppm 2>/dev/null > test.png');
return 3 if $max_dist >= STOP_RADIUS;
}
return 2;
}
# random walk
my $angle = rand(2 * PI);
$p->[0] += STEP * cos($angle);
$p->[1] += STEP * sin($angle);
# drag particle towards center by some distance
my $nudge;
if (sqrt(dist2($p, [0, 0])) > STOP_RADIUS + 1) {
$nudge = 1;
} else {
$nudge = STEP * ATTRACT;
}
if ($nudge) {
$angle = atan2($p->[1], $p->[0]);
$p->[0] -= $nudge * cos($angle);
$p->[1] -= $nudge * sin($angle);
}
return 1;
}
my $count;
PARTICLE: while (1) {
my $a = rand(2 * PI);
my $p = [ $r_start * cos($a), $r_start * sin($a) ];
while (my $m = move($p)) {
if ($m == 1) { next }
elsif ($m == 2) { $count++; last; }
elsif ($m == 3) { last PARTICLE }
else { last }
}
print STDERR "$count $max_dist/@{[int($r_start)]}/@{[STOP_RADIUS]}\r" unless $count% 7;
}
sub write_eps {
my $size = 128;
my $p = $size / (STOP_RADIUS * 1.05);
my $b = STOP_RADIUS * $p;
if ($p < 1) {
$size = STOP_RADIUS * 1.05;
$b = STOP_RADIUS;
$p = 1;
}
my $hp = $p / 2;
open OUT, ">", "test.eps";
# print EPS to standard out
print OUT <<"HEAD";
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 @{[$size*2, $size*2]}
$size $size translate
/l{ rlineto }def
/c{ $hp 0 360 arc fill }def
-$size -$size moveto
$size 2 mul 0 l
0 $size 2 mul l
-$size 2 mul 0 l
closepath
0 setgray fill
0 setlinewidth .1 setgray 0 0 $b 0 360 arc stroke
.8 setgray /TimesRoman findfont 16 scalefont setfont
-$size 10 add $size -16 add moveto
(Step = @{[STEP]} Attract = @{[ATTRACT]}) show
0 1 0 setrgbcolor newpath
HEAD
for (@particles) {
for (@$_) {
printf OUT "%.3g %.3g c ", map { $_ * $p } @$_ for @$_;
}
}
print OUT "\n%%EOF";
close OUT;
}
write_eps; |
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
| #Fortran | Fortran | module bac
implicit none
contains
subroutine Gennum(n)
integer, intent(out) :: n(4)
integer :: i, j
real :: r
call random_number(r)
n(1) = int(r * 9.0) + 1
i = 2
outer: do while (i <= 4)
call random_number(r)
n(i) = int(r * 9.0) + 1
inner: do j = i-1 , 1, -1
if (n(j) == n(i)) cycle outer
end do inner
i = i + 1
end do outer
end subroutine Gennum
subroutine Score(n, guess, b, c)
character(*), intent(in) :: guess
integer, intent(in) :: n(0:3)
integer, intent(out) :: b, c
integer :: digit, i, j, ind
b = 0; c = 0
do i = 1, 4
read(guess(i:i), "(i1)") digit
if (digit == n(i-1)) then
b = b + 1
else
do j = i, i+2
ind = mod(j, 4)
if (digit == n(ind)) then
c = c + 1
exit
end if
end do
end if
end do
end subroutine Score
end module bac
program Bulls_and_Cows
use bac
implicit none
integer :: n(4)
integer :: bulls=0, cows=0, tries=0
character(4) :: guess
call random_seed
call Gennum(n)
write(*,*) "I have selected a number made up of 4 digits (1-9) without repetitions."
write(*,*) "You attempt to guess this number."
write(*,*) "Every digit in your guess that is in the correct position scores 1 Bull"
write(*,*) "Every digit in your guess that is in an incorrect position scores 1 Cow"
write(*,*)
do while (bulls /= 4)
write(*,*) "Enter a 4 digit number"
read*, guess
if (verify(guess, "123456789") /= 0) then
write(*,*) "That is an invalid entry. Please try again."
cycle
end if
tries = tries + 1
call Score (n, guess, bulls, cows)
write(*, "(a, i1, a, i1, a)") "You scored ", bulls, " bulls and ", cows, " cows"
write(*,*)
end do
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
end program Bulls_and_Cows |
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
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
s: STRING_32
do
s := "The tiny tiger totally taunted the tall Till."
print ("%NString to encode: " + s)
print ("%NEncoded string: " + encode (s, 12))
print ("%NDecoded string (after encoding and decoding): " + decode (encode (s, 12), 12))
end
feature -- Basic operations
decode (to_be_decoded: STRING_32; offset: INTEGER): STRING_32
-- Decode `to be decoded' according to `offset'.
do
Result := encode (to_be_decoded, 26 - offset)
end
encode (to_be_encoded: STRING_32; offset: INTEGER): STRING_32
-- Encode `to be encoded' according to `offset'.
local
l_offset: INTEGER
l_char_code: INTEGER
do
create Result.make_empty
l_offset := (offset \\ 26) + 26
across to_be_encoded as tbe loop
if tbe.item.is_alpha then
if tbe.item.is_upper then
l_char_code := ('A').code + (tbe.item.code - ('A').code + l_offset) \\ 26
Result.append_character (l_char_code.to_character_32)
else
l_char_code := ('a').code + (tbe.item.code - ('a').code + l_offset) \\ 26
Result.append_character (l_char_code.to_character_32)
end
else
Result.append_character (tbe.item)
end
end
end
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
| #Rust | Rust | const EPSILON: f64 = 1e-15;
fn main() {
let mut fact: u64 = 1;
let mut e: f64 = 2.0;
let mut n: u64 = 2;
loop {
let e0 = e;
fact *= n;
n += 1;
e += 1.0 / fact as f64;
if (e - e0).abs() < EPSILON {
break;
}
}
println!("e = {:.15}", e);
} |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Scala | Scala | import scala.annotation.tailrec
object CalculateE extends App {
private val ε = 1.0e-15
@tailrec
def iter(fact: Long, ℯ: Double, n: Int, e0: Double): Double = {
val newFact = fact * n
val newE = ℯ + 1.0 / newFact
if (math.abs(newE - ℯ) < ε) ℯ
else iter(newFact, newE, n + 1, ℯ)
}
println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
} |
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)
| #Wren | Wren | import "random" for Random
var countBullsAndCows = Fn.new { |guess, answer|
var bulls = 0
var cows = 0
var i = 0
for (d in guess) {
if (answer[i] == d) {
bulls = bulls + 1
} else if (answer.contains(d)) {
cows = cows + 1
}
i = i + 1
}
return [bulls, cows]
}
var r = Random.new()
var choices = []
// generate all possible distinct 4 digit (1 to 9) integer arrays
for (i in 1..9) {
for (j in 1..9) {
if (j != i) {
for (k in 1..9) {
if (k != i && k != j) {
for (l in 1..9) {
if (l != i && l != j && l != k) {
choices.add([i, j, k, l])
}
}
}
}
}
}
}
// pick one at random as the answer
var answer = choices[r.int(choices.count)]
// keep guessing, pruning the list as we go based on the score, until answer found
while (true) {
var guess = choices[r.int(choices.count)]
var bc = countBullsAndCows.call(guess, answer)
System.print("Guess = %(guess.join("")) Bulls = %(bc[0]) Cows = %(bc[1])")
if (bc[0] == 4) {
System.print("You've just found the answer!")
return
}
for (i in choices.count - 1..0) {
var bc2 = countBullsAndCows.call(choices[i], answer)
// if score is no better remove it from the list of choices
if (bc2[0] <= bc[0] && bc2[1] <= bc[1]) choices.removeAt(i)
}
if (choices.count == 0) {
System.print("Something went wrong as no choices left! Aborting program")
}
} |
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.
| #JavaScript | JavaScript | var foo = function() { return arguments.length };
foo() // 0
foo(1, 2, 3) // 3 |
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
| #Oforth | Oforth | : catalan( n -- m )
n ifZero: [ 1 ] else: [ catalan( n 1- ) 2 n * 1- * 2 * n 1+ / ] ; |
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
| #Simula | Simula | CLASS ARRAYLISTS;
BEGIN
CLASS ITEM;;
CLASS ITEMARRAY(N); INTEGER N;
BEGIN
REF(ITEM) ARRAY DATA(1:N);
! OUTTEXT("NEW ITEMARRAY WITH ");!OUTINT(N, 0);!OUTTEXT(" ELEMENTS");
! OUTIMAGE;
END;
CLASS ARRAYLIST;
BEGIN
PROCEDURE EXPAND(N); INTEGER N;
BEGIN
INTEGER I;
REF(ITEMARRAY) TEMP;
! OUTTEXT("EXPAND TO CAPACITY ");!OUTINT(N, 0);!OUTIMAGE;
TEMP :- NEW ITEMARRAY(N);
FOR I := 1 STEP 1 UNTIL SIZE DO
TEMP.DATA(I) :- ITEMS.DATA(I);
ITEMS :- TEMP;
END;
PROCEDURE ADD(T); REF(ITEM) T;
BEGIN
IF SIZE + 1 > CAPACITY THEN
BEGIN
CAPACITY := 2 * CAPACITY;
EXPAND(CAPACITY);
END;
SIZE := SIZE + 1;
ITEMS.DATA(SIZE) :- T;
! OUTTEXT("SIZE IS ");!OUTINT(SIZE, 0);!OUTIMAGE;
END;
PROCEDURE REMOVE(I); INTEGER I;
BEGIN
INTEGER J;
IF I < 1 OR I > SIZE THEN ERROR("REMOVE: INDEX OUT OF BOUNDS");
FOR J := I STEP 1 UNTIL SIZE - 1 DO
ITEMS.DATA(J) :- ITEMS.DATA(J + 1);
ITEMS.DATA(SIZE) :- NONE;
SIZE := SIZE - 1;
END;
REF(ITEM) PROCEDURE GET(I); INTEGER I;
BEGIN
IF I < 1 OR I > SIZE THEN ERROR("GET: INDEX OUT OF BOUNDS");
GET :- ITEMS.DATA(I);
END;
INTEGER CAPACITY;
INTEGER SIZE;
REF(ITEMARRAY) ITEMS;
CAPACITY := 20;
SIZE := 0;
EXPAND(CAPACITY);
END;
ITEM CLASS TEXTITEM(TXT); TEXT TXT;;
ARRAYLIST CLASS TEXTARRAYLIST;
BEGIN
PROCEDURE ADD(T); TEXT T;
THIS TEXTARRAYLIST QUA ARRAYLIST.ADD(NEW TEXTITEM(T));
TEXT PROCEDURE GET(I); INTEGER I;
GET :- THIS TEXTARRAYLIST QUA ARRAYLIST.GET(I) QUA TEXTITEM.TXT;
END;
ITEM CLASS REALITEM(X); REAL X;;
ARRAYLIST CLASS REALARRAYLIST;
BEGIN
PROCEDURE ADD(X); REAL X;
THIS REALARRAYLIST QUA ARRAYLIST.ADD(NEW REALITEM(X));
REAL PROCEDURE GET(I); INTEGER I;
GET := THIS REALARRAYLIST QUA ARRAYLIST.GET(I) QUA REALITEM.X;
END;
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
| #Tailspin | Tailspin |
templates braceExpansion
composer braceParse
[ <part|'[{}\\,]'>* ] // This is not simply <production> because there may be unbalanced special chars
rule production: [ <part>* ]
rule part: <alternation|balancedBraces|escapedCharacter|'[^{}\\,]+'>+
rule alternation: (<='{'>) [ <production> <alternate>+ ] (<='}'>)
rule alternate: (<=','>) <production>
rule balancedBraces: <='{'> <part>* <='}'>
rule escapedCharacter: <'\\.'>
end braceParse
templates collateSequence
@: [''];
$... -> #
$@!
when <'.*'> do
def part: $;
@: [$@... -> '$;$part;'];
otherwise
def alternates: [ $... -> collateSequence ... ];
@: [$@... -> \(def prefix: $; $alternates... -> '$prefix;$;' ! \)];
end collateSequence
$ -> braceParse -> collateSequence !
end braceExpansion
'~/{Downloads,Pictures}/*.{jpg,gif,png}' -> '"$;" expands to:$ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write
'It{{em,alic}iz,erat}e{d,}, please.' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write
'{,{,gotta have{ ,\, again\, }}more }cowbell!' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write
'{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write
|
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
| #Phix | Phix | with javascript_semantics
function same_digits(integer n, b)
integer f = remainder(n,b)
n = floor(n/b)
while n>0 do
if remainder(n,b)!=f then return false end if
n = floor(n/b)
end while
return true
end function
function is_brazilian(integer n)
if n>=7 then
if remainder(n,2)=0 then return true end if
for b=2 to n-2 do
if same_digits(n,b) then return true end if
end for
end if
return false
end function
constant kinds = {" ", " odd ", " prime "}
for i=1 to length(kinds) do
printf(1,"First 20%sBrazilian numbers:\n", {kinds[i]})
integer c = 0, n = 7, p = 4
while true do
if is_brazilian(n) then
printf(1,"%d ",n)
c += 1
if c==20 then
printf(1,"\n\n")
exit
end if
end if
switch i
case 1: n += 1
case 2: n += 2
case 3: p += 1; n = get_prime(p)
end switch
end while
end for
integer n = 7, c = 0
atom t0 = time(), t1 = time()+1
while c<100000 do
if platform()!=JS and time()>t1 then
printf(1,"checking %d [count:%d]...\r",{n,c})
t1 = time()+1
end if
c += is_brazilian(n)
n += 1
end while
printf(1,"The %,dth Brazilian number: %d\n", {c,n-1})
?elapsed(time()-t0)
|
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
| #Lingo | Lingo | ----------------------------------------
-- @desc Class "Calendar"
-- @file parent script "Calendar"
----------------------------------------
property _months
property _weekdayStr
property _refDateObj
property _year
property _calStr
on new (me)
me._months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
me._weekdayStr = "Mo Tu We Th Fr Sa Su"
me._refDateObj = date(1905,1,2)
return me
end
on make (me, year)
me._year = year
me._calStr = ""
-- prefill cal string with spaces
emptyLine = bytearray(68,32).readRawString(68)&RETURN
repeat with i = 1 to 38
put emptyLine after _calStr
end repeat
me._write (string(year), 32, 1)
repeat with i = 1 to 12
me._writeMonth(i)
end repeat
return me._calStr
end
on _writeMonth (me, monthNum)
xOffset = (monthNum-1) mod 3 * 24
yOffset = (monthNum-1)/3 * 9 + 2
pre = (20 - me._months[monthNum].length)/2
me._write(me._months[monthNum], 1+xOffset+pre, 1+yOffset)
me._write(me._weekdayStr, 1+xOffset, 2+yOffset)
y = 3
x = ((date(me._year, monthNum, 1) - me._refDateObj) mod 7)+1
repeat with i = 1 to 31
if date(me._year, monthNum, i).month<>monthNum then exit repeat
dayStr = string(i)
if i<10 then put " " before dayStr
me._write(dayStr, x*3-2+xOffset, y+yOffset)
if x=7 then
y = y+1
x = 1
else
x = x+1
end if
end repeat
end
on _write (me, str, x, y)
put str into char x to x+str.length-1 of line y of _calStr
end |
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.
| #Phix | Phix | -- demo\rosetta\BrownianTree.exw
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
integer x,y,ox,oy
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
sequence grid = repeat(repeat(0,width),height)
integer xy = floor(width*height*0.8)
--atom t = time()+1
grid[floor(width/2)][floor(height/2)] = 1
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
for i=1 to xy do
x = rand(width) y = rand(height)
ox = x oy = y
while x>=1 and x<=width
and y>=1 and y<=height do
if grid[y][x] then
grid[oy][ox] = 1
cdCanvasPixel(cddbuffer, ox, oy, #00FF00)
exit
end if
ox = x x += rand(3)-2
oy = y y += rand(3)-2
end while
-- -- if making the canvas bigger/resizeable,
-- -- put this in so that you can kill it.
-- if time()>=t then
-- ?{i,xy}
-- t = time()+1
-- end if
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_RED)
return IUP_DEFAULT
end function
IupOpen()
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "200x200") -- fixed size
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
dlg = IupDialog(canvas, "RESIZE=NO")
IupSetAttribute(dlg, "TITLE", "Brownian Tree")
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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
| #F.23 | F# |
open System
let generate_number targetSize =
let rnd = Random()
let initial = Seq.initInfinite (fun _ -> rnd.Next(1,9))
initial |> Seq.distinct |> Seq.take(targetSize) |> Seq.toList
let countBulls guess target =
let hits = List.map2 (fun g t -> if g = t then true else false) guess target
List.filter (fun x -> x = true) hits |> List.length
let countCows guess target =
let mutable score = 0
for g in guess do
for t in target do
if g = t then
score <- score + 1
else
score <- score
score
let countScore guess target =
let bulls = countBulls guess target
let cows = countCows guess target
(bulls, cows)
let playRound guess target =
countScore guess target
let inline ctoi c : int =
int c - int '0'
let lineToList (line: string) =
let listc = Seq.map(fun c -> c |> string) line |> Seq.toList
let conv = List.map(fun x -> Int32.Parse x) listc
conv
let readLine() =
let line = Console.ReadLine()
if line <> null then
if line.Length = 4 then
Ok (lineToList line)
else
Error("Input guess must be 4 characters!")
else
Error("Input guess cannot be empty!")
let rec handleInput() =
let line = readLine()
match line with
| Ok x -> x
| Error s ->
printfn "%A" s
handleInput()
[<EntryPoint>]
let main argv =
let target = generate_number 4
let mutable shouldEnd = false
while shouldEnd = false do
let guess = handleInput()
let (b, c) = playRound guess target
printfn "Bulls: %i | Cows: %i" b c
if b = 4 then
shouldEnd <- true
else
shouldEnd <- false
0
|
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
| #Ela | Ela | open number char monad io string
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
caesar _ _ [] = ""
caesar op key (x::xs) = check shifted ++ caesar op key xs
where orig = indexOf (string.upper $ toString x) chars
shifted = orig `op` key
check val | orig == -1 = x
| val > 24 = trans $ val - 25
| val < 0 = trans $ 25 + val
| else = trans shifted
trans idx = chars:idx
cypher = caesar (+)
decypher = caesar (-)
key = 2
do
putStrLn "A string to encode:"
str <- readStr
putStr "Encoded string: "
cstr <- return <| cypher key str
put cstr
putStrLn ""
putStr "Decoded string: "
put $ decypher key cstr |
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
| #Scheme | Scheme |
(import (rnrs))
(define (e)
(sum
(map
(lambda (x) (/ 1.0 x))
(scanl
(lambda (a x) (* a x))
1
(enum-from-to 1 20)))))
(define (enum-from-to m n)
(if (>= n m)
(iterate-until (lambda (x) (>= x n)) (lambda (x) (+ 1 x)) m)
'()))
(define (iterate-until p f x)
(let loop ((vs (list x)) (h x))
(if (p h)
(reverse vs)
(loop (cons (f h) vs) (f h)))))
(define (sum xs)
(fold-left + 0 xs))
(define-record-type scan (fields acc scan))
(define (scanl f start-value xs)
(scan-scan
(fold-left
(lambda (a x)
(let ((v (f (scan-acc a) x)))
(make-scan v (cons v (scan-scan a)))))
(make-scan start-value (cons start-value '()))
xs)))
(display (e))
(newline) |
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)
| #Yabasic | Yabasic |
clear screen
guesses = 0
void = ran()
while(len(secret$) < 4) // zero not allowed
n$ = chr$(int(ran(1) * 9) + 49)
if not(instr(secret$, n$)) secret$ = secret$ + n$
wend
print " Secretly, my opponent just chose a number. But she didn't tell anyone!\n\t\t\t\t", secret$, "."
print " I can however be given a score for my guesses."
for i = 1234 to 9876
if check(str$(i)) = 0 then
available$ = available$ + " " + str$(i)
k = k +1
end if
next i
available$ = trim$(available$) // remove the surplus, leading space
while(true)
print
print "Currently holding ", k, " possible numbers. "
guess$ =word$(available$, 1 + int(k * ran(1)), " ")
print "Computer guessed ", guess$, " & got ";
bulls = 0
cows = 0
guesses = guesses + 1
r$ = score$(guess$, secret$)
bulls = val(word$(r$, 1, ","))
cows = val(word$(r$, 2, ","))
print bulls, " bull(s), and ", cows, " cow(s)."
if guess$ = secret$ then
print "\nComputer won after ", guesses, " guesses!";
print " That took ", right$(time$, 1), " seconds. ENDED!"
break
end if
kk = 0
new$ = ""
for j = 1 to k
bullsT = 0
cowsT = 0
possible$ = word$(available$, j, " ")
r$ = score$(guess$, possible$)
bullsT = val(word$(r$, 1, ","))
cowsT = val(word$(r$, 2, ","))
if (bullsT = bulls) and ( cowsT = cows) then
new$ = new$ + " " + possible$ // keep those with same score
kk = kk + 1
end if
next j
available$ = trim$(new$)
k = kk
wend
sub score$(a$, b$) // return as a csv string the number of bulls & cows.
local i, c$, bulls, cows
bulls = 0 : cows = 0
for i = 1 to 4
c$ = mid$(a$, i, 1)
if mid$(b$, i, 1) = c$ then
bulls = bulls + 1
else
if (instr(b$, c$) <> 0) and (instr(b$, c$) <> i) cows = cows + 1
end if
next i
return str$(bulls) + "," + str$(cows)
end sub
sub check(i$)
local t, i, j
t = 0 // zero flags available: 1 means not available
for i = 1 to 3
for j = i + 1 to 4
if mid$(i$, i, 1) = mid$(i$, j, 1) t = 1
next j
next i
if instr(i$, "0") t = 1
return t
end sub
sub word$(l$, i, d$)
local c$(1), n
n = token(l$, c$(), d$)
return c$(i)
end sub |
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.
| #jq | jq |
# Calling a function that requires no arguments:
f() = print("Hello world!")
f()
# Calling a function with a fixed number of arguments:
function f(x, y, z)
x*y - z^2
end
f(3, 4, 2)
# Calling a function with optional arguments:
# Note Julia uses multiple dispatch based on argument number and type, so
# f() is always different from f(x) unless default arguments are used, as in:
pimultiple(mult=1.0) = pi * mult # so pimultiple() defaults to pi * (1.0) or pi
# Calling a function with a variable number of arguments:
f(a,b,x...) = reduce(+, 0, x) - a - b
# here a and b are single arguments, but x is a tuple of x plus whatever follows x, so:
a = b = c = d = e = 3
f(a,b,c) # x within the function is (c) so == 0 + c - a - b
f(a,b,c,d,e) # x is a tuple == (c,d,e) so == (0 + c + d + e) - a - b
f(a,b) # x is () so == 0 - a - b
# Calling a function with named arguments:
# Functions with keyword arguments are defined using a semicolon in the function signature,
# as in
# function plot(x, y; style="solid", width=1, color="black")
#
# When the function is called, the semicolon is optional, so plot here can be
# either called with plot(x, y, width=2) or less commonly as plot(x, y; width=2).
# Using a function in statement context:
# Any function can be used as a variable by its name.
circlearea(x) = x^2 * pi
map(circlearea, [r1, r2, r3, r4])
# Using a function in first-class context within an expression:
cylindervolume = circlearea(r) * h
# Obtaining the return value of a function:
radius = 2.5
area = circlearea(2.5)
# Distinguishing built-in functions and user-defined functions:
# Julia does not attempt to distinguish these in any special way,
# but at the REPL command line there is ? help available for builtin
# functions that would not generally be available for the user-defined ones.
# Distinguishing subroutines and functions:
# All subroutines are called functions in Julia, regardless of whether they return values.
# Stating whether arguments are passed by value or by reference:
# As in Python, all arguments are passed by pointer reference, but assignment to a passed argument
# only changes the variable within the function. Assignment to the values referenced by the argument
## DOES however change those values. For instance:
a = 3
b = [3]
c = [3]
function f(x, y)
a = 0
b[1] = 0
c = [0]
end # a and c are now unchanged but b = [0]
# Is partial application possible and how:
# In Julia, there are many different ways to compose functions. In particular,
# Julia has an "arrow" operator -> that may be used to curry other functions.
f(a, b) = a^2 + a + b
v = [4, 6, 8]
map(x -> f(x, 10), v) # v = [30, 52, 82]
|
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
| #ooRexx | ooRexx | loop i = 0 to 15
say "catI("i") =" .catalan~catI(i)
say "catR1("i") =" .catalan~catR1(i)
say "catR2("i") =" .catalan~catR2(i)
end
-- This is implemented as static members on a class object
-- so that the code is able to keep state information between calls. This
-- memoization will speed up things like factorial calls by remembering previous
-- results.
::class catalan
-- initialize the class object
::method init class
expose facts catI catR1 catR2
facts = .table~new
catI = .table~new
catR1 = .table~new
catR2 = .table~new
-- seed a few items
facts[0] = 1
facts[1] = 1
facts[2] = 2
catI[0] = 1
catR1[0] = 1
catR2[0] = 1
-- private factorial method
::method fact private class
expose facts
use arg n
-- see if we've calculated this before
if facts~hasIndex(n) then return facts[n]
numeric digits 120
fact = 1
loop i = 2 to n
fact *= i
end
-- save this result
facts[n] = fact
return fact
::method catI class
expose catI
use arg n
numeric digits 20
res = catI[n]
if res == .nil then do
-- dividing by 1 removes insignificant trailing 0s
res = (self~fact(2 * n)/(self~fact(n + 1) * self~fact(n))) / 1
catI[n] = res
end
return res
::method catR1 class
expose catR1
use arg n
numeric digits 20
if catR1~hasIndex(n) then return catR1[n]
sum = 0
loop i = 0 to n - 1
sum += self~catR1(i) * self~catR1(n - 1 - i)
end
-- remove insignificant trailing 0s
sum = sum / 1
catR1[n] = sum
return sum
::method catR2 class
expose catR2
use arg n
numeric digits 20
res = catR2[n]
if res == .nil then do
res = ((2 * (2 * n - 1) * self~catR2(n - 1)) / (n + 1))
catR2[n] = res
end
return res |
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
| #Tcl | Tcl | package require Tcl 8.6
proc combine {cases1 cases2 {insert ""}} {
set result {}
foreach c1 $cases1 {
foreach c2 $cases2 {
lappend result $c1$insert$c2
}
}
return $result
}
proc expand {string *expvar} {
upvar 1 ${*expvar} expanded
set a {}
set result {}
set depth 0
foreach token [regexp -all -inline {(?:[^\\{},]|\\.)+|[\\{},]} $string] {
switch $token {
"," {
if {$depth == 0} {
lappend result {*}[commatize $a]
set a {}
set expanded 1
continue
}
}
"\{" {incr depth 1}
"\}" {incr depth -1}
}
append a $token
}
lappend result {*}[commatize $a]
return $result
}
proc commatize {string} {
set current {{}}
set depth 0
foreach token [regexp -all -inline {(?:[^\\{},]|\\.)+|[\\{},]} $string] {
switch $token {
"\{" {
if {[incr depth] == 1} {
set collect {}
continue
}
}
"\}" {
if {[incr depth -1] == 0} {
set foundComma 0
set exp [expand $collect foundComma]
if {!$foundComma} {
set exp [lmap c [commatize $collect] {set c \{$c\}}]
}
set current [combine $current $exp]
continue
} elseif {$depth < 0} {
set depth 0
}
}
}
if {$depth} {
append collect $token
} else {
set current [lmap s $current {set s $s$token}]
}
}
if {$depth} {
set current [combine $current [commatize $collect] "\{"]
}
return $current
} |
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
| #Python | Python | '''Brazilian numbers'''
from itertools import count, islice
# isBrazil :: Int -> Bool
def isBrazil(n):
'''True if n is a Brazilian number,
in the sense of OEIS:A125134.
'''
return 7 <= n and (
0 == n % 2 or any(
map(monoDigit(n), range(2, n - 1))
)
)
# monoDigit :: Int -> Int -> Bool
def monoDigit(n):
'''True if all the digits of n,
in the given base, are the same.
'''
def go(base):
def g(b, n):
(q, d) = divmod(n, b)
def p(qr):
return d != qr[1] or 0 == qr[0]
def f(qr):
return divmod(qr[0], b)
return d == until(p)(f)(
(q, d)
)[1]
return g(base, n)
return go
# -------------------------- TEST --------------------------
# main :: IO ()
def main():
'''First 20 members each of:
OEIS:A125134
OEIS:A257521
OEIS:A085104
'''
for kxs in ([
(' ', count(1)),
(' odd ', count(1, 2)),
(' prime ', primes())
]):
print(
'First 20' + kxs[0] + 'Brazilians:\n' +
showList(take(20)(filter(isBrazil, kxs[1]))) + '\n'
)
# ------------------- GENERIC FUNCTIONS --------------------
# primes :: [Int]
def primes():
''' Non finite sequence of prime numbers.
'''
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(str(x) for x in xs) + ']'
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
# MAIN ---
if __name__ == '__main__':
main() |
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
| #Lua | Lua | function print_cal(year)
local months={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
"JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}
local daysTitle="MO TU WE TH FR SA SU"
local daysPerMonth={31,28,31,30,31,30,31,31,30,31,30,31}
local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
if year%4==0 and year%100~=0 or year%400==0 then
daysPerMonth[2]=29
end
local sep=5
local monthwidth=daysTitle:len()
local calwidth=3*monthwidth+2*sep
function center(str, width)
local fill1=math.floor((width-str:len())/2)
local fill2=width-str:len()-fill1
return string.rep(" ",fill1)..str..string.rep(" ",fill2)
end
function makeMonth(name, skip,days)
local cal={
center(name,monthwidth),
daysTitle
}
local curday=1-skip
while #cal<9 do
line={}
for i=1,7 do
if curday<1 or curday>days then
line[i]=" "
else
line[i]=string.format("%2d",curday)
end
curday=curday+1
end
cal[#cal+1]=table.concat(line," ")
end
return cal
end
local calendar={}
for i,month in ipairs(months) do
local dpm=daysPerMonth[i]
calendar[i]=makeMonth(month, startday, dpm)
startday=(startday+dpm)%7
end
print(center("[SNOOPY]",calwidth),"\n")
print(center("--- "..year.." ---",calwidth),"\n")
for q=0,3 do
for l=1,9 do
line={}
for m=1,3 do
line[m]=calendar[q*3+m][l]
end
print(table.concat(line,string.rep(" ",sep)))
end
end
end
print_cal(1969) |
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.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de brownianTree (File Size Cnt)
(let Img (grid Size Size)
(put Img (/ Size 2) (/ Size 2) 'pix T)
(use (P Q)
(do Cnt
(setq P (get Img (rand 1 Size) (rand 1 Size)))
(loop
(setq Q ((if2 (rand T) (rand T) north east south west) P))
(T (; Q pix) (put P 'pix T))
(setq P (or Q (get Img (rand 1 Size) (rand 1 Size)))) ) ) )
(out "img.pbm"
(prinl "P1")
(prinl Size " " Size)
(for L Img
(for This L
(prin (if (: pix) 1 0)) )
(prinl) ) ) ) ) |
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
| #FreeBASIC | FreeBASIC | function get_digit( num as uinteger, ps as uinteger ) as uinteger
return (num mod 10^(ps+1))\10^ps
end function
function is_malformed( num as uinteger ) as boolean
if num > 9876 then return true
dim as uinteger i, j
for i = 0 to 2
for j = i+1 to 3
if get_digit( num, j ) = get_digit( num, i ) then return true
next j
next i
return false
end function
function make_number() as uinteger
dim as uinteger num = 0
while is_malformed(num)
num = int(rnd*9877)
wend
return num
end function
randomize timer
dim as uinteger count=0, num=make_number(), guess=0
dim as uinteger cows, bulls, i, j
while guess <> num
count += 1
do
print "Guess a number. "
input guess
loop while is_malformed(guess)
cows = 0
bulls = 0
for i = 0 to 3
for j = 0 to 3
if get_digit( num, i ) = get_digit( guess, j ) then
if i= j then bulls += 1
if i<>j then cows += 1
end if
next j
next i
print using "You scored # bulls and # cows."; bulls; cows
wend
print using "Correct. That took you ### guesses."; count |
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
| #Elena | Elena | import system'routines;
import system'math;
import extensions;
import extensions'text;
const string Letters = "abcdefghijklmnopqrstuvwxyz";
const string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string TestText = "Pack my box with five dozen liquor jugs.";
const int Key = 12;
class Encrypting : Enumerator
{
int theKey;
Enumerator theEnumerator;
constructor(int key, string text)
{
theKey := key;
theEnumerator := text.enumerator();
}
bool next() => theEnumerator;
reset() => theEnumerator;
enumerable() => theEnumerator;
get()
{
var ch := theEnumerator.get();
var index := Letters.indexOf(0, ch);
if (-1 < index)
{
^ Letters[(theKey+index).mod:26]
}
else
{
index := BigLetters.indexOf(0, ch);
if (-1 < index)
{
^ BigLetters[(theKey+index).mod:26]
}
else
{
^ ch
}
}
}
}
extension encryptOp
{
encrypt(key)
= new Encrypting(key, self).summarize(new StringWriter());
decrypt(key)
= new Encrypting(26 - key, self).summarize(new StringWriter());
}
public program()
{
console.printLine("Original text :",TestText);
var encryptedText := TestText.encrypt:Key;
console.printLine("Encrypted text:",encryptedText);
var decryptedText := encryptedText.decrypt:Key;
console.printLine("Decrypted text:",decryptedText);
console.readChar()
} |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const float: EPSILON is 1.0e-15;
const proc: main is func
local
var integer: fact is 1;
var float: e is 2.0;
var float: e0 is 0.0;
var integer: n is 2;
begin
repeat
e0 := e;
fact *:= n;
incr(n);
e +:= 1.0 / flt(fact);
until abs(e - e0) < EPSILON;
writeln("e = " <& e digits 15);
end func; |
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
| #Sidef | Sidef | func calculate_e(n=50) {
sum(0..n, {|k| 1/k! })
}
say calculate_e()
say calculate_e(69).as_dec(100) |
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)
| #zkl | zkl | d9:="123456789";
choices:=Walker.cproduct(d9,d9,d9,d9).pump(List,// lazy,-->3024, order is important
fcn(list){ s:=list.concat(); (s.unique().len()==4) and s or Void.Skip });
do{
guess:=choices[(0).random(choices.len())];
score:=ask("My guess is %s. How many bulls and cows? ".fmt(guess)).strip();
bulls,cows:=score.split("").apply("toInt"); // "12"-->(1,2)
choices=choices.filter('wrap(c){
bulls==c.zipWith('==,guess).sum(0) and // 0 + True == 1
cows ==c.zipWith('wrap(a,b){ a!=b and guess.holds(a) },guess).sum(0)
});
}while(choices.len()>1);
if(not choices) "Nothing fits the scores you gave.".println();
else "Solution found: ".println(choices[0]); |
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.
| #Julia | Julia |
# Calling a function that requires no arguments:
f() = print("Hello world!")
f()
# Calling a function with a fixed number of arguments:
function f(x, y, z)
x*y - z^2
end
f(3, 4, 2)
# Calling a function with optional arguments:
# Note Julia uses multiple dispatch based on argument number and type, so
# f() is always different from f(x) unless default arguments are used, as in:
pimultiple(mult=1.0) = pi * mult # so pimultiple() defaults to pi * (1.0) or pi
# Calling a function with a variable number of arguments:
f(a,b,x...) = reduce(+, 0, x) - a - b
# here a and b are single arguments, but x is a tuple of x plus whatever follows x, so:
a = b = c = d = e = 3
f(a,b,c) # x within the function is (c) so == 0 + c - a - b
f(a,b,c,d,e) # x is a tuple == (c,d,e) so == (0 + c + d + e) - a - b
f(a,b) # x is () so == 0 - a - b
# Calling a function with named arguments:
# Functions with keyword arguments are defined using a semicolon in the function signature,
# as in
# function plot(x, y; style="solid", width=1, color="black")
#
# When the function is called, the semicolon is optional, so plot here can be
# either called with plot(x, y, width=2) or less commonly as plot(x, y; width=2).
# Using a function in statement context:
# Any function can be used as a variable by its name.
circlearea(x) = x^2 * pi
map(circlearea, [r1, r2, r3, r4])
# Using a function in first-class context within an expression:
cylindervolume = circlearea(r) * h
# Obtaining the return value of a function:
radius = 2.5
area = circlearea(2.5)
# Distinguishing built-in functions and user-defined functions:
# Julia does not attempt to distinguish these in any special way,
# but at the REPL command line there is ? help available for builtin
# functions that would not generally be available for the user-defined ones.
# Distinguishing subroutines and functions:
# All subroutines are called functions in Julia, regardless of whether they return values.
# Stating whether arguments are passed by value or by reference:
# As in Python, all arguments are passed by pointer reference, but assignment to a passed argument
# only changes the variable within the function. Assignment to the values referenced by the argument
## DOES however change those values. For instance:
a = 3
b = [3]
c = [3]
function f(x, y)
a = 0
b[1] = 0
c = [0]
end # a and c are now unchanged but b = [0]
# Is partial application possible and how:
# In Julia, there are many different ways to compose functions. In particular,
# Julia has an "arrow" operator -> that may be used to curry other functions.
f(a, b) = a^2 + a + b
v = [4, 6, 8]
map(x -> f(x, 10), v) # v = [30, 52, 82]
|
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
| #PARI.2FGP | PARI/GP | catalan(n)=binomial(2*n,n+1)/n |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Dim out As New List(Of String)
Dim comma = False
While Not String.IsNullOrEmpty(s)
Dim gs = GetItem(s, depth)
Dim g = gs.Item1
s = gs.Item2
If String.IsNullOrEmpty(s) Then
Exit While
End If
out.AddRange(g)
If s(0) = "}" Then
If comma Then
Return Tuple.Create(out, s.Substring(1))
End If
Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1))
End If
If s(0) = "," Then
comma = True
s = s.Substring(1)
End If
End While
Return Nothing
End Function
Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)
Dim out As New List(Of String) From {""}
While Not String.IsNullOrEmpty(s)
Dim c = s(0)
If depth > 0 AndAlso (c = "," OrElse c = "}") Then
Return Tuple.Create(out, s)
End If
If c = "{" Then
Dim x = GetGroup(s.Substring(1), depth + 1)
If Not IsNothing(x) Then
Dim tout As New List(Of String)
For Each a In out
For Each b In x.Item1
tout.Add(a + b)
Next
Next
out = tout
s = x.Item2
Continue While
End If
End If
If c = "\" AndAlso s.Length > 1 Then
c += s(1)
s = s.Substring(1)
End If
out = out.Select(Function(a) a + c).ToList()
s = s.Substring(1)
End While
Return Tuple.Create(out, s)
End Function
Sub Main()
For Each s In {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\, again\, }}more }cowbell!",
"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
}
Dim fmt = "{0}" + vbNewLine + vbTab + "{1}"
Dim parts = GetItem(s)
Dim res = String.Join(vbNewLine + vbTab, parts.Item1)
Console.WriteLine(fmt, s, res)
Next
End Sub
End Module |
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
| #Racket | Racket | #lang racket
(require math/number-theory)
(define (repeat-digit? n base d-must-be-1?)
(call-with-values
(λ () (quotient/remainder n base))
(λ (q d) (and (or (not d-must-be-1?) (= d 1))
(let loop ((n q))
(if (zero? n)
d
(call-with-values
(λ () (quotient/remainder n base))
(λ (q r) (and (= d r) (loop q))))))))))
(define (brazilian? n (for-prime? #f))
(for/first ((b (in-range 2 (sub1 n))) #:when (repeat-digit? n b for-prime?)) b))
(define (prime-brazilian? n)
(and (prime? n) (brazilian? n #t)))
(module+ main
(displayln "First 20 Brazilian numbers:")
(stream->list (stream-take (stream-filter brazilian? (in-naturals)) 20))
(displayln "First 20 odd Brazilian numbers:")
(stream->list (stream-take (stream-filter brazilian? (stream-filter odd? (in-naturals))) 20))
(displayln "First 20 prime Brazilian numbers:")
(stream->list (stream-take (stream-filter prime-brazilian? (stream-filter odd? (in-naturals))) 20))) |
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
| #M2000_Interpreter | M2000 Interpreter |
Module Calendar (Year, LocaleId) {
Function GetMax(Year, Month) {
a=date(str$(Year)+"-"+str$(Month)+"-1")
max=32
do {
max--
m=val(str$(cdate(a,0,0,max), "m"))
} until m=Month
=max+1
}
Function SkipMo(Year, Month) {
a=date(str$(Year)+"-"+str$(Month)+"-1")
=(val(str$(a, "w"))-8) mod 7 +7
}
Function Title$(a$) {
=Ucase$(left$(a$,1))+Lcase$(Mid$(a$, 2))
}
locale LocaleId
Cursor 0,Height-1 ' last line, so each new line scroll all lines up
Print Over $(2), Year
Print
For j=0 to 3 {
Print
For i=1 to 3 {
Month=i+j*3
Print Part @((i-1)*29-1), $(2,22), Title$(Ucase$(locale$(55+Month)))
}
Print
Dim Skip(1 to 3), Count(1 to 3), D(1 to 3)=1
For i=1 to 3 {
Month=i+j*3
if i>1 Then Print String$(" ",8);
For k=42 to 48 :Print Title$(Ucase$(Left$(locale$(k),2)));" ";:Next k
Skip(i)=SkipMo(Year, Month)
Count(i)=GetMax(Year, Month)
}
Print
For i=1 to 3 {
if i>1 Then Print String$(" ",8);
For k=1 to 7 {
skip(i)--
if skip(i)>0 Then Print " "; :continue
Count(i)--
Print format$("{0::-2} ", d(i));
d(i)++
}
}
Print
Print @(0)
For m=1 to 5 {
For i=1 to 3 {
if i>1 Then Print String$(" ",8);
For k=1 to 7 {
Count(i)--
if Count(i)<0 Then Print " "; : Continue
Print format$("{0::-2} ", d(i));
d(i)++
}
}
Print
}
}
}
Form 80,43
Calendar 1969, 1033 ' English
k=Key$ ' wait key
Calendar 2018, 1032 ' Greek
|
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.
| #Processing | Processing | boolean SIDESTICK = false;
boolean[][] isTaken;
void setup() {
size(512, 512);
background(0);
isTaken = new boolean[width][height];
isTaken[width/2][height/2] = true;
}
void draw() {
int x = floor(random(width));
int y = floor(random(height));
if (isTaken[x][y]) {
return;
}
while (true) {
int xp = x + floor(random(-1, 2));
int yp = y + floor(random(-1, 2));
boolean iscontained = (
0 <= xp && xp < width &&
0 <= yp && yp < height
);
if (iscontained && !isTaken[xp][yp]) {
x = xp;
y = yp;
continue;
} else {
if (SIDESTICK || (iscontained && isTaken[xp][yp])) {
isTaken[x][y] = true;
set(x, y, #FFFFFF);
}
break;
}
}
if (frameCount > width * height) {
noLoop();
}
} |
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
| #Frink | Frink |
// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]
// Put 4 random digits into target array
digits = array[1 to 9]
target = new array
for i = 0 to 3
{
target@i = digits.removeRandom[]
}
// Game variables
guessCount = 0
solved = 0
while solved == 0
{
// Round variables
bulls = 0
cows = 0
// Input guess from player
guess = input["Guess a 4 digit number with numbers 1 to 9: "]
// Valid Guess Tests. Set validGuess to 1. If any test fails it will be set to 0
validGuess = 1
// Test for exactly 4 digits
if length[guess] != 4
{
println["$guess is invalid. Your guess must be 4 digits."]
validGuess = 0
}
// Test for any characters not in 1 - 9 using regex
if guess =~ %r/[^1-9]/
{
println["$guess is invalid. Your guess can only contain the digits 1 through 9."]
validGuess = 0
}
// Check for duplicate digits in guess
comboCheck = 1
guessArr = charList[guess] // Split guess string into array of characters.
guessArrCombos = guessArr.combinations[2] // Divide the array into all possible 2 digits combinations.
for geussCombo = guessArrCombos
{
if geussCombo@0 == geussCombo@1 // If the two digits in the combinations are the same mark the comboCheck as failed.
comboCheck = 0
}
if comboCheck == 0
{
println["$guess is invalid. Each digit in your guess should be unique."]
validGuess = 0
}
// If all tests pass, continue with the game.
if validGuess == 1
{
guessCount = guessCount + 1
for i = 0 to 3
{
if parseInt[guessArr@i] == target@i // Convert guess from string to int. Frink imports all input as strings.
{
bulls = bulls + 1
next // If bull is found, skip the contains check.
}
if target.contains[parseInt[guessArr@i]]
{
cows = cows + 1
}
}
if bulls == 4
{
solved = 1 // Exit from While loop.
} else
{
// Print the results of the guess. Formatting for plurals.
bullsPlural = bulls == 1 ? "bull" : "bulls"
cowsPlural = cows == 1 ? "cow" : "cows"
println["Your guess of $guess had $bulls $bullsPlural and $cows $cowsPlural."]
}
}
}
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]
|
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
| #Elixir | Elixir | defmodule Caesar_cipher do
defp set_map(map, range, key) do
org = Enum.map(range, &List.to_string [&1])
{a, b} = Enum.split(org, key)
Enum.zip(org, b ++ a) |> Enum.into(map)
end
def encode(text, key) do
map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key)
String.graphemes(text) |> Enum.map_join(fn c -> Map.get(map, c, c) end)
end
end
text = "The five boxing wizards jump quickly"
key = 3
IO.puts "Original: #{text}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}" |
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
| #Standard_ML | Standard ML | fun calcEToEps() =
let
val eps = 1.0e~15
fun calcToEps'(eest: real, prev: real, denom, i) =
if Real.abs(eest - prev) < eps then
eest
else
let
val denom' = denom * i;
val prev' = eest
in
calcToEps'(eest + 1.0/denom', prev', denom', i + 1.0)
end
in
calcToEps'(2.0, 1.0, 1.0, 2.0)
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
| #Swift | Swift | import Foundation
func calculateE(epsilon: Double = 1.0e-15) -> Double {
var fact: UInt64 = 1
var e = 2.0, e0 = 0.0
var n = 2
repeat {
e0 = e
fact *= UInt64(n)
n += 1
e += 1.0 / Double(fact)
} while fabs(e - e0) >= epsilon
return e
}
print(String(format: "e = %.15f\n", arguments: [calculateE()])) |
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.
| #Kotlin | Kotlin | // version 1.0.6
fun fun1() = println("No arguments")
fun fun2(i: Int) = println("One argument = $i")
fun fun3(i: Int, j: Int = 0) = println("One required argument = $i, one optional argument = $j")
fun fun4(vararg v: Int) = println("Variable number of arguments = ${v.asList()}")
fun fun5(i: Int) = i * i
fun fun6(i: Int, f: (Int) -> Int) = f(i)
fun fun7(i: Int): Double = i / 2.0
fun fun8(x: String) = { y: String -> x + " " + y }
fun main(args: Array<String>) {
fun1() // no arguments
fun2(2) // fixed number of arguments, one here
fun3(3) // optional argument, default value used here
fun4(4, 5, 6) // variable number of arguments
fun3(j = 8, i = 7) // using named arguments, order unimportant
val b = false
if (b) fun1() else fun2(9) // statement context
println(1 + fun6(4, ::fun5) + 3) // first class context within an expression
println(fun5(5)) // obtaining return value
println(Math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver
fun1() // calling sub-routine which has a Unit return type by default
println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit)
println(fun8("Hello")("world")) // partial application isn't supported though you can do this
} |
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
| #Pascal | Pascal | Program CatalanNumbers(output);
function catalanNumber1(n: integer): double;
begin
if n = 0 then
catalanNumber1 := 1.0
else
catalanNumber1 := double(4 * n - 2) / double(n + 1) * catalanNumber1(n-1);
end;
var
number: integer;
begin
writeln('Catalan Numbers');
writeln('Recursion with a fraction:');
for number := 0 to 14 do
writeln (number:3, round(catalanNumber1(number)):9);
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
| #Wren | Wren | var getGroup // forward declaration
var getItem = Fn.new { |s, depth|
var out = [""]
while (s != "") {
var c = s[0]
if (depth > 0 && (c == "," || c == "}")) return [out, s]
var cont = false
if (c == "{") {
var x = getGroup.call(s[1..-1], depth+1)
if (!x[0].isEmpty) {
var t = []
for (a in out) {
for (b in x[0]) {
t.add(a + b)
}
}
out = t
s = x[1]
cont = true
}
}
if (!cont) {
if (c == "\\" && s.count > 1) {
c = c + s[1]
s = s[1..-1]
}
out = out.map { |a| a + c }.toList
s = s[1..-1]
}
}
return [out, s]
}
getGroup = Fn.new { |s, depth|
var out = []
var comma = false
while (s != "") {
var t = getItem.call(s, depth)
var g = t[0]
s = t[1]
if (s == "") break
out.addAll(g)
if (s[0] == "}") {
if (comma) return [out, s[1..-1]]
return [out.map { |a| "{" + a + "}" }.toList, s[1..-1]]
}
if (s[0] == ",") {
comma = true
s = s[1..-1]
}
}
return [[], ""]
}
var inputs = [
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"It{{em,alic}iz,erat}e{d,}, please.",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
]
for (input in inputs) {
System.print(input)
for (s in getItem.call(input, 0)[0]) System.print(" " + s)
System.print()
} |
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
| #Raku | Raku | multi is-Brazilian (Int $n where $n %% 2 && $n > 6) { True }
multi is-Brazilian (Int $n) {
LOOP: loop (my int $base = 2; $base < $n - 1; ++$base) {
my $digit;
for $n.polymod( $base xx * ) {
$digit //= $_;
next LOOP if $digit != $_;
}
return True
}
False
}
my $upto = 20;
put "First $upto Brazilian numbers:\n", (^Inf).hyper.grep( &is-Brazilian )[^$upto];
put "\nFirst $upto odd Brazilian numbers:\n", (^Inf).hyper.map( * * 2 + 1 ).grep( &is-Brazilian )[^$upto];
put "\nFirst $upto prime Brazilian numbers:\n", (^Inf).hyper(:8degree).grep( { .is-prime && .&is-Brazilian } )[^$upto]; |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DataGrid[
rowHeights:{__Integer},
colWidths:{__Integer},
spacings:{_Integer,_Integer},
borderWidths:{{_Integer,_Integer},{_Integer,_Integer}},
options_Association,
data:{__List?MatrixQ}]:=
With[
(*Need to make sure we have sensible defaults for the decoration options.*)
{alignment=Lookup[options,"alignment",{0,0}],
background=Lookup[options,"background"," "],
dividers=Lookup[options,"dividers",{" "," "," "}],
border=Lookup[options,"border"," "],
dims={Length[rowHeights],Length[colWidths]}},
(*Pad the data so that it will fit into the specified rectangle (list of lists).*)
With[{augmentedData=PadRight[data,Times@@dims,{{{background}}}]},
(*Create a matrix of dimensions based on desired rectangle. Once we have a matrix of cells we can "thread" these two matrices and use that data to coerce each cell into its final dimensions.*)
With[{cellDims=ArrayReshape[Outer[List,rowHeights,colWidths],{Times@@dims,2}]},
(*MatrixAlign, defined below, rescales and aligns each cell's data.*)
With[{undecoratedGrid=Partition[MapThread[MatrixAlign[alignment,#1,background][#2]&, {cellDims,augmentedData}],dims[[2]]]},
(*Add the spacing to each row.*)
With[{dividedRows=MapThread[Transpose[Riffle[#2,{ConstantArray[dividers[[2]],{#1,spacings[[2]]}]},{2,-2,2}]]&, {rowHeights,undecoratedGrid}]},
(*Add the spacing between rows.*)
With[{dividedColumn=Riffle[dividedRows,{Transpose[Riffle[ConstantArray[dividers[[1]],{spacings[[1]],#}]&/@colWidths,{ConstantArray[dividers[[3]],spacings]},{2,-2,2}]]},{2,-2,2}]},
(*Assemble all cell rows into actual character rows. We now have one large matrix.*)
With[{dividedGrid=Catenate[Map[Flatten,dividedColumn,{2}]]},
(*Add borders.*)
ArrayPad[dividedGrid,borderWidths,border]]]]]]]];
DataGrid[dims:{_Integer,_Integer},spacings_,borderWidths_,options_,data:{__List?MatrixQ}]:=
(*Calculate the max height for each row and max width for each column, and then just call the previous DataGrid function above.*)
With[
{rowHeights=Flatten@BlockMap[Max[Part[#,All,All,1]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{1,dims[[2]]}],
colWidths=Flatten@BlockMap[Max[Part[#,All,All,2]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{dims[[1]],1}]},
DataGrid[rowHeights,colWidths,spacings,borderWidths,options,data]];
(*This could probably be simplified, but I like having all of the aligment options explicit and separate for testability.*)
MatrixAlign[{-1,-1},dims_,pad_]:=PadRight[#,dims,pad]&;
MatrixAlign[{-1,0},dims_,pad_]:=PadRight[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{-1,1},dims_,pad_]:=PadRight[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,-1},dims_,pad_]:=CenterArray[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,0},dims_,pad_]:=CenterArray[#,dims,pad]&;
MatrixAlign[{0,1},dims_,pad_]:=CenterArray[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,-1},dims_,pad_]:=PadLeft[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,0},dims_,pad_]:=PadLeft[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,1},dims_,pad_]:=PadLeft[#,dims,pad]&;
(*While the grid functions make no assumptions about the format of the data, we will be using them with string/character data, and we will eventually want to output a calendar as a single large string. AsString gives us a standard method for transforming a matrix of characters into a string with rows delimited by newlines.*)
AsString[matrix_List?MatrixQ]:=StringRiffle[matrix,"\n",""]; |
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.
| #PureBasic | PureBasic | #Window1 = 0
#Image1 = 0
#ImgGadget = 0
#NUM_PARTICLES = 3000
#width = 200
#height = 200
#xmax = #width -3
#ymax = #height -3
Define.i Event ,i ,x,y
If OpenWindow(#Window1, 0, 0, #width, #height, "Brownian Tree PureBasic Example", #PB_Window_SystemMenu )
If CreateImage(#Image1, #width, #height)
ImageGadget(#ImgGadget, 0, 0, #width, #height, ImageID(#Image1))
StartDrawing(ImageOutput(#Image1))
FrontColor($FFFFFF)
Plot( Random(#xmax) , Random(#ymax ))
StopDrawing()
SetGadgetState(#ImgGadget, ImageID(#Image1))
For i = 1 To #NUM_PARTICLES
x = Random(#xmax)+1 : y = Random (#ymax)+1
StartDrawing(ImageOutput(#Image1))
While Point(x+1, y+1) + Point(x, y+1)+Point(x+1, y)+Point(x-1, y-1)+Point(x-1, y)+Point(x, y-1) = 0
x = x + (Random(2)-1) : y = y + (Random(2)-1)
If x < 1 Or x > #xmax Or y < 1 Or y > #ymax
x = Random(#xmax)+1 : y = Random (#ymax)+1
EndIf
Wend
Plot(x,y)
StopDrawing()
SetGadgetState(#ImgGadget, ImageID(#Image1))
Next
EndIf
Repeat
Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
EndIf |
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
| #Go | Go | package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
// generate pattern
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
// accept and score guesses
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
// malformed: not four characters
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
// malformed: repeated digit
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
// malformed: not a digit
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default: // I just think cows should go first
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
} |
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
| #Erlang | Erlang |
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
-module(ceasar).
-export([main/2]).
%% rot: rotate Char by Key places
rot(Char,Key) when (Char >= $A) and (Char =< $Z) or
(Char >= $a) and (Char =< $z) ->
Offset = $A + Char band 32,
N = Char - Offset,
Offset + (N + Key) rem 26;
rot(Char, _Key) ->
Char.
%% key: normalize key.
key(Key) when Key < 0 ->
26 + Key rem 26;
key(Key) when Key > 25 ->
Key rem 26;
key(Key) ->
Key.
main(PlainText, Key) ->
Encode = key(Key),
Decode = key(-Key),
io:format("Plaintext ----> ~s~n", [PlainText]),
CypherText = lists:map(fun(Char) -> rot(Char, Encode) end, PlainText),
io:format("Cyphertext ---> ~s~n", [CypherText]),
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).
|
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
| #Tcl | Tcl |
set ε 1.0e-15
set fact 1
set e 2.0
set e0 0.0
set n 2
while {[expr abs($e - $e0)] > ${ε}} {
set e0 $e
set fact [expr $fact * $n]
incr n
set e [expr $e + 1.0/$fact]
}
puts "e = $e" |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #TI-83_BASIC | TI-83 BASIC | 0->D
2->N
2->E
1->F
1.0E-12->Z
While abs(E-D)>Z
F*N->F
N+1->N
E->D
E+1/F->E
End
Disp E
|
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.
| #Lambdatalk | Lambdatalk |
The command
replace :a0 :a1 ... an-1
in expression containing some occurences of :ai
by v0 v1 ... vp-1
is rewritten in a prefixed parenthesized form
{{lambda {:a0 :a1 ... an-1}
expression containing some occurences of :ai}
v0 v1 ... vp-1}
so called IIFE (Immediately Invoked Function Expression), and defines an anonymous function containing a sequence of n arguments :ai, immediately invoked on a sequence of p values vi, and returning the expression in its body as so modified:
1) if p < n (partial application)
• the occurrences of the p first arguments are replaced in the function's body by the corresponding p given values,
• a function waiting for missing n-p values is created,
• and its reference is returned.
• example:
{{lambda {:x :y} ... :y ... :x ...} hello}
-> {lambda {:y} ... :y ... hello ...} // replaces :x by hello
-> LAMB_123 // the new functions's reference
• called with the value world this function will return ... world ... hello ...
2) if p = n (normal application)
• the occurences of the n arguments are replaced in the function's body by the corresponding p given values,
• the body is evaluated and the result is returned.
• example
{{lambda {:x :y} ... :y ... :x ...} hello world}
-> {{lambda {:y} ... :y ... hello ...} world} // replaces :x by hello
-> {{lambda {} ... world ... hello ...} } // replaces :y by world
-> ... world ... hello ... // the value
3) if p > n (variadicity)
• the occurrences of the n-1 first arguments are replaced in the function's body by the corresponding n-1 given values,
• the occurrences of the last argument are replaced in the body by the sequence of p-n supernumerary values,
• the body is evaluated and the result is returned.
• example:
{{lambda {:x :y} ... :y ... :x ...} hello world good morning}
-> {{lambda {:y} ... :y ... hello ...} world good morning}
-> {{lambda {} ... world good morning ... hello ...}}
-> ... world good morning ... hello ... // the value
More can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda
|
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
| #Perl | Perl | sub factorial { my $f = 1; $f *= $_ for 2 .. $_[0]; $f; }
sub catalan {
my $n = shift;
factorial(2*$n) / factorial($n+1) / factorial($n);
}
print "$_\t@{[ catalan($_) ]}\n" for 0 .. 20; |
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
| #zkl | zkl | fcn eyeball(code,ps=L(),brace=False){ //-->indexes of valid braces & commas
cs:=L();
foreach c in (code){ // start fresh or continue (if recursing)
switch(c){
case("\\"){ __cWalker.next(); }
case(",") { if(brace) cs.append(__cWalker.n); } // maybe valid
case("{") { // this is real only if there is matching } and a comma
n:=__cWalker.n;
_,cz:=self.fcn(__cWalker,ps,True);
if(cz){ ps.append(n,__cWalker.n); ps.extend(cz) } // valid {} pair
}
case("}"){ if(brace) return(ps,cs); }
}
}
return(ps,False)
}
fcn expando(code,strings=T("")){
reg [const] stack=List(); reg roots,cs; bs,_:=eyeball(code);
foreach c in (code){
if(bs.holds(__cWalker.n)){
if (c=="{") { stack.append(cs); cs=0; roots=strings; }
else if(c==",") { stack.append(strings); strings=roots; cs+=1; }
else if(c=="}") { do(cs){ strings=stack.pop().extend(strings); } cs=stack.pop(); }
}else if(c=="\\"){
c="\\"+__cWalker.next();
strings=strings.apply('+(c));
}
else strings=strings.apply('+(c));
}
strings
} |
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
| #REXX | REXX | /*REXX pgm finds: 1st N Brazilian #s; odd Brazilian #s; prime Brazilian #s; ZZZth #.*/
parse arg t.1 t.2 t.3 t.4 . /*obtain optional arguments from the CL*/
if t.4=='' | t.4=="," then t.4= 0 /*special test case of Nth Brazilian #.*/
hdr.1= 'first'; hdr.2= "first odd"; hdr.3= 'first prime'; hdr.4= /*four headers.*/
#p= 0 /*#P: the number of primes (so far).*/
do c=1 for 4 /*process each of the four cases. */
if t.c=='' | t.c=="," then t.c= 20 /*check if a target is null or a comma.*/
step= 1 + (c==2) /*STEP is set to unity or two (for ODD)*/
if t.c==0 then iterate /*check to see if this case target ≡ 0.*/
$=; #= 0 /*initialize list to null; counter to 0*/
do j=1 by step until #>= t.c /*search integers for Brazilian # type.*/
prime= 0 /*signify if J may not be prime. */
if c==3 then do /*is this a "case 3" calculation? */
if \isPrime(j) then iterate /*(case 3) Not a prime? Then skip it.*/
prime= 1 /*signify if J is definately a prime.*/
end /* [↓] J≡prime will be used for speedup*/
if \isBraz(j, prime) then iterate /*Not Brazilian number? " " " */
#= # + 1 /*bump the counter of Brazilian numbers*/
if c\==4 then $= $ j /*for most cases, append J to ($) list.*/
end /*j*/ /* [↑] cases 1──►3, $ has leading blank*/
say /* [↓] use a special header for cases.*/
if c==4 then do; $= j; t.c= th(t.c); end /*for Nth Brazilian number, just use J.*/
say center(' 'hdr.c" " t.c " Brazilian number"left('s', c\==4)" ", 79, '═')
say strip($) /*display a case result to the terminal*/
end /*c*/ /* [↑] cases 1──►3 have a leading blank*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isBraz: procedure; parse arg x,p; if x<7 then return 0 /*Is # < seven? Nope. */
if x//2==0 then return 1 /*Is # even? Yup. _*/
if p then mx= iSqrt(x) /*X prime? Use integer √X*/
else mx= x%3 -1 /*X not known if prime. */
do b=2 for mx /*scan for base 2 ──► max*/
if sameDig(x, b) then return 1 /*it's a Brazilian number*/
end /*b*/; return 0 /*not " " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure expose @. !. #p; parse arg x '' -1 _ /*get 1st arg & last decimal dig*/
if #p==0 then do; !.=0; y= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
do i=1 for words(y); #p= #p+1; z=word(y,i); @.#p= z; !.z=1; end
end /*#P: is the number of primes. */
if !.x then return 1; if x<61 then return 0; if x//2==0 then return 0
if x//3==0 then return 0; if _==5 then return 0; if x//7==0 then return 0
do j=5 until @.j**2>x; if x//@.j ==0 then return 0
if x//(@.j+2) ==0 then return 0
end /*j*/; #p= #p + 1; @.#p= x; !.x= 1; return 1 /*it's a prime.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x; q= 1; r= 0; do while q<=x; q= q*4; end
do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q;end;end; return r
/*──────────────────────────────────────────────────────────────────────────────────────*/
sameDig: procedure; parse arg x, b; f= x // b /* // ◄── the remainder.*/
x= x % b /* % ◄── is integer ÷ */
do while x>0; if x//b \==f then return 0
x= x % b
end /*while*/; return 1 /*it has all the same dig*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: parse arg th; return th || word('th st nd rd', 1+(th//10)*(th//100%10\==1)*(th//10<4)) |
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
| #Overview | Overview | DataGrid[
rowHeights:{__Integer},
colWidths:{__Integer},
spacings:{_Integer,_Integer},
borderWidths:{{_Integer,_Integer},{_Integer,_Integer}},
options_Association,
data:{__List?MatrixQ}]:=
With[
(*Need to make sure we have sensible defaults for the decoration options.*)
{alignment=Lookup[options,"alignment",{0,0}],
background=Lookup[options,"background"," "],
dividers=Lookup[options,"dividers",{" "," "," "}],
border=Lookup[options,"border"," "],
dims={Length[rowHeights],Length[colWidths]}},
(*Pad the data so that it will fit into the specified rectangle (list of lists).*)
With[{augmentedData=PadRight[data,Times@@dims,{{{background}}}]},
(*Create a matrix of dimensions based on desired rectangle. Once we have a matrix of cells we can "thread" these two matrices and use that data to coerce each cell into its final dimensions.*)
With[{cellDims=ArrayReshape[Outer[List,rowHeights,colWidths],{Times@@dims,2}]},
(*MatrixAlign, defined below, rescales and aligns each cell's data.*)
With[{undecoratedGrid=Partition[MapThread[MatrixAlign[alignment,#1,background][#2]&, {cellDims,augmentedData}],dims[[2]]]},
(*Add the spacing to each row.*)
With[{dividedRows=MapThread[Transpose[Riffle[#2,{ConstantArray[dividers[[2]],{#1,spacings[[2]]}]},{2,-2,2}]]&, {rowHeights,undecoratedGrid}]},
(*Add the spacing between rows.*)
With[{dividedColumn=Riffle[dividedRows,{Transpose[Riffle[ConstantArray[dividers[[1]],{spacings[[1]],#}]&/@colWidths,{ConstantArray[dividers[[3]],spacings]},{2,-2,2}]]},{2,-2,2}]},
(*Assemble all cell rows into actual character rows. We now have one large matrix.*)
With[{dividedGrid=Catenate[Map[Flatten,dividedColumn,{2}]]},
(*Add borders.*)
ArrayPad[dividedGrid,borderWidths,border]]]]]]]];
DataGrid[dims:{_Integer,_Integer},spacings_,borderWidths_,options_,data:{__List?MatrixQ}]:=
(*Calculate the max height for each row and max width for each column, and then just call the previous DataGrid function above.*)
With[
{rowHeights=Flatten@BlockMap[Max[Part[#,All,All,1]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{1,dims[[2]]}],
colWidths=Flatten@BlockMap[Max[Part[#,All,All,2]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{dims[[1]],1}]},
DataGrid[rowHeights,colWidths,spacings,borderWidths,options,data]];
(*This could probably be simplified, but I like having all of the aligment options explicit and separate for testability.*)
MatrixAlign[{-1,-1},dims_,pad_]:=PadRight[#,dims,pad]&;
MatrixAlign[{-1,0},dims_,pad_]:=PadRight[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{-1,1},dims_,pad_]:=PadRight[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,-1},dims_,pad_]:=CenterArray[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,0},dims_,pad_]:=CenterArray[#,dims,pad]&;
MatrixAlign[{0,1},dims_,pad_]:=CenterArray[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,-1},dims_,pad_]:=PadLeft[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,0},dims_,pad_]:=PadLeft[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,1},dims_,pad_]:=PadLeft[#,dims,pad]&;
(*While the grid functions make no assumptions about the format of the data, we will be using them with string/character data, and we will eventually want to output a calendar as a single large string. AsString gives us a standard method for transforming a matrix of characters into a string with rows delimited by newlines.*)
AsString[matrix_List?MatrixQ]:=StringRiffle[matrix,"\n",""]; |
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.
| #Python | Python | import pygame, sys, os
from pygame.locals import *
from random import randint
pygame.init()
MAXSPEED = 15
SIZE = 3
COLOR = (45, 90, 45)
WINDOWSIZE = 400
TIMETICK = 1
MAXPART = 50
freeParticles = pygame.sprite.Group()
tree = pygame.sprite.Group()
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Brownian Tree")
screen = pygame.display.get_surface()
class Particle(pygame.sprite.Sprite):
def __init__(self, vector, location, surface):
pygame.sprite.Sprite.__init__(self)
self.vector = vector
self.surface = surface
self.accelerate(vector)
self.add(freeParticles)
self.rect = pygame.Rect(location[0], location[1], SIZE, SIZE)
self.surface.fill(COLOR, self.rect)
def onEdge(self):
if self.rect.left <= 0:
self.vector = (abs(self.vector[0]), self.vector[1])
elif self.rect.top <= 0:
self.vector = (self.vector[0], abs(self.vector[1]))
elif self.rect.right >= WINDOWSIZE:
self.vector = (-abs(self.vector[0]), self.vector[1])
elif self.rect.bottom >= WINDOWSIZE:
self.vector = (self.vector[0], -abs(self.vector[1]))
def update(self):
if freeParticles in self.groups():
self.surface.fill((0,0,0), self.rect)
self.remove(freeParticles)
if pygame.sprite.spritecollideany(self, freeParticles):
self.accelerate((randint(-MAXSPEED, MAXSPEED),
randint(-MAXSPEED, MAXSPEED)))
self.add(freeParticles)
elif pygame.sprite.spritecollideany(self, tree):
self.stop()
else:
self.add(freeParticles)
self.onEdge()
if (self.vector == (0,0)) and tree not in self.groups():
self.accelerate((randint(-MAXSPEED, MAXSPEED),
randint(-MAXSPEED, MAXSPEED)))
self.rect.move_ip(self.vector[0], self.vector[1])
self.surface.fill(COLOR, self.rect)
def stop(self):
self.vector = (0,0)
self.remove(freeParticles)
self.add(tree)
def accelerate(self, vector):
self.vector = vector
NEW = USEREVENT + 1
TICK = USEREVENT + 2
pygame.time.set_timer(NEW, 50)
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == NEW and (len(freeParticles) < MAXPART):
Particle((randint(-MAXSPEED,MAXSPEED),
randint(-MAXSPEED,MAXSPEED)),
(randint(0, WINDOWSIZE), randint(0, WINDOWSIZE)),
screen)
elif event.type == TICK:
freeParticles.update()
half = WINDOWSIZE/2
tenth = WINDOWSIZE/10
root = Particle((0,0),
(randint(half-tenth, half+tenth),
randint(half-tenth, half+tenth)), screen)
root.stop()
while True:
input(pygame.event.get())
pygame.display.flip() |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.