task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Call_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.
| #Fortran | Fortran | program main
implicit none
integer :: a
integer :: f, g
logical :: lresult
interface
integer function h(a,b,c)
integer :: a, b
integer, optional :: c
end function
end interface
write(*,*) 'no arguments: ', f()
write(*,*) '-----------------'
write(*,*) 'fixed arguments: ', g(5,8,lresult)
write(*,*) '-----------------'
write(*,*) 'optional arguments: ', h(5,8), h(5,8,4)
write(*,*) '-----------------'
write(*,*) 'function with variable arguments: Does not apply!'
write(*,*) 'An option is to pass arrays of variable lengths.'
write(*,*) '-----------------'
write(*,*) 'named arguments: ', h(c=4,b=8,a=5)
write(*,*) '-----------------'
write(*,*) 'function in statement context: Does not apply!'
write(*,*) '-----------------'
write(*,*) 'Fortran passes memory location of variables as arguments.'
write(*,*) 'So an argument can hold the return value.'
write(*,*) 'function result: ', g(5,8,lresult) , ' function successful? ', lresult
write(*,*) '-----------------'
write(*,*) 'Distinguish between built-in and user-defined functions: Does not apply!'
write(*,*) '-----------------'
write(*,*) 'Calling a subroutine: '
a = 30
call sub(a)
write(*,*) 'Function call: ', f()
write(*,*) '-----------------'
write(*,*) 'All variables are passed as pointers.'
write(*,*) 'Problems can arise if instead of sub(a), one uses sub(10).'
write(*,*) '-----------------'
end program
!no argument
integer function f()
f = 10
end function
!fixed number of arguments
integer function g(a, b, lresult)
integer :: a, b
logical :: lresult
g = a+b
lresult = .TRUE.
end function
!optional arguments
integer function h(a, b, c)
integer :: a, b
integer, optional :: c
h = a+b
if(present(c)) then
h = h+10*c
end if
end function
!subroutine
subroutine sub(a)
integer :: a
a = a*100
write(*,*) 'Output of subroutine: ', a
end subroutine
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #VBA | VBA | Public Sub reduce()
s = [{1,2,3,4,5}]
Debug.Print WorksheetFunction.Sum(s)
Debug.Print WorksheetFunction.Product(s)
End Sub |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Vlang | Vlang | vfn main() {
n := [1, 2, 3, 4, 5]
println(reduce(add, n))
println(reduce(sub, n))
println(reduce(mul, n))
}
fn add(a int, b int) int { return a + b }
fn sub(a int, b int) int { return a - b }
fn mul(a int, b int) int { return a * b }
fn reduce(rf fn(int, int) int, m []int) int {
mut r := m[0]
for v in m[1..] {
r = rf(r, v)
}
return r
} |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #zkl | zkl | zkl: Walker.cproduct(List(1,2),List(3,4)).walk().println();
L(L(1,3),L(1,4),L(2,3),L(2,4))
zkl: foreach a,b in (List(1,2),List(3,4)){ print("(%d,%d) ".fmt(a,b)) }
(1,3) (1,4) (2,3) (2,4)
zkl: Walker.cproduct(List(3,4),List(1,2)).walk().println();
L(L(3,1),L(3,2),L(4,1),L(4,2)) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{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
| #langur | langur | val .factorial = f if(.x < 2: 1; .x x self(.x - 1))
val .catalan = f(.n) .factorial(2 x .n) / .factorial(.n+1) / .factorial(.n)
for .i in 0..15 {
writeln $"\.i:2;: \(.catalan(.i):10)"
}
writeln "10000: ", .catalan(10000) |
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
| #PHP | PHP | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
} |
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
| #Haskell | Haskell | import Data.Numbers.Primes (primes)
isBrazil :: Int -> Bool
isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])
monoDigit :: Int -> Int -> Bool
monoDigit n b =
let (q, d) = quotRem n b
in d ==
snd
(until
(uncurry (flip ((||) . (d /=)) . (0 ==)))
((`quotRem` b) . fst)
(q, d))
main :: IO ()
main =
mapM_
(\(s, xs) ->
(putStrLn . concat)
[ "First 20 "
, s
, " Brazilians:\n"
, show . take 20 $ filter isBrazil xs
, "\n"
])
[([], [1 ..]), ("odd", [1,3 ..]), ("prime", primes)] |
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
| #FutureBasic | FutureBasic | window 1, @"Calendar", (0, 0, 520, 520 )
Str255 a
open "UNIX", 1,"cal 1969"
do
line input #1, a
print a
until eof(1)
close 1
HandleEvents |
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.
| #JavaScript | JavaScript | function brownian(canvasId, messageId) {
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d");
// Options
var drawPos = true;
var seedResolution = 50;
var clearShade = 0; // 0..255
// Static state
var width = canvas.width;
var height = canvas.height;
var cx = width/2;
var cy = height/2;
var clearStyle = "rgba("+clearShade+", "+clearShade+", "+clearShade+", 1)";
// Utilities
function radius(x,y) {
return Math.sqrt((x-cx)*(x-cy)+(y-cx)*(y-cy));
}
function test(x, y) {
if (x < 0 || y < 0 || x >= width || y >= height)
return false;
var data = ctx.getImageData(x, y, 1, 1).data;
return data[0] != clearShade || data[1] != clearShade || data[2] != clearShade;
}
var shade = 120;
function setc(x, y, c) {
//var imgd = ctx.createImageData(1, 1);
//var pix = imgd.data;
//pix[0] = pix[1] = pix[2] = c == 255 ? 255 : shade;
//pix[3] = 255;
//shade = (shade + 1) % 254;
//ctx.putImageData(imgd, x, y);
//ctx.fillStyle = "rgba("+c+", "+c+", "+c+", 1)";
shade = (shade + 0.02) % 360;
if (c) {
ctx.fillStyle = "hsl("+shade+", 100%, 50%)";
} else {
ctx.fillStyle = clearStyle;
}
ctx.fillRect (x, y, 1, 1);
}
function set(x,y) {
setc(x,y,true);
}
function clear(x,y) {
setc(x,y,false);
}
// Initialize canvas to blank opaque
ctx.fillStyle = clearStyle;
ctx.fillRect (0, 0, width, height);
// Current position
var x;
var y;
// Farthest distance from center a particle has yet been placed.
var closeRadius = 1;
// Place seed
set(cx, cy);
// Choose a new random position for a particle (not necessarily unoccupied)
function newpos() {
// Wherever particles are injected, the tree will tend to grow faster
// toward it. Ideally, particles wander in from infinity; the best we
// could do is to have them wander in from the edge of the field.
// But in order to have the rendering occur in a reasonable time when
// the seed is small, without too much visible bias, we instead place
// the particles in a coarse grid. The final tree will cover every
// point on the grid.
//
// There's probably a better strategy than this.
x = Math.floor(Math.random()*(width/seedResolution))*seedResolution;
y = Math.floor(Math.random()*(height/seedResolution))*seedResolution;
}
newpos();
var animation;
animation = window.setInterval(function () {
if (drawPos) clear(x,y);
for (var i = 0; i < 10000; i++) {
var ox = x;
var oy = y;
// Changing this to use only the first four directions will result
// in a denser tree.
switch (Math.floor(Math.random()*8)) {
case 0: x++; break;
case 1: x--; break;
case 2: y++; break;
case 3: y--; break;
case 4: x++; y++; break;
case 5: x--; y++; break;
case 6: x++; y--; break;
case 7: x--; y--; break;
}
if (x < 0 || y < 0 ||
x >= width || y >= height ||
radius(x,y) > closeRadius+seedResolution+2) {
// wandered out of bounds or out of interesting range of the
// tree, so pick a new spot
var progress = 1000;
do {
newpos();
progress--;
} while ((test(x-1,y-1) || test(x,y-1) || test(x+1,y-1) ||
test(x-1,y ) || test(x,y ) || test(x+1,y ) ||
test(x-1,y+1) || test(x,y+1) || test(x+1,y+1)) && progress > 0);
if (progress <= 0) {
document.getElementById(messageId).appendChild(
document.createTextNode("Stopped for lack of room."));
clearInterval(animation);
break;
}
}
if (test(x, y)) {
// hit something, mark where we came from and pick a new spot
set(ox,oy);
closeRadius = Math.max(closeRadius, radius(ox,oy));
newpos();
}
}
if (drawPos) set(x,y);
}, 1);
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #E | E | def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]
/** Choose a random number to be guessed. */
def pick4(entropy) {
def digits := [1,2,3,4,5,6,7,8,9].diverge()
# Partial Fisher-Yates shuffle
for i in 0..!4 {
def other := entropy.nextInt(digits.size() - i) + i
def t := digits[other]
digits[other] := digits[i]
digits[i] := t
}
return digits(0, 4)
}
/** Compute the score of a guess. */
def scoreGuess(actual :Number, guess :Number) {
var bulls := 0
var cows := 0
for i => digit in guess {
if (digit == actual[i]) {
bulls += 1
} else if (actual.indexOf1(digit) != -1) {
cows += 1
}
}
return [bulls, cows]
}
/** Parse a guess string into a list of digits (Number). */
def parseGuess(guessString, fail) :Number {
if (guessString.size() != 4) {
return fail(`I need four digits, not ${guessString.size()} digits.`)
} else {
var digits := []
for c in guessString {
if (('1'..'9')(c)) {
digits with= c - '0'
} else {
return fail(`I need a digit from 1 to 9, not "$c".`)
}
}
return digits
}
}
/** The game loop: asking for guesses and reporting scores and win conditions.
The return value is null or a broken reference if there was a problem. */
def bullsAndCows(askUserForGuess, tellUser, entropy) {
def actual := pick4(entropy)
def gameTurn() {
return when (def guessString := askUserForGuess <- ()) -> {
escape tellAndContinue {
def guess := parseGuess(guessString, tellAndContinue)
def [bulls, cows] := scoreGuess(actual, guess)
if (bulls == 4) {
tellUser <- (`You got it! The number is $actual!`)
null
} else {
tellAndContinue(`Your score for $guessString is $bulls bulls and $cows cows.`)
}
} catch message {
# The parser or scorer has something to say, and the game continues afterward
when (tellUser <- (message)) -> {
gameTurn()
}
}
} catch p {
# Unexpected problem of some sort
tellUser <- ("Sorry, game crashed.")
throw(p)
}
}
return gameTurn()
} |
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
| #COBOL | COBOL |
identification division.
program-id. caesar.
data division.
1 msg pic x(50)
value "The quick brown fox jumped over the lazy dog.".
1 offset binary pic 9(4) value 7.
1 from-chars pic x(52).
1 to-chars pic x(52).
1 tabl.
2 pic x(26) value "abcdefghijklmnopqrstuvwxyz".
2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
2 pic x(26) value "abcdefghijklmnopqrstuvwxyz".
2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
procedure division.
begin.
display msg
perform encrypt
display msg
perform decrypt
display msg
stop run
.
encrypt.
move tabl (1:52) to from-chars
move tabl (1 + offset:52) to to-chars
inspect msg converting from-chars
to to-chars
.
decrypt.
move tabl (1 + offset:52) to from-chars
move tabl (1:52) to to-chars
inspect msg converting from-chars
to to-chars
.
end program caesar.
|
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
| #Myrddin | Myrddin | use std
const main = {
var f: uint64 = 1
var e: flt64 = 2.0
var e0: flt64 = 0.0
var n = 2
while e > e0
e0 = e
f *= n
e += 1.0 / (f : flt64)
n++
;;
std.put("e: {}\n", 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
| #Nanoquery | Nanoquery | e0 = 0
e = 2
n = 0
fact = 1
while (e - e0) > 10^-15
e0 = e
n += 1
fact *= 2*n*((2*n)+1)
e += ((2.0*n)+2)/fact
end
println "Computed e = " + e
println "Number of iterations = " + n |
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)
| #Raku | Raku | # we use the [] reduction meta operator along with the Cartesian Product
# operator X to create the Cartesian Product of four times [1..9] and then get
# all the elements where the number of unique digits is four.
my @candidates = ([X] [1..9] xx 4).grep: *.unique == 4;
repeat {
my $guess = @candidates.pick;
my ($bulls, $cows) = read-score;
@candidates .= grep: &score-correct;
# note how we declare our two subroutines within the repeat block. This
# limits the scope in which the routines are known to the scope in which
# they are needed and saves us a lot of arguments to our two routines.
sub score-correct($a) {
my $exact = [+] $a >>==<< $guess;
# number of elements of $a that match any element of $b
my $loose = +$a.grep: any @$guess;
return $bulls == $exact && $cows == $loose - $exact;
}
sub read-score() {
loop {
my $score = prompt "My guess: {$guess.join}.\n";
if $score ~~ m:s/^ $<bulls>=(\d) $<cows>=(\d) $/
and $<bulls> + $<cows> <= 4 {
return +$<bulls>, +$<cows>;
}
say "Please specify the number of bulls and cows";
}
}
} while @candidates > 1;
say @candidates
?? "Your secret number is {@candidates[0].join}!"
!! "I think you made a mistake with your scoring."; |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Sidef | Sidef | -> DT { ('DATE'.("\LWC") + 'TIME'.("\LWC")).("\LREQUIRE") }
-> MONTHS_PER_COL { 6 }
-> WEEK_DAY_NAMES { <MO TU WE TH FR SA SU> }
-> MONTH_NAMES { <JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC> }
-> FMT_MONTH (YEAR, MONTH, STR="", WEEK_DAY=0) {
STR = "%11\LS\E%9\LS\E\12".("\LSPRINTF")(MONTH_NAMES()[MONTH-1],'')
STR += (WEEK_DAY_NAMES().("\LJOIN")(' ') + "\12")
-> DATE { DT().("\LNEW")("\LYEAR" => YEAR, "\LMONTH" => MONTH) }
WEEK_DAY = DATE().("\LDAY_OF_WEEK")
STR += ([" "] * WEEK_DAY-1 -> ("\LJOIN")(" "))
-> LAST_DAY {
DT().("\LLAST_DAY_OF_MONTH")(
"\LYEAR" => YEAR, "\LMONTH" => MONTH
).("\LDAY")
}
(DATE().("\LDAY") .. LAST_DAY()).("\LEACH")({ |DAY|
(WEEK_DAY ~~ (2..7)) && (STR += " ")
(WEEK_DAY == 8) && (
STR += "\12"
WEEK_DAY = 1
)
STR += ("%2\LD" % DAY)
++WEEK_DAY
})
(WEEK_DAY < 8) && (STR += " ")
STR += ([" "] * 8-WEEK_DAY -> ("\LJOIN")(" "))
STR += "\12"
}
-> FMT_YEAR (YEAR, STR="", MONTH_STRS=[]) {
MONTH_STRS = 12.("\LOF")({|I| FMT_MONTH(YEAR, I+1).("\LLINES") })
STR += (' '*(MONTHS_PER_COL()*10 + 2) + YEAR + "\12")
(0..11 -> ("\LBY")(MONTHS_PER_COL())).("\LEACH")({ |MONTH|
MONTH_STRS[MONTH] && ->() {
{ |I|
MONTH_STRS[MONTH + I] && (
STR += MONTH_STRS[MONTH + I].("\LSHIFT")
STR += ' '*2
)
} * MONTHS_PER_COL()
STR += "\12"
MONTH_STRS[MONTH] && __FUNC__()
}()
STR += "\12"
})
STR
}
FMT_YEAR(ARGV ? ARGV[0].("\LTO_I") : 1969).("\LPRINT") |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #X86-64_Assembly | X86-64 Assembly |
option casemap:none
strdup proto :qword
printf proto :qword, :vararg
exit proto :dword
.data
bstr db "String 1",0
.data?
buff dq ?
.code
main proc
invoke printf, CSTR("Copying %s to buff with strdup using invoke....",10), addr bstr
invoke strdup, addr bstr
mov buff, rax
invoke printf, CSTR("buff now = %s",10), buff
invoke exit, 0
ret
main endp
end
;Now, we could target a specific ABI by assigning the call values to the registers like
;.code
;main proc
; lea rdi, bstr
; call strdup
; mov buff, rax
;main endp
;end
|
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Zig | Zig | const std = @import("std");
const c = @cImport({
@cInclude("stdlib.h"); // `free`
@cInclude("string.h"); // `strdup`
});
pub fn main() !void {
const string = "Hello World!";
var copy = c.strdup(string);
try std.io.getStdOut().writer().print("{s}\n", .{copy});
c.free(copy);
} |
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.
| #Fortress | Fortress |
component call_a_function
export Executable
(* Declaring test functions that allow the various ways to call functions in Fortress to be demonstrated. *)
addition(i:ZZ32, j:ZZ32): ZZ32 = i+j
addition(i:ZZ32): ZZ32 = i+1
(* Strings are concatenated by using a space as an infix operator. *)
addition(i:String, j:String): String = i j
printAString(s:String): () = println(s)
(* Functions can be passed to other functions as arguments. When passing a function as an argument, the argument's type should be
represented as follows: "typeOfArgument(s)->returnType," which, in this case, is "String->()." You could also technically use the
"Any" type, but that isn't type-safe. *)
printAString(s:String, f:String->()) = f(s)
(* Defined functions can then be called as follows. *)
var x:ZZ32 = addition(1, 2)
var str:String = addition("This is ", "another string.")
run() = do
(* You can call built-in functions the same way that you call functions that you define. *)
println("x at start: " x)
x := addition(x, 2)
println("x at middle: " x)
printAString("This " "is " "a " "string.")
printAString(str)
printAString("\nThis is a string that is being printed by a function of the same name \nthat takes a function as an argument.\n",
printAString)
x := addition(4)
println("x at end: " x)
end
end
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
let str => import 'strings';
# Sum of [1, 10]:
let nums => [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];
a.stream nums -> s.reduce 0 + -- io.writeln io.stdout;
# As an alternative to an array, a range stream can be used. Here's the product of [1, 11):
s.range 1 11 -> s.reduce 1 * -- io.writeln io.stdout;
# And here's a concatenation:
s.range 1 11 -> s.reduce '' (str.format '{}{}') -- io.writeln io.stdout; |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Wortel | Wortel | !/ ^+ [1 2 3] ; returns 6 |
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
| #Liberty_BASIC | Liberty BASIC | print "non-recursive version"
print catNonRec(5)
for i = 0 to 15
print i;" = "; catNonRec(i)
next
print
print "recursive version"
print catRec(5)
for i = 0 to 15
print i;" = "; catRec(i)
next
print
print "recursive with memoisation"
redim cats(20) 'clear the array
print catRecMemo(5)
for i = 0 to 15
print i;" = "; catRecMemo(i)
next
print
wait
function catNonRec(n) 'non-recursive version
catNonRec=1
for i=1 to n
catNonRec=((2*((2*i)-1))/(i+1))*catNonRec
next
end function
function catRec(n) 'recursive version
if n=0 then
catRec=1
else
catRec=((2*((2*n)-1))/(n+1))*catRec(n-1)
end if
end function
function catRecMemo(n) 'recursive version with memoisation
if n=0 then
catRecMemo=1
else
if cats(n-1)=0 then 'call it recursively only if not already calculated
prev = catRecMemo(n-1)
else
prev = cats(n-1)
end if
catRecMemo=((2*((2*n)-1))/(n+1))*prev
end if
cats(n) = catRecMemo 'memoisation for future use
end function |
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
| #PicoLisp | PicoLisp | (de braceExpand (Str)
(let Lst
(make
(for (Lst (chop Str) Lst)
(case (pop 'Lst)
("\\" (link (pop 'Lst)))
("{"
(recur ()
(let L
(make
(while
(case (pop 'Lst)
("\\" (link (pop 'Lst)) Lst)
("{" (recurse) Lst)
("}" NIL)
("," (link 0) Lst) # Replace commata with '0'
(T (link @) Lst) ) ) )
(if (= "}" @) # Was closing brace
(if (member 0 L) # Has comma(ta)
(link (split L 0))
(chain (list "{") (replace L 0 ",") (list "}")))
(chain (list "{") (replace L 0 ",")) ) ) ) )
(T (link @)) ) ) )
(recur (Lst)
(ifn (find pair Lst)
(list (pack Lst))
(let R (recurse (cdr Lst))
(mapcan
'((A) (mapcar '((B) (pack A B)) R))
(if (pair (car Lst))
(mapcan recurse (car Lst))
(list (car Lst)) ) ) ) ) ) ) ) |
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
| #Isabelle | Isabelle | theory Brazilian
imports Main
begin
function (sequential) base :: "nat ⇒ nat ⇒ nat list" where
"base n 0 = undefined"
| "base n (Suc 0) = replicate n 1"
| "base n b = (if n < b then [n]
else (base (n div b) b) @ [n mod b]
)"
by pat_completeness auto
termination base
apply(relation "measure (λ(n,b). n div b)", simp)
using div_greater_zero_iff by auto
lemma base_simps:
"b > 1 ⟹ base n b = (if n < b then [n] else base (n div b) b @ [n mod b])"
by (metis One_nat_def base.elims nat_neq_iff not_less_zero)
lemma "base 123 10 = [1, 2, 3]"
and "base 65536 2 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
and "base 65535 2 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]"
and "base 123 100 = [1, 23]"
and "base 69 100 = [69]"
and "base 255 16 = [15, 15]"
by(simp add: base_simps)+
lemma "base 5 1 = [1, 1, 1, 1, 1]"
by (simp add: eval_nat_numeral(3) numeral_Bit0)
lemma base_2_numbers: "a < b ⟹ c < b ⟹ a > 0 ⟹ base (a * b + c) b = [a, c]"
apply(simp add: base_simps)
using mult_eq_if by auto
lemma base_half_minus_one: "even n ⟹ n ≥ 8 ⟹ base n (n div 2 - 1) = [2, 2]"
proof -
assume "even n" and "n ≥ 8"
have n: "(2 * (n div 2 - 1) + 2) = n"
using ‹n ≥ 8› ‹even n› add.commute dvd_mult_div_cancel le_0_eq by auto
from ‹n ≥ 8› base_2_numbers[where b="n div 2 - 1" and a=2 and c=2] have
"base (2 * (n div 2 - 1) + 2) (n div 2 - 1) = [2, 2]" by simp
with n show ?thesis by simp
qed
lemma base_rs_numbers: "r > 0 ⟹ s - 1 > r ⟹ base (r*s) (s - 1) = [r, r]"
proof -
assume "r > 0" and "s - 1 > r"
from ‹s - 1 > r› have "r*s = r*(s - 1) + r"
by (metis add.commute gr_implies_not0 less_diff_conv mult.commute mult_eq_if)
from base_2_numbers[where a=r and b="s - 1" and c=r] have
"s - 1 > r ⟹ 0 < r ⟹ base (r * (s - 1) + r) (s - 1) = [r, r]" .
with ‹s - 1 > r› ‹r > 0› have "base (r * (s - 1) + r) (s - 1) = [r, r]" by(simp)
with ‹r * s = r * (s - 1) + r› show "base (r*s) (s - 1) = [r, r]" by (simp)
qed
definition all_equal :: "nat list ⇒ bool" where
"all_equal xs ≡ ∀x∈set xs. ∀y∈set xs. x = y"
lemma all_equal_alt:
"all_equal xs ⟷ replicate (length xs) (hd xs) = xs"
unfolding all_equal_def
apply(induction xs)
apply(simp)
apply(simp)
by (metis in_set_replicate replicate_eqI)
definition brazilian :: "nat set" where
"brazilian ≡ {n. ∃b. 1 < b ∧ Suc b < n ∧ all_equal (base n b)}"
lemma "0 ∉ brazilian"
and "1 ∉ brazilian"
and "2 ∉ brazilian"
and "3 ∉ brazilian"
by (simp add: brazilian_def)+
lemma "4 ∉ brazilian"
apply (simp add: brazilian_def all_equal_def)
apply(intro allI impI)
apply(case_tac "b = 1", simp)
apply(case_tac "b = 2", simp add: base_simps, blast)
by(simp)
lemma "5 ∉ brazilian"
apply (simp add: brazilian_def all_equal_def)
apply(intro allI impI)
apply(case_tac "b = 1", simp)
apply(case_tac "b = 2", simp add: base_simps, blast)
apply(case_tac "b = 3", simp add: base_simps, blast)
by(simp)
lemma "6 ∉ brazilian"
apply (simp add: brazilian_def all_equal_def)
apply(intro allI impI)
apply(case_tac "b = 1", simp)
apply(case_tac "b = 2", simp add: base_simps, blast)
apply(case_tac "b = 3", simp add: base_simps, blast)
apply(case_tac "b = 4", simp add: base_simps, blast)
by(simp)
lemma "7 ∈ brazilian"
apply(simp add: brazilian_def)
apply(rule exI[where x=2])
by(simp add: base_simps all_equal_def)
lemma "8 ∈ brazilian"
apply(simp add: brazilian_def)
apply(rule exI[where x=3])
by(simp add: base_simps all_equal_def)
lemma "9 ∉ brazilian"
apply (simp add: brazilian_def all_equal_def)
apply(intro allI impI)
apply(case_tac "b = 1", simp)
apply(case_tac "b = 2", simp add: base_simps, blast)
apply(case_tac "b = 3", simp add: base_simps, blast)
apply(case_tac "b = 4", simp add: base_simps, blast)
apply(case_tac "b = 5", simp add: base_simps, blast)
apply(case_tac "b = 6", simp add: base_simps, blast)
apply(case_tac "b = 7", simp add: base_simps, blast)
by(simp)
theorem "even n ⟹ n ≥ 8 ⟹ n ∈ brazilian"
apply(simp add: brazilian_def)
apply(rule_tac x="n div 2 - 1" in exI)
by(simp add: base_half_minus_one[simplified] all_equal_def)
(*
The problem description on Rosettacode was broken.
Fortunately, we found the error when proving it correct with Isabelle.
Rosettacode claimed:
"all integers, that factor decomposition is R*S >= 8, with S+1 > R,
are Brazilian because R*S = R(S-1) + R, which is RR in base S-1"
This is wrong. Here are some counterexamples:
r = 3
s = 3
r*s = 9 ≥ 8
s+1 = 4 > 3 = r
But (s*r) = 9 ∉ brazilian
The correct precondition would be s-1>r instead of s+1>r.
But this is not enough.
Also, r > 1 is needed additionally, because
r=1
s=9
r*s = 9 ≥ 8
s+1 = 10 > 1 = r or s-1 = 8 > 1 = r
But (s*r) = 9 ∉ brazilian
Doing the proof, we also learn that the precondition r*s ≥ 8 is not required.
*)
theorem "r > 1 ⟹ s-1 > r ⟹ r*s ∈ brazilian"
apply(simp add: brazilian_def)
apply(rule_tac x="s - 1" in exI)
apply(subst base_rs_numbers[of r s])
using not_numeral_le_zero apply fastforce
apply(simp; fail)
by(simp add: all_equal_def)
fun is_brazilian_for_base :: "nat ⇒ nat ⇒ bool" where
"is_brazilian_for_base n 0 ⟷ False"
| "is_brazilian_for_base n (Suc 0) ⟷ False"
| "is_brazilian_for_base n (Suc b) ⟷ all_equal (base n (Suc b)) ∨ is_brazilian_for_base n b"
lemma "is_brazilian_for_base 7 2" and "is_brazilian_for_base 8 3" by code_simp+
lemma is_brazilian_for_base_Suc_simps:
"is_brazilian_for_base n (Suc b) ⟷ b ≠ 0 ∧ (all_equal (base n (Suc b)) ∨ is_brazilian_for_base n b)"
by(cases b)(simp)+
lemma is_brazilian_for_base:
"is_brazilian_for_base n b ⟷ (∃w ∈ {2..b}. all_equal (base n w))"
proof(induction b)
case 0
show "is_brazilian_for_base n 0 = (∃w∈{2..0}. all_equal (base n w))" by simp
next
case (Suc b)
assume IH: "is_brazilian_for_base n b = (∃w∈{2..b}. all_equal (base n w))"
show "is_brazilian_for_base n (Suc b) = (∃w∈{2..Suc b}. all_equal (base n w))"
apply(simp add: is_brazilian_for_base_Suc_simps IH)
using le_Suc_eq by fastforce
qed
lemma is_brazilian_for_base_is:
"Suc (Suc n) ∈ brazilian ⟷ is_brazilian_for_base (Suc (Suc n)) n"
apply(simp add: brazilian_def is_brazilian_for_base)
using less_Suc_eq_le by force
definition brazilian_executable :: "nat ⇒ bool" where
"brazilian_executable n ≡ n > 1 ∧ is_brazilian_for_base n (n - 2)"
lemma brazilian_executable[code_unfold]:
"n ∈ brazilian ⟷ brazilian_executable n"
apply(simp add: brazilian_executable_def)
apply(cases "n = 0 ∨ n = 1")
apply(simp add: brazilian_def)
apply(blast)
apply(simp)
apply(case_tac n, simp, simp, rename_tac n2)
apply(case_tac n2, simp, simp, rename_tac n3)
apply(subst is_brazilian_for_base_is[symmetric])
apply(simp)
done
text‹
In Isabelle/HOl, functions must be total, i.e. they must terminate.
Therefore, we cannot simply write a function which enumerates the infinite
set of natural numbers and stops when we found 20 Brazilian numbers,
since it is not guaranteed that 20 Brazilian numbers exist and that the
function will terminate.
We could prove that and then write that function, but here is the lazy solution:
›
lemma "[n ← upt 0 34. n ∈ brazilian] =
[7,8,10,12,13,14,15,16,18,20,21,22,24,26,27,28,30,31,32,33]"
by(code_simp)
lemma "[n ← upt 0 80. odd n ∧ n ∈ brazilian] =
[7,13,15,21,27,31,33,35,39,43,45,51,55,57,63,65,69,73,75,77]"
by code_simp
(*TODO: the first 20 prime Brazilian numbers*)
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
| #Gambas | Gambas | Public Sub Main()
Shell "cal 1969"
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.
| #Julia | Julia | using Images, FileIO
function main(h::Integer, w::Integer, side::Bool=false)
W0 = w >> 1
H0 = h >> 1
@inline function motecolor(x::Integer, y::Integer)
h = clamp(180 * (atan2(y - H0, x - W0) / π + 1.0), 0.0, 360.0)
return HSV(h, 0.5, 0.5)
end
img = zeros(RGB{N0f8}, h, w)
img[H0, W0] = RGB(1, 1, 1)
free = trues(h, w)
free[H0, W0] = false
for i in eachindex(img)
x = rand(1:h)
y = rand(1:w)
free[x, y] || continue
mc = motecolor(x, y)
for j in 1:1000
xp = x + rand(-1:1)
yp = y + rand(-1:1)
contained = checkbounds(Bool, img, xp, yp)
if contained && free[xp, yp]
x, y = xp, yp
continue
else
if side || (contained && !free[xp, yp])
free[x, y] = false
img[x, y] = mc
end
break
end
end
end
return img
end
imgnoside = main(256, 256)
imgwtside = main(256, 256, true)
save("data/browniantree_noside.jpg", imgnoside)
save("data/browniantree_wtside.jpg", imgwtside) |
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
| #EasyLang | EasyLang | dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
h = i + random (9 - i)
swap dig[i] dig[h]
.
# print dig[]
len g[] 4
attempts = 0
repeat
repeat
ok = 0
s$[] = strchars input
if len s$[] = 4
ok = 1
for i range 4
g[i] = number s$[i]
if g[i] = 0
ok = 0
.
.
.
until ok = 1
.
print g[]
attempts += 1
bulls = 0
cows = 0
for i range 4
if g[i] = dig[i]
bulls += 1
else
for j range 4
if dig[j] = g[i]
cows += 1
.
.
.
.
print "bulls:" & bulls & " cows:" & cows
until bulls = 4
.
print "Well done! " & attempts & " attempts needed." |
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
| #CoffeeScript | CoffeeScript | cipher = (msg, rot) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
String.fromCharCode \
if c >= 97
then (c + rot + 26 - 97) % 26 + 97
else (c + rot + 26 - 65) % 26 + 65
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3 |
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
| #Nim | Nim | const epsilon : float64 = 1.0e-15
var fact : int64 = 1
var e : float64 = 2.0
var e0 : float64 = 0.0
var n : int64 = 2
while abs(e - e0) >= epsilon:
e0 = e
fact = fact * n
inc(n)
e = e + 1.0 / fact.float64
echo 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
| #Pascal | Pascal | program Calculating_the_value_of_e;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils;
const
EPSILON = 1.0e-14;
function Get_E: Extended;
var
recfact: Extended;
n: Integer;
begin
recfact := 1.0;
Result := 2.0;
n := 2;
repeat
recfact /= n;
inc(n);
Result := Result + recfact;
until (recfact < EPSILON);
end;
begin
writeln(format('calc e = %.15f intern e= %.15f', [Get_E,exp(1.0)]));
{$IFDEF WINDOWS}readln;{$ENDIF}
end.
|
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)
| #Red | Red | Red []
digits: charset [#"1" - #"9"] ;; bitset for parse rule in valid function
check: function [s i ][ ;; returns string with bulls -B and cows - C found
return sort append copy "" collect [
repeat pos 4 [ either ( v: pick i pos ) = pick s pos [ keep "B"][ if find s v [keep "C"] ] ]
]
]
valid: function [ i] [ all [ parse i [4 digits] "," 4 = length? unique i ] ] ;; check if number/string is valid
;; collect all possible permutations
possible: collect [ repeat i 9876 [ if valid s: to-string i [ keep s ] ] ] ;; should start at 1234, but for sake of brevity...
forever [ ;; read valid secret number from keyboard...
while [ not valid secret: ask "^/Enter Number with 4 uniq digits (1 - 9 only, q-quit ) " ] [ ;; "^/" is character for newline
either secret = "q" [print "Bye" halt ] [ print [ secret "invalid, Try again !" ] ]
]
results: copy #() ;; map (key-value ) to store each guess and its result
foreach guess possible [
foreach [k v] body-of results [ ;; check guess against previous results
if v <> check guess k [ guess: copy "" break ]
]
if empty? guess [ continue ] ;; check against previous results failed ?
put results guess res: check guess secret ;; store current guess and result in map
if res = "BBBB" [break] ;; number found ? then break foreach loop
]
foreach [k v] body-of results [ print [k "-" v]] ;; display all guesses and their results
print [CR "Found *" last k: keys-of results "* in " length? k " attempts" CR] ;; cr - constant for newline / carriage return
] ;; forever loop
|
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.
| #Tcl | Tcl |
\146\157\162\145\141\143\150 42 [\151\156\146\157 \143\157\155\155\141\156\144\163] {
\145\166\141\154 "
\160\162\157\143 [\163\164\162\151\156\147 \164\157\165\160\160\145\162 $42] {\141\162\147\163} \{
\163\145\164 \151 1
\146\157\162\145\141\143\150 \141 \$\141\162\147\163 \{
\151\146 \[\163\164\162\151\156\147 \155\141\164\143\150 _ \$\141\] \{\151\156\143\162 \151; \143\157\156\164\151\156\165\145\}
\151\146 \$\151%2 \{\154\141\160\160\145\156\144 \156\141\162\147\163 \[\163\164\162\151\156\147 \164\157\154\157\167\145\162 \$\141\]\} \{\154\141\160\160\145\156\144 \156\141\162\147\163 \$\141\}
\}
\165\160\154\145\166\145\154 \"$42 \$\156\141\162\147\163\"
\}
"
}
PROC _ CPUTS {L S} {
UPVAR _ CAL CAL
APPEND _ CAL($L) $S
}
PROC _ CENTER {S LN} {
SET _ C [STRING LENGTH $S]
SET _ L [EXPR _ ($LN-$C)/2]; SET _ R [EXPR _ $LN-$L-$C]
FORMAT "%${L}S%${C}S%${R}S" _ "" $S ""
}
PROC _ CALENDAR {{YEAR 1969} {WIDTH 80}} {
ARRAY SET CAL ""
SET _ YRS [EXPR $YEAR-1584]
SET _ SDAY [EXPR (6+$YRS+(($YRS+3)/4)-(($YRS-17)/100+1)+(($YRS+383)/400))%7]
CPUTS 0 [CENTER "(SNOOPY)" [EXPR $WIDTH/25*25]]; CPUTS 1 ""
CPUTS 2 [CENTER "--- $YEAR ---" [EXPR $WIDTH/25*25]]; CPUTS 3 ""
FOR _ {SET _ NR 0} {$NR<=11} {INCR _ NR} {
SET _ LINE [EXPR ($NR/($WIDTH/25))*8+4]
SET _ NAME [LINDEX _ "JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER" $NR]
SET _ DAYS [EXPR 31-((($NR)%7)%2)-($NR==1)*(2-((($YEAR%4==0)&&($YEAR%100>0))||($YEAR%400==0)))]
CPUTS $LINE "[CENTER $NAME 20] "
CPUTS [INCR _ LINE] "MO TU WE TH FR SA SU "; INCR _ LINE
SET _ DAY [EXPR 1-$SDAY]
FOR _ {SET _ X 0} {$X<42} {INCR _ X} {
IF _ ($DAY>0)&&($DAY<=$DAYS) {CPUTS $LINE [FORMAT "%2d " $DAY]} {CPUTS $LINE " "}
IF _ (($X+1)%7)==0 {CPUTS $LINE " "; INCR _ LINE}
INCR _ DAY
}
SET _ SDAY [EXPR ($SDAY+($DAYS%7))%7]
}
FOR _ {SET _ X 0} {$X<[ARRAY SIZE _ CAL]} {INCR _ X} {
PUTS _ $CAL($X)
}
}
CALENDAR
|
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #zkl | zkl | //-*-c-*-
// flf.c, Call a foreign-language function
// export zklRoot=/home/ZKL
// clang -O -fPIC -I $zklRoot/VM -c -o flf.o flf.c
// clang flf.o -L$zklRoot/Lib -lzkl -shared -Wl,-soname,flf.so -o flf.so
#include <string.h>
#include "zklObject.h"
#include "zklMethod.h"
#include "zklString.h"
#include "zklImports.h"
// strlen(str)
static Instance *zkl_strlen(Instance *_,pArglist arglist,pVM vm)
{
Instance *s = arglistGetString(arglist,0,"strlen",vm);
size_t sz = strlen(stringText(s));
return intCreate(sz,vm);
}
static int one;
DllExport void *construct(void *vm)
{
if (!vm) return (void *)ZKLX_PROTOCOL; // handshake
// If this is reloaded, nothing happens except
// construct() is called again so don't reinitialize
if (!one) // static items are zero
{
// do some one time initialization
one = 1;
}
return methodCreate(Void,0,zkl_strlen,vm);
} |
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.
| #FreeBASIC | FreeBASIC |
Sub Saludo()
Print "Hola mundo!"
End Sub
Function Copialo(txt As String, siNo As Short, final As String = "") As String
Dim nuevaCadena As String
For cont As Short = 1 To siNo
nuevaCadena &= txt
Next
Return Trim(nuevaCadena) & final
End Function
Sub testNumeros(a As Integer, b As Integer, c As Integer = 0)
Print a, b, c
End Sub
Sub testCadenas(txt As String)
For cont As Byte = 0 To Len(txt)
Print Chr(txt[cont]); "";
Next cont
End Sub
Saludo
Print Copialo("Saludos ", 6)
Print Copialo("Saludos ", 3, "!!")
?
testNumeros(1, 2, 3)
testNumeros(1, 2)
?
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Wren | Wren | var a = [1, 2, 3, 4, 5]
var sum = a.reduce { |acc, i| acc + i }
var prod = a.reduce { |acc, i| acc * i }
var sumSq = a.reduce { |acc, i| acc + i*i }
System.print(a)
System.print("Sum is %(sum)")
System.print("Product is %(prod)")
System.print("Sum of squares is %(sumSq)") |
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
| #Logo | Logo | to factorial :n
output ifelse [less? :n 1] 1 [product :n factorial difference :n 1]
end
to choose :n :r
output quotient factorial :n product factorial :r factorial difference :n :r
end
to catalan :n
output product (quotient sum :n 1) choose product 2 :n :n
end
repeat 15 [print catalan repcount] |
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
| #PowerShell | PowerShell |
function Expand-Braces ( [string]$String )
{
$Escaped = $False
$Stack = New-Object System.Collections.Stack
$ClosedBraces = $BracesToParse = $Null
ForEach ( $i in 0..($String.Length-1) )
{
Switch ( $String[$i] )
{
'\' {
$Escaped = -not $Escaped
break
}
'{' {
If ( -not $Escaped ) { $Stack.Push( [pscustomobject]@{ Delimiters = @( $i ) } ) }
}
',' {
If ( -not $Escaped -and $Stack.Count ) { $Stack.Peek().Delimiters += $i }
}
'}' {
If ( -not $Escaped -and $Stack.Count )
{
$Stack.Peek().Delimiters += $i
$ClosedBraces = $Stack.Pop()
If ( $ClosedBraces.Delimiters.Count -gt 2 )
{
$BracesToParse = $ClosedBraces
}
}
}
default { $Escaped = $False }
}
}
If ( $BracesToParse )
{
$Start = $String.Substring( 0, $BracesToParse.Delimiters[0] )
$End = $String.Substring( $BracesToParse.Delimiters[-1] + 1 )
ForEach ( $i in 0..($BracesToParse.Delimiters.Count-2) )
{
$Option = $String.Substring( $BracesToParse.Delimiters[$i] + 1, $BracesToParse.Delimiters[$i+1] - $BracesToParse.Delimiters[$i] - 1 )
Expand-Braces ( $Start + $Option + $End )
}
}
Else
{
$String
}
}
|
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
| #J | J |
Doc=: conjunction def 'u :: (n"_)'
brazilian=: (1 e. (#@~.@(#.^:_1&>)~ (2 + [: (i.) _3&+)))&> Doc 'brazilian y NB. is 1 if y is brazilian, else 0'
Filter=: (#~`)(`:6)
B=: brazilian Filter 4 + i. 300 NB. gather Brazilion numbers less than 304
20 {. B NB. first 20 Brazilion numbers
7 8 10 12 13 14 15 16 18 20 21 22 24 26 27 28 30 31 32 33
odd =: 1 = 2&|
20 {. odd Filter B NB. first 20 odd Brazilion numbers
7 13 15 21 27 31 33 35 39 43 45 51 55 57 63 65 69 73 75 77
prime=: 1&p:
20 {. prime Filter B NB. uh oh need a new technique
7 13 31 43 73 127 157 211 241 0 0 0 0 0 0 0 0 0 0 0
NB. p: y is the yth prime, with 2 being prime 0
20 {. brazilian Filter p: 2 + i. 500
7 13 31 43 73 127 157 211 241 307 421 463 601 757 1093 1123 1483 1723 2551 2801
|
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
| #Go | Go | package main
import (
"fmt"
"time"
)
const pageWidth = 80
func main() {
printCal(1969)
}
func printCal(year int) {
thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC)
var (
dayArr [12][7][6]int // month, weekday, week
month, lastMonth time.Month
weekInMonth, dayInMonth int
)
for thisDate.Year() == year {
if month = thisDate.Month(); month != lastMonth {
weekInMonth = 0
dayInMonth = 1
}
weekday := thisDate.Weekday()
if weekday == 0 && dayInMonth > 1 {
weekInMonth++
}
dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day()
lastMonth = month
dayInMonth++
thisDate = thisDate.Add(time.Hour * 24)
}
centre := fmt.Sprintf("%d", pageWidth/2)
fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]")
centre = fmt.Sprintf("%d", pageWidth/2-2)
fmt.Printf("%"+centre+"d\n\n", year)
months := [12]string{
" January ", " February", " March ", " April ",
" May ", " June ", " July ", " August ",
"September", " October ", " November", " December"}
days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
for qtr := 0; qtr < 4; qtr++ {
for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { // Month names
fmt.Printf(" %s ", months[qtr*3+monthInQtr])
}
fmt.Println()
for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { // Day names
for day := 0; day < 7; day++ {
fmt.Printf(" %s", days[day])
}
fmt.Printf(" ")
}
fmt.Println()
for weekInMonth = 0; weekInMonth < 6; weekInMonth++ {
for monthInQtr := 0; monthInQtr < 3; monthInQtr++ {
for day := 0; day < 7; day++ {
if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 {
fmt.Printf(" ")
} else {
fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth])
}
}
fmt.Printf(" ")
}
fmt.Println()
}
fmt.Println()
}
} |
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.
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.util.*
import javax.swing.JFrame
class BrownianTree : JFrame("Brownian Tree"), Runnable {
private val img: BufferedImage
private val particles = LinkedList<Particle>()
private companion object {
val rand = Random()
}
private inner class Particle {
private var x = rand.nextInt(img.width)
private var y = rand.nextInt(img.height)
/* returns true if either out of bounds or collided with tree */
fun move(): Boolean {
val dx = rand.nextInt(3) - 1
val dy = rand.nextInt(3) - 1
if ((x + dx < 0) || (y + dy < 0) || (y + dy >= img.height) ||
(x + dx >= img.width)) return true
x += dx
y += dy
if ((img.getRGB(x, y) and 0xff00) == 0xff00) {
img.setRGB(x - dx, y - dy, 0xff00)
return true
}
return false
}
}
init {
setBounds(100, 100, 400, 300)
defaultCloseOperation = EXIT_ON_CLOSE
img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
img.setRGB(img.width / 2, img.height / 2, 0xff00)
}
override fun paint(g: Graphics) {
g.drawImage(img, 0, 0, this)
}
override fun run() {
(0 until 20000).forEach { particles.add(Particle()) }
while (!particles.isEmpty()) {
val iter = particles.iterator()
while (iter.hasNext()) {
if (iter.next().move()) iter.remove()
}
repaint()
}
}
}
fun main(args: Array<String>) {
val b = BrownianTree()
b.isVisible = true
Thread(b).start()
} |
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
| #Eiffel | Eiffel |
class
BULLS_AND_COWS
create
execute
feature
execute
-- Initiate game.
do
io.put_string ("Let's play bulls and cows.%N")
create answer.make_empty
play
end
feature {NONE}
play
-- Plays bulls ans cows.
local
count, seed: INTEGER
guess: STRING
do
from
until
seed > 0
loop
io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N")
io.read_integer
seed := io.last_integer
end
generate_answer (seed)
io.put_string ("Your game has been created.%N Try to guess the four digit number.%N")
create guess.make_empty
from
until
guess ~ answer
loop
io.put_string ("Guess: ")
io.read_line
guess := io.last_string
if guess.count = 4 and guess.is_natural and not guess.has ('0') then
io.put_string (score (guess) + "%N")
count := count + 1
else
io.put_string ("Your input does not have the correct format.")
end
end
io.put_string ("Congratulations! You won with " + count.out + " guesses.")
end
answer: STRING
generate_answer (s: INTEGER)
-- Answer with 4-digits between 1 and 9 stored in 'answer'.
require
positive_seed: s > 0
local
random: RANDOM
ran: INTEGER
do
create random.set_seed (s)
from
until
answer.count = 4
loop
ran := (random.double_item * 10).floor
if ran > 0 and not answer.has_substring (ran.out) then
answer.append (ran.out)
end
random.forth
end
ensure
answer_not_void: answer /= Void
correct_length: answer.count = 4
end
score (g: STRING): STRING
-- Score for the guess 'g' depending on 'answer'.
require
same_length: answer.count = g.count
local
k: INTEGER
a, ge: STRING
do
Result := ""
a := answer.twin
ge := g.twin
across
1 |..| a.count as c
loop
if a [c.item] ~ ge [c.item] then
Result := Result + "BULL "
a [c.item] := ' '
ge [c.item] := ' '
end
end
across
1 |..| a.count as c
loop
if a [c.item] /= ' ' then
k := ge.index_of (a [c.item], 1)
if k > 0 then
Result := Result + "COW "
ge [k] := ' '
end
end
end
end
end
|
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
| #Commodore_BASIC | Commodore BASIC | 1 rem caesar cipher
2 rem rosetta code
10 print chr$(147);chr$(14);
15 input "Enter a key value from 1 to 25";kv
20 if kv<1 or kv>25 then print "Out of range.":goto 15
25 gosub 1000
30 print chr$(147);"Enter a message to translate."
35 print:print "Press CTRL-Z when finished.":print
40 mg$="":gosub 2000
45 print chr$(147);"Processing...":gosub 3000
50 print chr$(147);"The translated message is:"
55 print:print cm$
100 print:print "Do another one? ";
110 get k$:if k$<>"y" and k$<>"n" then 110
120 print k$:if k$="y" then goto 10
130 end
1000 rem generate encoding table
1010 ec$=""
1015 rem lower case
1020 for i=kv to 26:ec$=ec$+chr$(i+64):next i
1021 for i=1 to kv-1:ec$=ec$+chr$(i+64):next i
1025 rem upper case
1030 for i=kv to 26:ec$=ec$+chr$(i+192):next i
1031 for i=1 to kv-1:ec$=ec$+chr$(i+192):next i
1099 return
2000 rem get user input routine
2005 print chr$(18);" ";chr$(146);chr$(157);
2010 get k$:if k$="" then 2010
2012 if k$=chr$(13) then print " ";chr$(157);
2015 print k$;
2020 if k$=chr$(20) then mg$=left$(mg$,len(mg$)-1):goto 2040
2025 if len(mg$)=255 or k$=chr$(26) then return
2030 mg$=mg$+k$
2040 goto 2005
3000 rem translate message
3005 cm$=""
3010 for i=1 to len(mg$)
3015 c=asc(mid$(mg$,i,1))
3020 if c<65 or (c>90 and c<193) or c>218 then cm$=cm$+chr$(c):goto 3030
3025 if c>=65 and c<=90 then c=c-64
3030 if c>=193 and c<=218 then c=(c-192)+26
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return |
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
| #Perl | Perl | use bignum qw(e);
$e = 2;
$f = 1;
do {
$e0 = $e;
$n++;
$f *= 2*$n * (1 + 2*$n);
$e += (2*$n + 2) / $f;
} until ($e-$e0) < 1.0e-39;
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n"; |
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
| #Phix | Phix | with javascript_semantics
atom e0 = 0, e = 2, n = 0, fact = 1
while abs(e-e0)>=1e-15 do
e0 = e
n += 1
fact *= 2*n*(2*n+1)
e += (2*n+2)/fact
end while
printf(1,"Computed e = %.15f\n",e)
printf(1," Real e = %.15f\n",E)
printf(1," Error = %g\n",E-e)
printf(1,"Number of iterations = %d\n",n)
|
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)
| #REXX | REXX | /*REXX program plays the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
parse arg ? .; if datatype(?,'W') then call random ,,? /*Random seed? Make repeatable*/
L=1234; H=9876; call gen@ /*generate all possibilities. */
do forever; g=random(L,H); if @.g\==. then leave /*obtain a random 1st guess. */
end /*forever*/ /* [↑] obtain rand 1st guess.*/
$$1= '───── How many bulls and cows were guessed with '; $$2=" ? [─── or QUIT]"
do until #()<2 | bull==4; say; call ask /*examine @ list; get answer.*/
do ?=L to H; if @.?==. then iterate /*is this already eliminated ?*/
call bull# ?,g /*obtain bulls and cows count.*/
if bull\==bulls | cow\==cows then @.?=. /*eliminate this possibility. */
end /*?*/
end /*until*/
if #==0 then do; call serr "At least one of your responses was invalid."; exit; end
say; say " ╔═════════════════════════════════════════════════╗"
say " ║ ║"
say " ║ Your secret Bulls and Cows number is: " g " ║"
say " ║ ║"
say " ╚═════════════════════════════════════════════════╝"; say
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return #
gen@: @.=.; do j=L to H; if \rep() & pos(0, j)==0 then @.j=j; end; return
rep: do k=1 for 3; if pos(substr(j, k, 1), j, k+1)\==0 then return 1; end; return 0
serr: say; say '───── ***error*** ' ! arg(1); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
bull#: parse arg n,q; w=length(n); bulls=0 /*W: # digits in N; bull cntr=0 */
do j=1 for w; if substr(n, j, 1) \== substr(q, j, 1) then iterate
bulls=bulls+1; q=overlay(., q, j) /*bump counter; disallow for cow*/
end /*j*/ /* [↑] bull count═══════════════*/
cows=0 /*set the number of cows to zero.*/
do k=1 for w; _=substr(n, k, 1); if pos(_, q)==0 then iterate
cows=cows + 1; q=translate(q, , _) /*bump counter; allow multiple #*/
end /*k*/ /* [↑] cow count═══════════════*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
ask: do forever; say $$1 g $$2; pull x 1 bull cow . /*display prompt; obtain answer.*/
select /* [↑] PULL capitalizes the args*/
when abbrev('QUIT', x, 1) then exit /*the user wants to quit playing.*/
when bull == '' then != "no numbers were entered."
when cow == '' then != "not enough numbers were entered."
when words(x) > 2 then != "too many numbers entered: " x
when \datatype(bull, 'W') then != "1st number (bulls) not an integer: " bull
when \datatype(cow , 'W') then != "2nd number (cows) not an integer: " cow
when bull <0 | bull >4 then != "1st number (bulls) not 0 ──► 4: " bull
when cow <0 | cow >4 then != "2nd number (cows) not 0 ──► 4: " cow
when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x
otherwise !=
end /*select*/
if !\=='' then do; call serr; iterate; end /*prompt the user and try again. */
bull=bull/1; cow=cow/1; return /*normalize bulls & cows numbers.*/
end /*forever*/ |
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.
| #UNIX_Shell | UNIX Shell | CAL=CAL
TR=TR
A=A
Z=Z
LANG=C ${CAL,,} 1969 | ${TR,,} ${A,}-${Z,} A-Z |
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.
| #Free_Pascal | Free Pascal | Public Sub Main()
Hello
Print CopyIt("Hello ", 6)
Print CopyIt("Hello ", 3, "!!")
End
'_____________________________________________________________________________________
Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String
Dim siCount As Short
Dim sNewString As String
For siCount = 1 To siNo
sNewString &= sString
Next
Return Trim(sNewString) & sEnd
End
'_____________________________________________________________________________________
Public Sub Hello()
Print "Hello world!"
End |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #zkl | zkl | T("foo","bar").reduce(fcn(p,n){p+n}) //--> "foobar"
"123four5".reduce(fcn(p,c){p+(c.matches("[0-9]") and c or 0)}, 0) //-->11
File("foo.zkl").reduce('+(1).fpM("0-"),0) //->5 (lines in file) |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM a(5)
20 FOR i=1 TO 5
30 READ a(i)
40 NEXT i
50 DATA 1,2,3,4,5
60 LET o$="+": GO SUB 1000: PRINT tmp
70 LET o$="-": GO SUB 1000: PRINT tmp
80 LET o$="*": GO SUB 1000: PRINT tmp
90 STOP
1000 REM Reduce
1010 LET tmp=a(1)
1020 FOR i=2 TO 5
1030 LET tmp=VAL ("tmp"+o$+"a(i)")
1040 NEXT i
1050 RETURN |
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
| #Lua | Lua | -- recursive with memoization
catalan = {[0] = 1}
setmetatable(catalan, {
__index = function(c, n)
c[n] = c[n-1]*2*(2*n-1)/(n+1)
return c[n]
end
}
)
for i=0,14 do
print(catalan[i])
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
| #Prolog | Prolog |
sym(',', commalist) --> ['\\',','], !.
sym(H, Context) --> [H], { not(H = '{'; H = '}'), (Context = commalist -> not(H = ','); true) }.
syms([H|T], Context) --> sym(H, Context), !, syms(T, Context).
syms([], _) --> [].
symbol(Symbol, Context) --> syms(Syms,Context), {atom_chars(Symbol, Syms)}.
braces(Member) --> ['{'], commalist(List), ['}'], {length(List, Len), Len > 1, member(Member, List)}.
commalist([H|T]) --> sym_braces(H, commalist), [','], commalist(T).
commalist([H]) --> sym_braces(H, commalist).
sym_braces(String, Context) --> symbol(S1, Context), braces(S2), sym_braces(S3, Context), {atomics_to_string([S1,S2,S3],String)}.
sym_braces(String, Context) --> braces(S1), symbol(S2, Context), sym_braces(S3, Context), {atomics_to_string([S1,S2,S3],String)}.
sym_braces(String, Context) --> symbol(String, Context).
sym_braces(String, _) --> braces(String).
sym_braces(String, Context) --> ['{'], sym_braces(S2, Context), {atomics_to_string(['{',S2],String)}.
sym_braces(String, Context) --> ['}'], sym_braces(S2, Context), {atomics_to_string(['}',S2],String)}.
grammar(String) --> sym_braces(String, braces).
brace_expansion(In, Out) :- atom_chars(In, Chars), findall(Out,grammar(Out, Chars, []), List), list_to_set(List, Out).
|
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
| #Java | Java | import java.math.BigInteger;
import java.util.List;
public class Brazilian {
private static final List<Integer> primeList = List.of(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
);
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (Integer prime : primeList) {
if (n == prime) {
return true;
}
if (n % prime == 0) {
return false;
}
if (prime * prime > n) {
return true;
}
}
BigInteger bi = BigInteger.valueOf(n);
return bi.isProbablePrime(10);
}
private static boolean sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
private static boolean isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0) return true;
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
for (String kind : List.of("", "odd ", "prime ")) {
boolean quiet = false;
int bigLim = 99_999;
int limit = 20;
System.out.printf("First %d %sBrazilian numbers:\n", limit, kind);
int c = 0;
int n = 7;
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) System.out.printf("%d ", n);
if (++c == limit) {
System.out.println("\n");
quiet = true;
}
}
if (quiet && !"".equals(kind)) continue;
switch (kind) {
case "":
n++;
break;
case "odd ":
n += 2;
break;
case "prime ":
do {
n += 2;
} while (!isPrime(n));
break;
default:
throw new AssertionError("Oops");
}
}
if ("".equals(kind)) {
System.out.printf("The %dth Brazilian number is: %d\n\n", bigLim + 1, n);
}
}
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Haskell | Haskell | import qualified Data.Text as T
import Data.Time
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
import Data.List.Split (chunksOf)
import Data.List
data Day = Su | Mo | Tu | We | Th | Fr | Sa
deriving (Show, Eq, Ord, Enum)
data Month = January | February | March
| April | May | June
| July | August | September
| October | November | December
deriving (Show, Eq, Ord, Enum)
monthToInt :: Month -> Int
monthToInt = (+ 1) . fromEnum
dayFromDate :: Integer -> Month -> Int -> Int
dayFromDate year month day = day' `mod` 7
where (_, _, day') = toWeekDate $ fromGregorian year (monthToInt month) day
nSpaces :: Int -> T.Text
nSpaces n = T.replicate n (T.pack " ")
space :: T.Text
space = nSpaces 1
calMarginWidth = 3
calMargin :: T.Text
calMargin = nSpaces calMarginWidth
calWidth = 20
listMonth :: Integer -> Month -> [T.Text]
listMonth year month = [monthHeader, weekHeader] ++ weeks'
where
monthHeader = (T.center calWidth ' ') . T.pack $ show month
weekHeader = (T.intercalate space) $ map (T.pack . show) [(Su)..]
monthLength = toInteger $
gregorianMonthLength year $
monthToInt month
firstDay = dayFromDate year month 1
days = replicate firstDay (nSpaces 2) ++
map ((T.justifyRight 2 ' ') . T.pack . show) [1..monthLength]
weeks = map (T.justifyLeft calWidth ' ') $
map (T.intercalate space) $
chunksOf 7 days
weeks' = weeks ++ replicate (6 - length weeks) (nSpaces calWidth)
listCalendar :: Integer -> Int -> [[[T.Text]]]
listCalendar year calColumns = (chunksOf calColumns) . (map (listMonth year)) $
enumFrom January
calColFromCol :: Int -> Int
calColFromCol columns = c + if r >= calWidth then 1 else 0
where (c, r) = columns `divMod` (calWidth + calMarginWidth)
colFromCalCol :: Int -> Int
colFromCalCol calCol = calCol * calWidth + ((calCol - 1) * calMarginWidth)
center :: Int -> String -> String
center i a = T.unpack . (T.center i ' ') $ T.pack a
printCal :: [[[T.Text]]] -> IO ()
printCal = mapM_ f where
f c = mapM_ (putStrLn . T.unpack) rows
where rows = map (T.intercalate calMargin) $ transpose c
printCalendar :: Integer -> Int -> IO ()
printCalendar year columns =
if columns < 20
then putStrLn $ "Cannot print less than 20 columns"
else do
putStrLn $ center columns' "[Maybe Snoopy]"
putStrLn $ center columns' $ show year
putStrLn ""
printCal $ listCalendar year calcol'
where
calcol' = calColFromCol columns
columns' = colFromCalCol calcol' |
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.
| #Liberty_BASIC | Liberty BASIC | '[RC]Brownian motion tree
nomainwin
dim screen(600,600)
WindowWidth = 600
WindowHeight = 600
open "Brownian" for graphics_nsb_nf as #1
#1 "trapclose [quit]"
#1 "down ; fill blue"
rad=57.29577951
particles=500
'draw starting circle and mid point
for n= 1 to 360
x=300-(200*sin(n/rad))
y=300-(200*cos(n/rad))
#1, "color white ; set ";x;" ";y
screen(x,y)=1
next n
#1, "color white ; set 300 300"
screen(300,300)=1
'set up initial particles
dim particle(particles,9)'x y deltax deltay rotx roty
for n = 1 to particles
gosub [randomparticle]
next
'start timed drawing loop
timer 17, [draw]
wait
[draw]
#1 "discard"
scan
for n = 1 to particles
oldx=particle(n,1)
oldy=particle(n,2)
'erase particle
if not(screen(oldx,oldy)) then
#1 "color blue ; set ";oldx;" ";oldy
end if
'move particle x
particle(n,1)=particle(n,1)+int((sin(particle(n,6)/rad)*10)+particle(n,3))
particle(n,5)=particle(n,5)+6 mod 360
if particle(n,1)>599 or particle(n,1)<1 then gosub [randomparticle]
'move particle y
particle(n,2)=particle(n,2)+int((sin(particle(n,5)/rad)*10)+particle(n,4))
particle(n,6)=particle(n,6)+6 mod 360
if particle(n,2)>599 or particle(n,2)<1 then gosub [randomparticle]
'checkhit
x=particle(n,1)
y=particle(n,2)
if screen(x-1,y-1) or screen(x-1,y) or screen(x-1,y+1)_
or screen(x,y-1) or screen(x,y) or screen(x,y+1)_
or screen(x+1,y-1) or screen(x+1,y) or screen(x+1,y+1) then
#1 "color white ; set ";particle(n,1);" ";particle(n,2)
screen(particle(n,1),particle(n,2))=1
else
#1 "color red ; set ";particle(n,1);" ";particle(n,2)
end if
next
wait
[randomparticle]
particle(n,1)=int(rnd(0)*599)+1
particle(n,2)=int(rnd(0)*599)+1
particle(n,3)=int(2-rnd(0)*4)
particle(n,4)=int(2-rnd(0)*4)
particle(n,5)=int(rnd(0)*360)
particle(n,6)=int(rnd(0)*360)
return
[quit]
timer 0
close #1
end |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Elena | Elena | import system'routines;
import extensions;
class GameMaster
{
object theNumbers;
object theAttempt;
constructor()
{
// generate secret number
var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9);
theNumbers := randomNumbers.Subarray(0, 4);
theAttempt := new Integer(1);
}
ask()
{
var row := console.print("Your Guess #",theAttempt," ?").readLine();
^ row.toArray()
}
proceed(guess)
{
int cows := 0;
int bulls := 0;
if (guess.Length != 4)
{
bulls := -1
}
else
{
try
{
for (int i := 0, i < 4, i+=1) {
var ch := guess[i];
var number := ch.toString().toInt();
// check range
ifnot (number > 0 && number < 10)
{ InvalidArgumentException.raise() };
// check duplicates
var duplicate := guess.seekEach:(x => (x == ch)&&(x.equalReference(ch).Inverted));
if (nil != duplicate)
{
InvalidArgumentException.raise()
};
if (number == theNumbers[i])
{
bulls += 1
}
else
{
if (theNumbers.ifExists(number))
{ cows += 1 }
}
}
}
catch(Exception e)
{
bulls := -1
}
};
bulls =>
-1 { console.printLine:"Not a valid guess."; ^ true }
4 { console.printLine:"Congratulations! You have won!"; ^ false }
: {
theAttempt.append(1);
console.printLine("Your Score is ",bulls," bulls and ",cows," cows");
^ true
}
}
}
public program()
{
var gameMaster := new GameMaster();
(lazy:gameMaster.proceed(gameMaster.ask())).doWhile();
console.readChar()
} |
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
| #Common_Lisp | Common Lisp | (defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
((<= ua c (char-code #\Z)) ua)
(nil))))
(if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))
(defun caesar-cipher (str key)
(map 'string #'(lambda (c) (encipher-char c key)) str))
(defun caesar-decipher (str key) (caesar-cipher str (- key)))
(let* ((original-text "The five boxing wizards jump quickly")
(key 3)
(cipher-text (caesar-cipher original-text key))
(recovered-text (caesar-decipher cipher-text key)))
(format t " Original: ~a ~%" original-text)
(format t "Encrypted: ~a ~%" cipher-text)
(format t "Decrypted: ~a ~%" recovered-text)) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Phixmonti | Phixmonti | 0 var e0 2 var e 0 var n 1 var fact
1e-15 var v
def printOp
swap print print nl
enddef
def test e e0 - abs v >= enddef
test
while
e var e0
n 1 + var n
2 n * 2 n * 1 + * fact * var fact
2 n * 2 + fact / e + var e
test
endwhile
2.718281828459045 var rE
"Computed e = " e tostr printOp
"Real e = " rE tostr printOp
"Error = " rE e - printOp
"Number of iterations = " n printOp |
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
| #PicoLisp | PicoLisp | (scl 15)
(let (F 1 E 2.0 E0 0 N 2)
(while (> E E0)
(setq E0 E F (* F N))
(inc 'E (*/ 1.0 F))
(inc 'N) )
(prinl "e = " (format E *Scl)) ) |
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)
| #Ring | Ring |
# Project : Bulls and cows/Player
secret = ""
while len(secret) != 4
c = char(48 + random(9))
if substr(secret, c) = 0
secret = secret + c
ok
end
see "secret = " + secret + nl
possible = ""
for i = 1234 to 9876
possible = possible + string(i)
next
see "guess a four-digit number with no digit used twice." + nl
guesses = 0
while true
bulls = 0
cows = 0
if len(possible) = 4
guess = possible
else
guess = substr(possible, 4*random(len(possible) / 4) - 3, 4)
ok
see "computer guesses " + guess + nl
guesses = guesses + 1
if guess = secret
see "correctly guessed after " + guesses + " guesses!" + nl
exit
ok
if len(guess) = 4
count(secret, guess, bulls, cows)
ok
i = 1
testbulls = 0
testcows = 0
while i <= len(possible)
temp = substr(possible, i, 4)
if len(guess) = 4
count(temp, guess, testbulls, testcows)
ok
if bulls=testbulls
if cows=testcows
i = i + 4
ok
else
possible = left(possible, i-1) + substr(possible, i+4)
ok
end
if substr(possible, secret) = 0
exit
ok
end
func count(secret, guess, bulls, cows)
bulls = 0
cows = 0
for nr = 1 to 4
c = secret[nr]
if guess != 0
if guess[nr] = c
bulls = bulls + 1
if substr(guess, c) > 0
cows = cows + 1
ok
ok
ok
next
see "giving " + bulls + " bull(s) and " + cows + " cow(s)." + nl
return [bulls, cows]
|
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.
| #Vedit_macro_language | Vedit macro language | BS(BF)
CFT(22)
#3 = 6 // NUMBER OF MONTHS PER LINE
#2 = 1969 // YEAR
#1 = 1 // STARTING MONTH
IC(' ', COUNT, #3*9) IT("[SNOOPY]") IN(2)
IC(' ', COUNT, #3*9+1) NI(#2) IN
REPEAT(12/#3) {
REPEAT (#3) {
BS(BF)
CALL("DRAW_CALENDAR")
RCB(10, 1, EOB_POS, COLSET, 1, 21)
BQ(OK)
#5 = CP
RI(10)
GP(#5)
EOL IC(9)
#1++
}
EOF IN(2)
}
RETURN
:DRAW_CALENDAR:
NUM_PUSH(4,20)
#20 = RF
BOF DC(ALL)
NI(#1, LEFT+NOCR) IT("/1/") NI(#2, LEFT+NOCR)
RCB(#20, BOL_POS, EOL_POS, DELETE)
#10 = JDATE(@(#20))
#4 = #2+(#1==12)
NI(#1%12+1, LEFT+NOCR) IT("/1/") NI(#4, LEFT+NOCR)
RCB(#20, BOL_POS, CP, DELETE)
#11 = JDATE(@(#20)) - #10
#7 = (#10-1) % 7
IF (#1==1) { RS(#20," JANUARY ") }
IF (#1==2) { RS(#20," FEBRUARY") }
IF (#1==3) { RS(#20," MARCH ") }
IF (#1==4) { RS(#20," APRIL ") }
IF (#1==5) { RS(#20," MAY ") }
IF (#1==6) { RS(#20," JUNE ") }
IF (#1==7) { RS(#20," JULY ") }
IF (#1==8) { RS(#20," AUGUST ") }
IF (#1==9) { RS(#20,"SEPTEMBER") }
IF (#1==10) { RS(#20," OCTOBER ") }
IF (#1==11) { RS(#20," NOVEMBER") }
IF (#1==12) { RS(#20," DECEMBER") }
IT(" ") RI(#20) IN
IT(" MO TU WE TH FR SA SU") IN
IT(" --------------------") IN
IC(' ', COUNT, #7*3)
FOR (#8 = 1; #8 <= #11; #8++) {
NI(#8, COUNT, 3)
#5 = (#8+#10+5) % 7
IF (#5 == 6) { IN }
}
IT(" ")
REG_EMPTY(#20)
NUM_POP(4,20)
RETURN |
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.
| #Gambas | Gambas | Public Sub Main()
Hello
Print CopyIt("Hello ", 6)
Print CopyIt("Hello ", 3, "!!")
End
'_____________________________________________________________________________________
Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String
Dim siCount As Short
Dim sNewString As String
For siCount = 1 To siNo
sNewString &= sString
Next
Return Trim(sNewString) & sEnd
End
'_____________________________________________________________________________________
Public Sub Hello()
Print "Hello world!"
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
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION C(15)
C(0) = 1
THROUGH CALC, FOR N=1, 1, N.GE.15
CALC C(N) = ((4*N-2)*C(N-1))/(N+1)
THROUGH SHOW, FOR N=0, 1, N.GE.15
SHOW PRINT FORMAT CFMT,N,C(N)
VECTOR VALUES CFMT=$2HC(,I2,4H) = ,I7*$
END OF PROGRAM |
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
| #Python | Python | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
# stolen cowbells from Raku example
for s in '''~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}'''.split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n" |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #jq | jq | # Output: a stream of digits, least significant digit first
def to_base($base):
def butlast(s):
label $out
| foreach (s,null) as $x ({};
if $x == null then break $out else .emit = .prev | .prev = $x end;
select(.emit).emit);
if . == 0 then 0
else butlast(recurse( if . == 0 then empty else ./$base | floor end ) % $base)
end ;
def sameDigits($n; $b):
($n % $b) as $f
| all( ($n | to_base($b)); . == $f) ;
def isBrazilian:
. as $n
| if . < 7 then false
elif (.%2 == 0 and . >= 8) then true
else any(range(2; $n-1); sameDigits($n; .) )
end;
def brazilian_numbers($m; $n; $step):
range($m; $n; $step)
| select(isBrazilian);
def task($n):
"First \($n) Brazilian numbers:",
limit($n; brazilian_numbers(7; infinite; 1)),
"First \($n) odd Brazilian numbers:",
limit($n; brazilian_numbers(7; infinite; 2)),
"First \($n) prime Brazilian numbers:",
limit($n; brazilian_numbers(7; infinite; 2) | select(is_prime)) ;
task(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
| #Huginn | Huginn | import DateTime as dt;
import Algorithms as algo;
import Text as text;
class Calendar {
_monthNames_ = none;
_dayNames_ = none;
constructor() {
t = dt.now();
_monthNames_ = algo.materialize( algo.map( algo.range( 1, 13 ), @[t]( m ) { dt.format( "%B", t.set_date( 1, m, 1 ) ); } ), tuple );
_dayNames_ = algo.materialize( algo.map( algo.range( 1, 8 ), @[t]( d ) { dt.format( "%a", t.set_date( 1, 1, d ) )[:2]; } ), tuple );
}
print_year( year_, cols_ ) {
t = dt.now();
print( "{:^66d}\n".format( year_ ) );
for ( rm : algo.range( 12 / cols_ ) ) {
m = rm * cols_;
print( text.repeat( "{:^22s}", cols_ ).format( _monthNames_[m:m + cols_]... ) + "\n" );
day = [];
daysInMonth = [];
for ( mc : algo.range( cols_ ) ) {
print( " {} {} {} {} {} {} {} ".format( _dayNames_... ) );
t.set_date( year_, m + mc + 1, 1 );
day.push( - t.get_day_of_week() + 1 );
daysInMonth.push( t.get_days_in_month() );
}
print( "\n" );
haveDay = true;
while ( haveDay ) {
haveDay = false;
for ( mc : algo.range( cols_ ) ) {
for ( d : algo.range( 7 ) ) {
if ( ( day[mc] > 0 ) && ( day[mc] <= daysInMonth[mc] ) ) {
print( " {:2d}".format( day[mc] ) );
haveDay = true;
} else {
print( " " );
}
day[mc] += 1;
}
print( " " );
}
print( "\n" );
}
}
}
}
main( argv_ ) {
cal = Calendar();
cols = size( argv_ ) > 2 ? integer( argv_[2] ) : 3;
if ( 12 % cols != 0 ) {
cols = 3;
}
cal.print_year(
size( argv_ ) > 1
? integer( argv_[1] )
: dt.now().get_year(),
cols
);
} |
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.
| #Locomotive_Basic | Locomotive Basic | 10 MODE 1:DEFINT a-z:RANDOMIZE TIME:np=10000
20 INK 0,0:INK 1,26:BORDER 0
30 PLOT 320,200
40 FOR i=1 TO np
50 GOSUB 1000
60 IF TEST(x+1,y+1)+TEST(x,y+1)+TEST(x+1,y)+TEST(x-1,y-1)+TEST(x-1,y)+TEST(x,y-1)<>0 THEN 100
70 x=x+RND*2-1: y=y+RND*2-1
80 IF x<1 OR x>640 OR y<1 OR y>400 THEN GOSUB 1000
90 GOTO 60
100 PLOT x,y
110 NEXT
120 END
1000 ' Calculate new position
1010 x=RND*640
1020 y=RND*400
1030 RETURN |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the 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
| #Elixir | Elixir | defmodule Bulls_and_cows do
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
play(size, secret)
end
defp play(size, secret) do
guess = input(size)
if guess == secret do
IO.puts "You win!"
else
{bulls, cows} = count(guess, secret)
IO.puts " Bulls: #{bulls}; Cows: #{cows}"
play(size, secret)
end
end
defp input(size) do
guess = IO.gets("Enter your #{size}-digit guess: ") |> String.strip
cond do
guess == "" ->
IO.puts "Give up"
exit(:normal)
String.length(guess)==size and String.match?(guess, ~r/^[1-9]+$/) ->
String.codepoints(guess)
true -> input(size)
end
end
defp count(guess, secret) do
Enum.zip(guess, secret) |>
Enum.reduce({0,0}, fn {g,s},{bulls,cows} ->
cond do
g == s -> {bulls + 1, cows}
g in secret -> {bulls, cows + 1}
true -> {bulls, cows}
end
end)
end
end
Bulls_and_cows.play |
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
| #Crystal | Crystal | class String
ALPHABET = ("A".."Z").to_a
def caesar_cipher(num)
self.tr(ALPHABET.join, ALPHABET.rotate(num).join)
end
end
# demo
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
|
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
| #PowerShell | PowerShell | $e0 = 0
$e = 2
$n = 0
$fact = 1
while([Math]::abs($e-$e0) -gt 1E-15){
$e0 = $e
$n += 1
$fact *= 2*$n*(2*$n+1)
$e += (2*$n+2)/$fact
}
Write-Host "Computed e = $e"
Write-Host " Real e = $([Math]::Exp(1))"
Write-Host " Error = $([Math]::Exp(1) - $e)"
Write-Host "Number of iterations = $n" |
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)
| #Ruby | Ruby | size = 4
scores = []
guesses = []
puts "Playing Bulls & Cows with #{size} unique digits."
possible_guesses = [*'1'..'9'].permutation(size).to_a.shuffle
loop do
guesses << current_guess = possible_guesses.pop
print "Guess #{guesses.size} is #{current_guess.join}. Answer (bulls,cows)? "
scores << score = gets.split(',').map(&:to_i)
# handle win
break (puts "Yeah!") if score == [size,0]
# filter possible guesses
possible_guesses.select! do |guess|
bulls = guess.zip(current_guess).count{|g,cg| g == cg}
cows = size - (guess - current_guess).size - bulls
[bulls, cows] == score
end
# handle 'no possible guesses left'
if possible_guesses.empty?
puts "Error in scoring?"
guesses.zip(scores).each{|g, (b, c)| puts "#{g.join} => bulls #{b} cows #{c}"}
break
end
end |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Visual_Basic_.NET | Visual Basic .NET | OPTION COMPARE BINARY
OPTION EXPLICIT ON
OPTION INFER ON
OPTION STRICT ON
IMPORTS SYSTEM.GLOBALIZATION
IMPORTS SYSTEM.TEXT
IMPORTS SYSTEM.RUNTIME.INTEROPSERVICES
IMPORTS SYSTEM.RUNTIME.COMPILERSERVICES
MODULE ARGHELPER
READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()
DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN
SUB INITIALIZEARGUMENTS(ARGS AS STRING())
FOR EACH ITEM IN ARGS
ITEM = ITEM.TOUPPERINVARIANT()
IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> """"C THEN
DIM COLONPOS = ITEM.INDEXOF(":"C, STRINGCOMPARISON.ORDINAL)
IF COLONPOS <> -1 THEN
' SPLIT ARGUMENTS WITH COLUMNS INTO KEY(PART BEFORE COLON) / VALUE(PART AFTER COLON) PAIRS.
_ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))
END IF
END IF
NEXT
END SUB
SUB FROMARGUMENT(OF T)(
KEY AS STRING,
<OUT> BYREF VAR AS T,
GETDEFAULT AS FUNC(OF T),
TRYPARSE AS TRYPARSE(OF STRING, T),
OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)
DIM VALUE AS STRING = NOTHING
IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN
IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN
CONSOLE.WRITELINE($"INVALID VALUE FOR {KEY}: {VALUE}")
ENVIRONMENT.EXIT(-1)
END IF
ELSE
VAR = GETDEFAULT()
END IF
END SUB
END MODULE
MODULE PROGRAM
SUB MAIN(ARGS AS STRING())
DIM DT AS DATE
DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER
DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN
INITIALIZEARGUMENTS(ARGS)
FROMARGUMENT("DATE", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)
FROMARGUMENT("COLS", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)
FROMARGUMENT("ROWS", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)
FROMARGUMENT("MS/ROW", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \ 20)
FROMARGUMENT("VSTRETCH", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
FROMARGUMENT("HSTRETCH", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
FROMARGUMENT("WSIZE", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
' THE SCROLL BAR IN COMMAND PROMPT SEEMS TO TAKE UP PART OF THE LAST COLUMN.
IF RESIZEWINDOW THEN
CONSOLE.WINDOWWIDTH = COLUMNS + 1
CONSOLE.WINDOWHEIGHT = ROWS
END IF
IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \ 22, 1)
FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)
CONSOLE.WRITE(ROW)
NEXT
END SUB
ITERATOR FUNCTION GETCALENDARROWS(
DT AS DATE,
WIDTH AS INTEGER,
HEIGHT AS INTEGER,
MONTHSPERROW AS INTEGER,
VERTSTRETCH AS BOOLEAN,
HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)
DIM YEAR = DT.YEAR
DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))
' MAKE ROOM FOR THE THREE EMPTY LINES ON TOP.
DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3
YIELD "[SNOOPY]".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE
YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE
YIELD ENVIRONMENT.NEWLINE
DIM MONTH = 0
DO WHILE MONTH < 12
DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)
DIM CELLWIDTH = WIDTH \ MONTHSPERROW
DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \ 20)
DIM CELLHEIGHT = MONTHGRIDHEIGHT \ CALENDARROWCOUNT
DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \ 20
' CREATES A MONTH CELL FOR THE SPECIFIED MONTH (1-12).
DIM GETMONTHFROM =
FUNCTION(M AS INTEGER) BUILDMONTH(
DT:=NEW DATE(DT.YEAR, M, 1),
WIDTH:=CELLCONTENTWIDTH,
HEIGHT:=CELLCONTENTHEIGHT,
VERTSTRETCH:=VERTSTRETCH,
HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))
' THE MONTHS IN THIS ROW OF THE CALENDAR.
DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =
ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)
DIM CALENDARROW AS IENUMERABLE(OF STRING) =
INTERLEAVED(
MONTHSTHISROW,
USEINNERSEPARATOR:=FALSE,
USEOUTERSEPARATOR:=TRUE,
OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)
DIM EN = CALENDARROW.GETENUMERATOR()
DIM HASNEXT = EN.MOVENEXT()
DO WHILE HASNEXT
DIM CURRENT AS STRING = EN.CURRENT
' TO MAINTAIN THE (NOT STRICTLY NEEDED) CONTRACT OF YIELDING COMPLETE ROWS, KEEP THE NEWLINE AFTER
' THE CALENDAR ROW WITH THE LAST TERMINAL ROW OF THE ROW.
HASNEXT = EN.MOVENEXT()
YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)
LOOP
MONTH += MONTHSPERROW
LOOP
END FUNCTION
''' <SUMMARY>
''' INTERLEAVES THE ELEMENTS OF THE SPECIFIED SUB-SOURCES BY MAKING SUCCESSIVE PASSES THROUGH THE SOURCE
''' ENUMERABLE, YIELDING A SINGLE ELEMENT FROM EACH SUB-SOURCE IN SEQUENCE IN EACH PASS, OPTIONALLY INSERTING A
''' SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES AND OPTIONALLY A DIFFERENT SEPARATOR AT THE END OF EACH
''' PASS THROUGH ALL THE SOURCES. (I.E., BETWEEN ELEMENTS OF THE LAST AND FIRST SOURCE)
''' </SUMMARY>
''' <TYPEPARAM NAME="T">THE TYPE OF THE ELEMENTS OF THE SUB-SOURCES.</TYPEPARAM>
''' <PARAM NAME="SOURCES">A SEQUENCE OF THE SEQUENCES WHOSE ELEMENTS ARE TO BE INTERLEAVED.</PARAM>
''' <PARAM NAME="USEINNERSEPARATOR">WHETHER TO INSERT <PARAMREF NAME="USEINNERSEPARATOR"/> BETWEEN THE ELEMENTS OFADJACENT SUB-SOURCES.</PARAM>
''' <PARAM NAME="INNERSEPARATOR">THE SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES.</PARAM>
''' <PARAM NAME="USEOUTERSEPARATOR">WHETHER TO INSERT <PARAMREF NAME="OUTERSEPARATOR"/> BETWEEN THE ELEMENTS OF THE LAST AND FIRST SUB-SOURCES.</PARAM>
''' <PARAM NAME="OUTERSEPARATOR">THE SEPARATOR BETWEEN ELEMENTS OF THE LAST AND FIRST SUB-SOURCE.</PARAM>
''' <PARAM NAME="WHILEANY">IF <SEE LANGWORD="TRUE"/>, THE ENUMERATION CONTINUES UNTIL EVERY GIVEN SUBSOURCE IS EMPTY;
''' IF <SEE LANGWORD="FALSE"/>, THE ENUMERATION STOPS AS SOON AS ANY ENUMERABLE NO LONGER HAS AN ELEMENT TO SUPPLY FOR THE NEXT PASS.</PARAM>
ITERATOR FUNCTION INTERLEAVED(OF T)(
SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),
OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,
OPTIONAL INNERSEPARATOR AS T = NOTHING,
OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,
OPTIONAL OUTERSEPARATOR AS T = NOTHING,
OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)
DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING
TRY
SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()
DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH
DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN
DIM ANYPREVITERS AS BOOLEAN = FALSE
DO
' INDICES OF FIRST AND LAST SUB-SOURCES THAT HAVE ELEMENTS.
DIM FIRSTACTIVE = -1, LASTACTIVE = -1
' DETERMINE WHETHER EACH SUB-SOURCE THAT STILL HAVE ELEMENTS.
FOR I = 0 TO NUMSOURCES - 1
ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()
IF ENUMERATORSTATES(I) THEN
IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I
LASTACTIVE = I
END IF
NEXT
' DETERMINE WHETHER TO YIELD ANYTHING IN THIS ITERATION BASED ON WHETHER WHILEANY IS TRUE.
' NOT YIELDING ANYTHING THIS ITERATION IMPLIES THAT THE ENUMERATION HAS ENDED.
DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)
IF NOT THISITERHASRESULTS THEN EXIT DO
' DON'T INSERT A SEPARATOR ON THE FIRST PASS.
IF ANYPREVITERS THEN
IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR
ELSE
ANYPREVITERS = TRUE
END IF
' GO THROUGH AND YIELD FROM THE SUB-SOURCES THAT STILL HAVE ELEMENTS.
FOR I = 0 TO NUMSOURCES - 1
IF ENUMERATORSTATES(I) THEN
' DON'T INSERT A SEPARATOR BEFORE THE FIRST ELEMENT.
IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR
YIELD SOURCEENUMERATORS(I).CURRENT
END IF
NEXT
LOOP
FINALLY
IF SOURCEENUMERATORS ISNOT NOTHING THEN
FOR EACH EN IN SOURCEENUMERATORS
EN.DISPOSE()
NEXT
END IF
END TRY
END FUNCTION
''' <SUMMARY>
''' RETURNS THE ROWS REPRESENTING ONE MONTH CELL WITHOUT TRAILING NEWLINES. APPROPRIATE LEADING AND TRAILING
''' WHITESPACE IS ADDED SO THAT EVERY ROW HAS THE LENGTH OF WIDTH.
''' </SUMMARY>
''' <PARAM NAME="DT">A DATE WITHIN THE MONTH TO REPRESENT.</PARAM>
''' <PARAM NAME="WIDTH">THE WIDTH OF THE CELL.</PARAM>
''' <PARAM NAME="HEIGHT">THE HEIGHT.</PARAM>
''' <PARAM NAME="VERTSTRETCH">IF <SEE LANGWORD="TRUE" />, BLANK ROWS ARE INSERTED TO FIT THE AVAILABLE HEIGHT.
''' OTHERWISE, THE CELL HAS A CONSTANT HEIGHT OF </PARAM>
''' <PARAM NAME="HORIZSTRETCH">IF <SEE LANGWORD="TRUE" />, THE SPACING BETWEEN INDIVIDUAL DAYS IS INCREASED TO
''' FIT THE AVAILABLE WIDTH. OTHERWISE, THE CELL HAS A CONSTANT WIDTH OF 20 CHARACTERS AND IS PADDED TO BE IN
''' THE CENTER OF THE EXPECTED WIDTH.</PARAM>
ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)
CONST DAY_WDT = 2 ' WIDTH OF A DAY.
CONST ALLDAYS_WDT = DAY_WDT * 7 ' WIDTH OF AL LDAYS COMBINED.
' NORMALIZE THE DATE TO JANUARY 1.
DT = NEW DATE(DT.YEAR, DT.MONTH, 1)
' HORIZONTAL WHITESPACE BETWEEN DAYS OF THE WEEK. CONSTANT OF 6 REPRESENTS 6 SEPARATORS PER LINE.
DIM DAYSEP AS NEW STRING(" "C, MATH.MIN((WIDTH - ALLDAYS_WDT) \ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))
' NUMBER OF BLANK LINES BETWEEN ROWS.
DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \ 7)
' WIDTH OF EACH DAY * 7 DAYS IN ONE ROW + DAY SEPARATOR LENGTH * 6 SEPARATORS PER LINE.
DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6
' THE WHITESPACE AT THE BEGINNING OF EACH LINE.
DIM LEFTPAD AS NEW STRING(" "C, (WIDTH - BLOCKWIDTH) \ 2)
' THE WHITESPACE FOR BLANK LINES.
DIM FULLPAD AS NEW STRING(" "C, WIDTH)
' LINES ARE "STAGED" IN THE STRINGBUILDER.
DIM SB AS NEW STRINGBUILDER(LEFTPAD)
DIM NUMLINES = 0
' GET THE CURRENT LINE SO FAR FORM THE STRINGBUILDER AND BEGIN A NEW LINE.
' RETURNS THE CURRENT LINE AND TRAILING BLANK LINES USED FOR VERTICAL PADDING (IF ANY).
' RETURNS EMPTY ENUMERABLE IF THE HEIGHT REQUIREMENT HAS BEEN REACHED.
DIM ENDLINE =
FUNCTION() AS IENUMERABLE(OF STRING)
DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)
SB.CLEAR()
SB.APPEND(LEFTPAD)
' USE AN INNER ITERATOR TO PREVENT LAZY EXECUTION OF SIDE EFFECTS OF OUTER FUNCTION.
RETURN IF(NUMLINES >= HEIGHT,
ENUMERABLE.EMPTY(OF STRING)(),
ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)
YIELD FINISHEDLINE
NUMLINES += 1
FOR I = 1 TO VERTBLANKCOUNT
IF NUMLINES >= HEIGHT THEN RETURN
YIELD FULLPAD
NUMLINES += 1
NEXT
END FUNCTION())
END FUNCTION
' YIELD THE MONTH NAME.
SB.APPEND(PADCENTER(DT.TOSTRING("MMMM", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())
FOR EACH L IN ENDLINE()
YIELD L
NEXT
' YIELD THE HEADER OF WEEKDAY NAMES.
DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())
SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))
FOR EACH L IN ENDLINE()
YIELD L
NEXT
' DAY OF WEEK OF FIRST DAY OF MONTH.
DIM STARTWKDY = CINT(DT.DAYOFWEEK)
' INITIALIZE WITH EMPTY SPACE FOR THE FIRST LINE.
DIM FIRSTPAD AS NEW STRING(" "C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)
SB.APPEND(FIRSTPAD)
DIM D = DT
DO WHILE D.MONTH = DT.MONTH
SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $"{{0,{DAY_WDT}}}", D.DAY)
' EACH ROW ENDS ON SATURDAY.
IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN
FOR EACH L IN ENDLINE()
YIELD L
NEXT
ELSE
SB.APPEND(DAYSEP)
END IF
D = D.ADDDAYS(1)
LOOP
' KEEP ADDING EMPTY LINES UNTIL THE HEIGHT QUOTA IS MET.
DIM NEXTLINES AS IENUMERABLE(OF STRING)
DO
NEXTLINES = ENDLINE()
FOR EACH L IN NEXTLINES
YIELD L
NEXT
LOOP WHILE NEXTLINES.ANY()
END FUNCTION
''' <SUMMARY>
''' RETURNS A NEW STRING THAT CENTER-ALIGNS THE CHARACTERS IN THIS STRING BY PADDING TO THE LEFT AND RIGHT WITH
''' THE SPECIFIED CHARACTER TO A SPECIFIED TOTAL LENGTH.
''' </SUMMARY>
''' <PARAM NAME="S">THE STRING TO CENTER-ALIGN.</PARAM>
''' <PARAM NAME="TOTALWIDTH">THE NUMBER OF CHARACTERS IN THE RESULTING STRING.</PARAM>
''' <PARAM NAME="PADDINGCHAR">THE PADDING CHARACTER.</PARAM>
<EXTENSION()>
PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = " "C) AS STRING
RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)
END FUNCTION
END MODULE |
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.
| #Go | Go | noArgs() |
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
| #Maple | Maple | CatalanNumbers := proc( n::posint )
return seq( (2*i)!/((i + 1)!*i!), i = 0 .. n - 1 );
end proc:
CatalanNumbers(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
| #Racket | Racket | #lang racket/base
(require racket/match)
(define (merge-lists as . bss)
(match bss
['() as]
[(cons b bt)
(apply merge-lists
(for*/list ((a (in-list as)) (b (in-list b))) (append a b))
bt)]))
(define (get-item cs depth)
(let loop ((out '(())) (cs cs))
(match cs
['() (values out cs)]
[`(,(or #\, #\}) . ,more) #:when (positive? depth) (values out cs)]
[`(#\{ . ,more)
(=> no-group-match)
(define-values (group-out group-rem) (get-group more (add1 depth) no-group-match))
(loop (merge-lists out group-out) group-rem)]
[(or `(#\\ ,c ,more ...) `(,c . ,more)) (loop (merge-lists out (list (list c))) more)])))
(define (get-group cs depth no-group-match)
(let loop ((out '()) (cs cs) (comma? #f))
(when (null? cs) (no-group-match))
(define-values (item-out item-rem) (get-item cs depth))
(when (null? item-rem) (no-group-match))
(let ((out (append out item-out)))
(match item-rem
[`(#\} . ,more) #:when comma? (values out more)]
[`(#\} . ,more) (values (merge-lists '((#\{)) out '((#\}))) more)]
[`(#\, . ,more) (loop out more #t)]
[_ (no-group-match)]))))
(define (brace-expand s)
(let-values (([out rem] (get-item (string->list s) 0))) (map list->string out)))
(module+ test
(define patterns
(list
"~/{Downloads,Pictures}/*.{jpg,gif,png}"
"It{{em,alic}iz,erat}e{d,}, please."
#<<P
{,{,gotta have{ ,\, again\, }}more }cowbell!
P
#<<P
{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}
P
))
(for ((s (in-list patterns)) #:when (printf "expand: ~a~%" s) (x (in-list (brace-expand s))))
(printf "\t~a~%" x))) |
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
| #Raku | Raku | grammar BraceExpansion {
token TOP { ( <meta> | . )* }
token meta { '{' <alts> '}' | \\ . }
token alts { <alt>+ % ',' }
token alt { ( <meta> | <-[ , } ]> )* }
}
sub crosswalk($/) {
|[X~] flat '', $0.map: -> $/ { $<meta><alts><alt>.&alternatives or ~$/ }
}
sub alternatives($_) {
when :not { () }
when 1 { '{' X~ $_».&crosswalk X~ '}' }
default { $_».&crosswalk }
}
sub brace-expand($s) { crosswalk BraceExpansion.parse($s) }
# Testing:
sub bxtest(*@s) {
for @s -> $s {
say "\n$s";
for brace-expand($s) {
say " ", $_;
}
}
}
bxtest Q:to/END/.lines;
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
a{b{1,2}c
a{1,2}b}c
a{1,{2},3}b
more{ darn{ cowbell,},}
ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr
{a,{\,b}c
a{b,{{c}}
{a{\}b,c}d
END |
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
| #Julia | Julia | using Primes, Lazy
function samedigits(n, b)
n, f = divrem(n, b)
while n > 0
n, f2 = divrem(n, b)
if f2 != f
return false
end
end
true
end
isbrazilian(n) = n >= 7 && (iseven(n) || any(b -> samedigits(n, b), 2:n-2))
brazilians = filter(isbrazilian, Lazy.range())
oddbrazilians = filter(n -> isodd(n) && isbrazilian(n), Lazy.range())
primebrazilians = filter(n -> isprime(n) && isbrazilian(n), Lazy.range())
println("The first 20 Brazilian numbers are: ", take(20, brazilians))
println("The first 20 odd Brazilian numbers are: ", take(20, oddbrazilians))
println("The first 20 prime Brazilian numbers are: ", take(20, primebrazilians))
|
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
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
printCalendar(\A[1]|1969)
end
procedure printCalendar(year) #: Print a 3 column x 80 char calendar
cols := 3 # fixed width
mons := [] # table of months
"January February March April May June " ||
"July August September October November December " ?
while put(mons, tab(find(" "))) do move(1)
write(center("[Snoopy Picture]",cols * 24 + 4)) # mandatory ..
write(center(year,cols * 24 + 4), "\n") # ... headers
M := list(cols) # coexpr container
every mon := 0 to 9 by cols do { # go through months by cols
writes(" ")
every i := 1 to cols do {
writes(center(mons[mon+i],24)) # header months
M[i] := create CalendarFormatWeek(year,mon + i) # formatting coexpr
}
write()
every 1 to 7 do { # 1 to max rows
every c := 1 to cols do { # for each column
writes(" ")
every 1 to 7 do writes(right(@M[c],3)) # each row day element
}
write()
}
}
return
end
link datetime
procedure CalendarFormatWeek(year,m) #: Format Week for Calendar
static D
initial D := [31,28,31,30,31,30,31,31,30,31,30,31]
every suspend "Su"|"Mo"|"Tu"|"We"|"Th"|"Fr"|"Sa" # header
every 1 to (d := (julian(m,1,year)+1)%7) do suspend "" # lead day alignment
every suspend 1 to D[m] do d +:= 1 # days
if m = 2 & IsLeapYear(year) then suspend (d +:= 1, 29) # LY adjustment
every d to (6*7) do suspend "" # trailer alignment
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.
| #Lua | Lua | function SetSeed( f )
for i = 1, #f[1] do -- the whole boundary of the scene is used as the seed
f[1][i] = 1
f[#f][i] = 1
end
for i = 1, #f do
f[i][1] = 1
f[i][#f[1]] = 1
end
end
function SetParticle( f )
local pos_x, pos_y
repeat
pos_x = math.random( #f )
pos_y = math.random( #f[1] )
until f[pos_x][pos_y] == 0
return pos_x, pos_y
end
function Iterate( f, num_particles )
for i = 1, num_particles do
local pos_x, pos_y = SetParticle( f )
while true do
local dx = math.random(5) - 3
local dy = math.random(5) - 3
if ( pos_x+dx >= 1 and pos_x+dx <= #f and pos_y+dy >= 1 and pos_y+dy <= #f[1] ) then
if f[pos_x+dx][pos_y+dy] ~= 0 then
f[pos_x][pos_y] = 1
break
else
pos_x = pos_x + dx
pos_y = pos_y + dy
end
end
end
end
end
size_x, size_y = 400, 400 -- size of the scene
num_particles = 16000
math.randomseed( os.time() )
f = {}
for i = 1, size_x do
f[i] = {}
for j = 1, size_y do
f[i][j] = 0
end
end
SetSeed( f )
Iterate( f, num_particles )
-- prepare the data for writing into a ppm-image file
for i = 1, size_x do
for j = 1, size_y do
if f[i][j] == 1 then f[i][j] = 255 end
end
end
Write_PPM( "brownian_tree.ppm", ConvertToColorImage(f) ) |
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
| #Erlang | Erlang | -module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).
% generate the secret code
generate_secret() -> generate_secret([], 4, lists:seq(1,9)).
generate_secret(Secret, 0, _) -> Secret;
generate_secret(Secret, N, Digits) ->
Next = lists:nth(random:uniform(length(Digits)), Digits),
generate_secret(Secret ++ [Next], N - 1, Digits -- [Next]).
% evaluate a guess
score_guess(Secret, Guess)
when length(Secret) =/= length(Guess) -> throw(badguess);
score_guess(Secret, Guess) ->
Bulls = count_bulls(Secret,Guess),
Cows = count_cows(Secret, Guess, Bulls),
[Bulls, Cows].
% count bulls (exact matches)
count_bulls(Secret, Guess) ->
length(lists:filter(fun(I) -> lists:nth(I,Secret) == lists:nth(I,Guess) end,
lists:seq(1, length(Secret)))).
% count cows (digits present but out of place)
count_cows(Secret, Guess, Bulls) ->
length(lists:filter(fun(I) -> lists:member(I, Guess) end, Secret)) - Bulls.
% play a game
play() -> play_round(generate_secret()).
play_round(Secret) -> play_round(Secret, read_guess()).
play_round(Secret, Guess) ->
play_round(Secret, Guess, score_guess(Secret,Guess)).
play_round(_, _, [4,0]) ->
io:put_chars("Correct!\n");
play_round(Secret, _, Score) ->
io:put_chars("\tbulls:"), io:write(hd(Score)), io:put_chars(", cows:"),
io:write(hd(tl(Score))), io:put_chars("\n"), play_round(Secret).
read_guess() ->
lists:map(fun(D)->D-48 end,
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)). |
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
| #Cubescript | Cubescript | alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
//Cubescript's built-in mod will fail on negative numbers
alias cipher [
push alpha [
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
"a b c d e f g h i j k l m n o p q r s t u v w x y z"
] [ push chars [] [
loop i (strlen $arg1) [
looplist n $alpha [
if (! (listlen $chars)) [
alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n [])
]
]
alias arg1 (
concatword (substr $arg1 0 $i) (
? (> (listindex $chars (substr $arg1 $i 1)) -1) (
at $chars (
modn (+ (
listindex $chars (substr $arg1 $i 1)
) $arg2) (listlen $chars)
)
) (substr $arg1 $i 1)
) (substr $arg1 (+ $i 1) (strlen $arg1))
)
alias chars []
]
] ]
result $arg1
]
alias decipher [
push alpha [
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
"a b c d e f g h i j k l m n o p q r s t u v w x y z"
] [ push chars [] [
loop i (strlen $arg1) [
looplist n $alpha [
if (! (listlen $chars)) [
alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n [])
]
]
alias arg1 (
concatword (substr $arg1 0 $i) (
? (> (listindex $chars (substr $arg1 $i 1)) -1) (
at $chars (
modn (- (
listindex $chars (substr $arg1 $i 1)
) $arg2 ) (listlen $chars)
)
) (substr $arg1 $i 1)
) (substr $arg1 (+ $i 1) (strlen $arg1))
)
alias chars []
]
] ]
result $arg1
] |
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
| #Processing | Processing | void setup() {
double e = 0;
long factorial = 1;
for (int i = 0; i < 11; i++) {
e += (double) (2 * i + 1) / factorial;
factorial *= (2 * i + 1) * (2 * i + 2);
}
println("After 11 iterations");
println("Computed value: " + e);
println("Real value: " + Math.E);
println("Error: " + (e - Math.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
| #Prolog | Prolog |
% Calculate the value e = exp 1
% Use Newton's method: x0 = 2; y = x(2 - ln x)
tolerance(1e-15).
exp1_iter(L) :-
lazy_list(newton, 2, L).
newton(X0, X1, X1) :-
X1 is X0*(2 - log(X0)).
e([X1, X2|_], X1) :- tolerance(Eps), abs(X2 - X1) < Eps.
e([_|Xs], E) :- e(Xs, E).
main :-
exp1_iter(Iter),
e(Iter, E),
format("e = ~w~n", [E]),
halt.
?- main.
|
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Scala | Scala |
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
}
def nextGuess(possible: Seq[List[Byte]]): List[Byte] = possible match {
case Nil => throw new IllegalStateException
case List(only) => only
case _ => possible(Random.nextInt(possible.size))
}
def doGuess(guess: List[Byte]): Pair[Int, Int] = {
println("My guess is " + guess);
val arr = readLine().split(' ').map(Integer.valueOf(_))
(arr(0), arr(1))
}
def testGuess(alt: List[Byte], guess: List[Byte]): Pair[Int, Int] = {
val bulls =alt.zip(guess).filter(p => p._1 == p._2).size
val cows = guess.filter(alt.contains(_)).size - bulls
(bulls, cows)
}
def play(possible: Seq[List[Byte]]): List[Byte] = {
val curGuess = nextGuess(possible)
val bc = doGuess(curGuess)
if (bc._1 == 4) { println("Ye-haw!"); curGuess }
else
play(possible.filter(p => testGuess(p, curGuess) == bc))
}
def main(args: Array[String]) {
play(allCombinations)
}
|
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.
| #Wren | Wren | IMPORT "/DATE" FOR DATE
IMPORT "/FMT" FOR FMT
IMPORT "/SEQ" FOR LST
VAR CALENDAR = FN.NEW { |YEAR|
VAR SNOOPY = "🐶"
VAR DAYS = "SU MO TU WE TH FR SA"
VAR MONTHS = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
]
FMT.PRINT("$70M", SNOOPY)
VAR YEARSTR = "--- %(YEAR) ---"
FMT.PRINT("$70M\N", YEARSTR)
VAR FIRST = LIST.FILLED(3, 0)
VAR MLEN = LIST.FILLED(3, 0)
VAR C = 0
FOR (CHUNK IN LST.CHUNKS(MONTHS, 3)) {
FOR (I IN 0..2) FMT.WRITE("$20M ", CHUNK[I])
SYSTEM.PRINT()
FOR (I IN 0..2) SYSTEM.WRITE("%(DAYS) ")
SYSTEM.PRINT()
FIRST[0] = DATE.NEW(YEAR, C*3 + 1, 1).DAYOFWEEK % 7
FIRST[1] = DATE.NEW(YEAR, C*3 + 2, 1).DAYOFWEEK % 7
FIRST[2] = DATE.NEW(YEAR, C*3 + 3, 1).DAYOFWEEK % 7
MLEN[0] = DATE.MONTHLENGTH(YEAR, C*3 + 1)
MLEN[1] = DATE.MONTHLENGTH(YEAR, C*3 + 2)
MLEN[2] = DATE.MONTHLENGTH(YEAR, C*3 + 3)
FOR (I IN 0..5) {
FOR (J IN 0..2) {
VAR START = 1 + 7 * I - FIRST[J]
FOR (K IN START..START+6) {
IF (K >= 1 && K <= MLEN[J]) {
FMT.WRITE("$2D ", K)
} ELSE {
SYSTEM.WRITE(" ")
}
}
SYSTEM.WRITE(" ")
}
SYSTEM.PRINT()
}
SYSTEM.PRINT()
C = C + 1
}
}
CALENDAR.CALL(1969) |
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.
| #Groovy | Groovy | noArgs() |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CatalanN[n_Integer /; n >= 0] := (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
| #REXX | REXX | /*- REXX --------------------------------------------------------------
* Brace expansion
* 26.07.2016
* s.* holds the set of strings
*--------------------------------------------------------------------*/
text.1='{,{,gotta have{ ,\, again\, }}more }cowbell!'
text.2='~/{Downloads,Pictures}/*.{jpg,gif,png}'
text.3='It{{em,alic}iz,erat}e{d,}, please. '
text.4='{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\} '
text.5='x{,a,b,c}{d,e}y'
text.6='aa{,{,11}cc}22'
text.7='{}'
Parse Arg dbg
oid='brace.xxx'; 'erase' oid
Do case=1 To 7
Call brac text.case
End
Return
brac:
s.=0
Parse Arg s
Say ''
Say ' 's
s.1.0=1 /* first iteration */
s.1.1=s /* the initial string */
Do it=1 To 10 Until todo=0 /* Iterate until all done */
todo=0 /* will be 1 if more to be done */
Call dbg 'Iteration' it
do di=1 To s.it.0 /* show current state */
Call dbg 's.'it'.'di s.it.di
End
ita=it+1 /* index for next set of strings*/
xp=0
do di=1 To s.it.0 /* loop over all strings */
Call dbg it'.'di s.it.di
Call bra s.it.di /* analyze current string */
If braces=1 Then Do /* If brace groups were found */
Do bgi=1 To bgdata.0 /* loop over grace groups */
If end.bgi=0 Then Iterate /* Incomplete bg (... ) */
clist=''
Do cj=1 To ci.bgi.0
clist=clist ci.bgi.cj
End
Call dbg bgdata.bgi '->' clist
If ccount.bgi>0 Then Do /* comma(s) founf in bg */
Call expand bgi /* expand this bg */
xp=1 /* indicate that we worked */
Leave
End
End
If xp=0 Then Do /* nothing done */
z=s.ita.0+1 /* copy string to next iteration*/
s.ita.z=s.it.di
End
End
Else Do /* no brace group */
z=s.ita.0+1 /* copy string to next iteration*/
s.ita.z=s
s.ita.0=z
End
End
Do dd=1 To s.ita.0 /* log current set of strings */
Call dbg ita dd s.ita.dd
End
End
Do dd=1 To s.it.0 /* show final set of strings */
Say dd s.it.dd
End
Return
bra:
/*---------------------------------------------------------------------
* Analyze the given string
* Input: s
* Output:
* bgdata.* Array of data about brace groups:
* level start column comma positions end column
*--------------------------------------------------------------------*/
parse Arg s
Call dbg 'bra:' s
level=0
bgdata.=0
bgn=0
bgnmax=0
ccount.=0
ol=''
ci.=0
bgnl=''
braces=0
end.=0
escape=0
Do i=1 To length(s)
c=substr(s,i,1)
Select
When escape Then
escape=0
When c='\' Then
escape=1
When c='{' Then Do
level=level+1
Call bm c
co=level
End
When c='}' Then Do
If level>0 Then Do
co=level
Call bm c
level=level-1
End
End
When c=',' Then Do
co=level
If co>0 Then Do
ccount.bgn=ccount.bgn+1
z=ccount.bgn
ci.bgn.0=z
ci.bgn.z=i
End
If ccount.bgn>0 Then
braces=1
End
Otherwise
co=level
End
ol=ol||co
bgnl=bgnl||bgn
End
Call dbg s
Call dbg ol
Call dbg left(copies('123456789.',10),length(s))
Call dbg bgnl
Do bgi=1 To bgdata.0
If end.bgi=1 Then Do
cl=''
Do cii=1 To ci.bgi.0
cl=cl ci.bgi.cii
End
Parse Var bgdata.bgi level a e
Call dbg bgi level a cl e
End
End
Return
bm:
/*---------------------------------------------------------------------
* Brace Management
* for '{' create a new brace group )record level and start column
* for '}' look for corresponding bg and add end column
* Input: column and character ( '{' or '}' )
* Output: bgdata.* level start-column [end-column]
*--------------------------------------------------------------------*/
Parse Arg oc
Call dbg oc i level
If oc='{' Then Do
z=bgdata.0+1
bgdata.z=level i
bgdata.0=z
bgn=bgnmax+1
bgnmax=bgn
End
Else Do
Do bgi=bgdata.0 To 1 By -1
If level=word(bgdata.bgi,1) Then Do
bgdata.bgi=bgdata.bgi i
end.bgi=1
Leave
End
End
bgn=bgn-1
Call dbg bgdata.bgi 'bgn='bgn
End
Return
expand:
/*---------------------------------------------------------------------
* Expand a brace group in string s
*--------------------------------------------------------------------*/
Parse Arg bgi
Parse Var bgdata.bgi . start end
clist=start clist end
If words(clist)>0 Then Do /* commas in brace group */
left=left(s,start-1) /* part of s before the '{' */
rite=substr(s,end+1) /* part of s after the '}' */
Do k=1 To words(clist)-1 /* Loop over comma positions */
a=word(clist,k) /* start position */
e=word(clist,k+1) /* end position */
choice.k=substr(s,a+1,e-a-1) /* one of the choices */
z=s.ita.0+1 /* add new string to next set */
s.ita.z=left||choice.k||rite /* construct new string */
s.ita.0=z
todo=1 /* maybe more to be done */
End
End
Else Do /* no commas */
z=s.ita.0+1 /* copy string as is to next set*/
s.ita.z=s
s.ita.0=z
End
Do zz=1 To s.ita.0
Call dbg zz s.ita.zz
End
Return
dbg: /* handle debug output */
If dbg<>'' Then /* argument given */
Say arg(1) /* show on screen */
Call lineout oid,arg(1) /* write to file */
Return |
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
| #Kotlin | Kotlin | fun sameDigits(n: Int, b: Int): Boolean {
var n2 = n
val f = n % b
while (true) {
n2 /= b
if (n2 > 0) {
if (n2 % b != f) {
return false
}
} else {
break
}
}
return true
}
fun isBrazilian(n: Int): Boolean {
if (n < 7) return false
if (n % 2 == 0) return true
for (b in 2 until n - 1) {
if (sameDigits(n, b)) {
return true
}
}
return false
}
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun main() {
val bigLim = 99999
val limit = 20
for (kind in ",odd ,prime".split(',')) {
var quiet = false
println("First $limit ${kind}Brazilian numbers:")
var c = 0
var n = 7
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) print("%,d ".format(n))
if (++c == limit) {
print("\n\n")
quiet = true
}
}
if (quiet && kind != "") continue
when (kind) {
"" -> n++
"odd " -> n += 2
"prime" -> {
while (true) {
n += 2
if (isPrime(n)) break
}
}
}
}
if (kind == "") println("The %,dth Brazilian number is: %,d".format(bigLim + 1, n))
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #J | J | require 'dates format' NB. J6.x
require 'dates general/misc/format' NB. J7.x
calBody=: (1 1 }. _1 _1 }. ":)@(-@(<.@%&22)@[ ]\ calendar@])
calTitle=: (<: - 22&|)@[ center '[Insert Snoopy here]' , '' ,:~ ":@]
formatCalendar=: calTitle , calBody |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | canvasdim = 1000;
n = 0.35*canvasdim^2;
canvas = ConstantArray[0, {canvasdim, canvasdim}];
init = Floor@(0.5*{canvasdim, canvasdim}); (*RandomInteger[canvasdim,2]*)
canvas[[init[[1]], init[[2]]]] = 1; (*1st particle initialized to midpoint*)
Monitor[ (*Provides real-time intermediate result monitoring*)
Do[
particle = RandomInteger[canvasdim, 2];
While[True,
ds = RandomInteger[{-1, 1}, 2];
While[ (*New Particle Domain Limit Section*)
!And @@ (0 < (particle + ds)[[#]] <= canvasdim & /@ {1, 2}),
particle = RandomInteger[canvasdim, 2];
];
(* Particle Aggregation Section *)
If[canvas[[(particle + ds)[[1]], (particle + ds)[[2]]]] > 0,
canvas[[particle[[1]], particle[[2]]]] = i;
Break[],
particle += ds
];
],
{i, n}],
{i, (particle + ds), MatrixPlot@canvas}
]
MatrixPlot[canvas,FrameTicks->None,ColorFunction->"DarkRainbow",ColorRules->{0 -> None}] |
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
| #Euphoria | Euphoria | include std\text.e
include std\os.e
include std\sequence.e
include std\console.e
sequence bcData = {0,0} --bull,cow score for the player
sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow
--indexes in element 2, integer value of it in element 3
sequence currentGuess = { {0,0,0,0}, {0,0,0,0}, 0} --player's guess, same format as goalNum
sequence removeChars = 0 & " 0\r\t\n" --characters to trim (remove) from user's input. \r, \t are single escaped characters,
--0 is ascii 0x0 and number zero is ascii 48, or 0x30. The rest are wysiwyg
integer tries = 0 --track number of tries to guess the number
sequence bcStrings ={"bull", "cow"} --stores singular and/or plural strings depending on score in bcData
goalNum[1] = rand( {9,9,9,9} ) --rand function works on objects. here it outputs into each sequence element.
goalNum[3] = goalNum[1][1] * 1000 + goalNum[1][2] * 100 + goalNum[1][3] * 10 + goalNum[1][4] --convert digits to an integer
--and store it
procedure getInputAndProcess(integer stage = 1) --object = 1 sets default value for the parameter if it isn't specified
goalNum[2][1..4] = 0 --{0,0,0,0} --set these to unscaned (0) since the scanning will start over.
currentGuess[1][1..4] = 0 --{0,0,0,0} --these too, or they will contain old marks
currentGuess[2][1..4] = 0
tries += 1 --equivalent to tries = tries + 1, but faster and shorter to write
bcData[1..2] = 0 -- {0,0}
if stage <= 1 then --if this process was run for the first time or with no parameters, then..
puts(1,"The program has thought of a four digit number using only digits 1 to 9.\nType your guess and press enter.\n")
end if
while 1 label "guesscheck" do --labels can be used to specify a jump point from exit or retry, and help readability
currentGuess[1] = trim(gets(0), removeChars) --get user input, trim unwanted characters from it, store it in currentGuess[1]
currentGuess[1] = mapping( currentGuess[1], {49,50,51,52,53,54,55,56,57}, {1,2,3,4,5,6,7,8,9} ) --convert ascii codes to
-- integer digits they represent
integer tempF = find('0',currentGuess[1])
if length(currentGuess[1]) != 4 or tempF != 0 then --if the input string is now more than 4 characters/integers,
--the input won't be used.
puts(1,"You probably typed too many digits or a 0. Try typing a new 4 digit number with only numbers 1 through 9.\n")
retry "guesscheck"
else
exit "guesscheck"
end if
end while
--convert separate digits to the one integer they represent and store it, like with goalNum[3]
currentGuess[3] = currentGuess[1][1] * 1000 + currentGuess[1][2] * 100 + currentGuess[1][3] * 10 + currentGuess[1][4]
--convert digits to the integer they represent, to print to a string later
--check for bulls
for i = 1 to 4 do
if goalNum[1][i] = currentGuess[1][i] then
goalNum[2][i] = 1
currentGuess[2][i] = 1
bcData[1] += 1
end if
end for
--check for cows, but not slots marked as bulls or cows already.
for i = 1 to 4 label "iGuessElem"do --loop through each guessed digit
for j = 1 to 4 label "jGoalElem" do --but first go through each goal digit, comparing the first guessed digit,
--and then the other guessed digits 2 through 4
if currentGuess[2][i] = 1 then --if the guessed digit we're comparing right now has been marked as bull or cow already
continue "iGuessElem" --skip to the next guess digit without comparing this guess digit to the other goal digits
end if
if goalNum[2][j] = 1 then --if the goal digit we're comparing to right now has been marked as a bull or cow already
continue "jGoalElem" --skip to the next goal digit
end if
if currentGuess[1][i] = goalNum[1][j] then --if the guessed digit is the same as the goal one,
--it won't be a bull, so it's a cow
bcData[2] += 1 --score one more cow
goalNum[2][j] = 1 --mark this digit as a found cow in the subsequence that stores 0's or 1's as flags
continue "iGuessElem" --skip to the next guess digit, so that this digit won't try to check for
--matches(cow) with other goal digits
end if
end for --this guess digit was compared to one goal digit , try comparing this guess digit with the next goal digit
end for --this guess digit was compared with all goal digits, compare the next guess digit to all the goal digits
if bcData[1] = 1 then --uses singular noun when there is score of 1, else plural
bcStrings[1] = "bull"
else
bcStrings[1] = "bulls"
end if
if bcData[2] = 1 then --the same kind of thing as above block
bcStrings[2] = "cow"
else
bcStrings[2] = "cows"
end if
if bcData[1] < 4 then --if less than 4 bulls were found, the player hasn't won, else they have...
printf(1, "Guess #%d : You guessed %d . You found %d %s, %d %s. Type new guess.\n", {tries, currentGuess[3], bcData[1], bcStrings[1], bcData[2], bcStrings[2]} )
getInputAndProcess(2)
else --else they have won and the procedure ends
printf(1, "The number was %d. You guessed %d in %d tries.\n", {goalNum[3], currentGuess[3], tries} )
any_key()--wait for keypress before closing console window.
end if
end procedure
--run the procedure
getInputAndProcess(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
| #D | D | import std.stdio, std.traits;
S rot(S)(in S s, in int key) pure nothrow @safe
if (isSomeString!S) {
auto res = s.dup;
foreach (immutable i, ref c; res) {
if ('a' <= c && c <= 'z')
c = ((c - 'a' + key) % 26 + 'a');
else if ('A' <= c && c <= 'Z')
c = ((c - 'A' + key) % 26 + 'A');
}
return res;
}
void main() @safe {
enum key = 3;
immutable txt = "The five boxing wizards jump quickly";
writeln("Original: ", txt);
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - 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
| #PureBasic | PureBasic | Define f.d=1.0, e.d=1.0, e0.d=e, n.i=1
LOOP:
f*n : e+1.0/f
If e-e0>=1.0e-15 : e0=e : n+1 : Goto LOOP : EndIf
Debug "e="+StrD(e,15) |
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
| #Python | Python | import math
#Implementation of Brother's formula
e0 = 0
e = 2
n = 0
fact = 1
while(e-e0 > 1e-15):
e0 = e
n += 1
fact *= 2*n*(2*n+1)
e += (2.*n+2)/fact
print "Computed e = "+str(e)
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n) |
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)
| #SenseTalk | SenseTalk | set the remoteWorkInterval to .001 -- optional
repeat forever
repeat forever
set description to "Enter a 4 digit number" & newline & "- zero's excluded" & newline & "- each digit should be unique" & newline
Ask "Enter a Number" title "Bulls & Cows (Player)" message description
put it into num
if num is ""
Answer "" with "Play" or "Quit" title "Quit Bulls & Cows (Player)?"
if it is "Quit"
exit all
end if
end if
set startTime to now
if number of characters in num is 4
if character 1 of num is not equal to character 2 of num
if character 1 of num is not equal to character 3 of num
if character 1 of num is not equal to character 4 of num
if character 2 of num is not equal to character 3 of num
if character 2 of num is not equal to character 4 of num
if character 3 of num is not equal to character 4 of num
if num does not contain 0
exit repeat
end if
end if
end if
end if
end if
end if
end if
end if
end repeat
set guess to 1111
set lastBullQty to 0
set digitLocation to 1
set cowVals to empty
repeat forever
set score to {
bulls: {
qty: 0,
values: {}
},
cows: {
qty: 0,
values: {}
}
}
repeat the number of characters in num times
if character the counter of guess is equal to character the counter of num
add 1 to score.bulls.qty
insert character the counter of guess into score.bulls.values
else
if num contains character the counter of guess
if character the counter of guess is not equal to character the counter of num
if score.bulls.values does not contain character the counter of guess and score.cows.values does not contain character the counter of guess
add 1 to score.cows.qty
if cowVals.(character the counter of guess) is empty
set cowVals.(character the counter of guess) to false
end if
end if
end if
end if
end if
end repeat
if guess is equal to num
put now - startTime into elapsedTime
set displayMessage to "Your Number:" && num & newline & "Guessed Number:" && guess & newline & newline & "Time Elapsed:" && elapsedTime.seconds && seconds
Answer displayMessage with "Play Again" or "Quit" title "Done!"
if it is "Quit"
exit all
end if
exit repeat
else
if the counter is greater than 1
if score.bulls.qty is not lastBullQty
if score.bulls.qty is greater than lastBullQty
if digitLocation is not 4 -- move on to the next digit
add 1 to digitLocation
else
set digitLocation to 1
end if
repeat for each (key,value) in cowVals
if score.bulls.values contains key
set cowVals.(key) to "bull"
else
set cowVals.(key) to false
end if
end repeat
else
subtract 1 from character digitLocation of guess -- stay on current digit
end if
set lastBullQty to score.bulls.qty -- save bull qty
else -- score.bulls.qty = lastBullQty
set cow_guessed to false
if cowVals is not empty
repeat for each (key,value) in cowVals
if value is false
set cow_guessed to true
set cowVals.(key) to true
if digitLocation is not 1
set character digitLocation of guess to key
exit repeat
else
add 1 to character digitLocation of guess
exit repeat
end if
end if
end repeat
if cow_guessed is false
if character digitLocation of guess is greater than 9
set character digitLocation of guess to 0 -- reset the current digit
end if
add 1 to character digitLocation of guess -- increment the current digit
end if
else
add 1 to character digitLocation of guess -- increment the current digit
end if
end if
end if
end if
end repeat
end repeat |
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.
| #X86_Assembly | X86 Assembly | .MODEL TINY
.CODE
.486
ORG 100H ;.COM FILES START HERE
YEAR EQU 1969 ;DISPLAY CALENDAR FOR SPECIFIED YEAR
START: MOV CX, 61 ;SPACE(61); TEXT(0, "[SNOOPY]"); CRLF(0)
CALL SPACE
MOV DX, OFFSET SNOOPY
CALL TEXT
MOV CL, 63 ;SPACE(63); INTOUT(0, YEAR); CRLF(0); CRLF(0)
CALL SPACE
MOV AX, YEAR
CALL INTOUT
CALL CRLF
CALL CRLF
MOV DI, 1 ;FOR MONTH:= 1 TO 12 DO DI=MONTH
L22: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL
L23: MOV CL, 5 ; SPACE(5)
CALL SPACE
MOV DX, DI ; TEXT(0, MONAME(MONTH+COL-1)); SPACE(7);
DEC DX ; DX:= (MONTH+COL-1)*10+MONAME
ADD DX, SI
IMUL DX, 10
ADD DX, OFFSET MONAME
CALL TEXT
MOV CL, 7
CALL SPACE
CMP SI, 5 ; IF COL<5 THEN SPACE(1);
JGE L24
MOV CL, 1
CALL SPACE
INC SI
JMP L23
L24: CALL CRLF
MOV SI, 6 ; FOR COL:= 0 TO 6-1 DO
L25: MOV DX, OFFSET SUMO ; TEXT(0, "SU MO TU WE TH FR SA");
CALL TEXT
DEC SI ; IF COL<5 THEN SPACE(2);
JE L27
MOV CL, 2
CALL SPACE
JMP L25
L27: CALL CRLF
XOR SI, SI ;FOR COL:= 0 TO 6-1 DO
L28: MOV BX, DI ;DAY OF FIRST SUNDAY OF MONTH (CAN BE NEGATIVE)
ADD BX, SI ;DAY(COL):= 1 - WEEKDAY(YEAR, MONTH+COL, 1);
MOV BP, YEAR
;DAY OF WEEK FOR FIRST DAY OF THE MONTH (0=SUN 1=MON..6=SAT)
CMP BL, 2 ;IF MONTH<=2 THEN
JG L3
ADD BL, 12 ; MONTH:= MONTH+12;
DEC BP ; YEAR:= YEAR-1;
L3:
;REM((1-1 + (MONTH+1)*26/10 + YEAR + YEAR/4 + YEAR/100*6 + YEAR/400)/7)
INC BX ;MONTH
IMUL AX, BX, 26
MOV CL, 10
CWD
IDIV CX
MOV BX, AX
MOV AX, BP ;YEAR
ADD BX, AX
SHR AX, 2
ADD BX, AX
MOV CL, 25
CWD
IDIV CX
IMUL DX, AX, 6 ;YEAR/100*6
ADD BX, DX
SHR AX, 2 ;YEAR/400
ADD AX, BX
MOV CL, 7
CWD
IDIV CX
NEG DX
INC DX
MOV [SI+DAY], DL ;COL+DAY
INC SI
CMP SI, 5
JLE L28
MOV BP, 6 ;FOR LINE:= 0 TO 6-1 DO BP=LINE
L29: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL
L30: MOV BX, DI ; DAYMAX:= DAYS(MONTH+COL);
MOV BL, [BX+SI+DAYS]
;IF MONTH+COL=2 & (REM(YEAR/4)=0 & REM(YEAR/100)#0 ! REM(YEAR/400)=0) THEN
MOV AX, DI ;MONTH
ADD AX, SI
CMP AL, 2
JNE L32
MOV AX, YEAR
TEST AL, 03H
JNE L32
MOV CL,100
CWD
IDIV CX
TEST DX, DX
JNE L31
TEST AL, 03H
JNE L32
L31: INC BX ;IF FEBRUARY AND LEAP YEAR THEN ADD A DAY
L32:
MOV DX, 7 ;FOR WEEKDAY:= 0 TO 7-1 DO
L33: MOVZX AX, [SI+DAY] ; IF DAY(COL)>=1 & DAY(COL)<=DAYMAX THEN
CMP AL, 1
JL L34
CMP AL, BL
JG L34
CALL INTOUT ; INTOUT(0, DAY(COL));
CMP AL, 10 ; IF DAY(COL)<10 THEN SPACE(1); LEFT JUSTIFY
JGE L36
MOV CL, 1
CALL SPACE
JMP L36
L34: MOV CL, 2 ; ELSE SPACE(2);
CALL SPACE ; SUPPRESS OUT OF RANGE DAYS
L36: MOV CL, 1 ; SPACE(1);
CALL SPACE
INC BYTE PTR [SI+DAY] ; DAY(COL):= DAY(COL)+1;
DEC DX ;NEXT WEEKDAY
JNE L33
CMP SI, 5 ;IF COL<5 THEN SPACE(1);
JGE L37
MOV CL, 1
CALL SPACE
INC SI
JMP L30
L37: CALL CRLF
DEC BP ;NEXT LINE DOWN
JNE L29
CALL CRLF
ADD DI, 6 ;NEXT 6 MONTHS
CMP DI, 12
JLE L22
RET
;DISPLAY POSITIVE INTEGER IN AX
INTOUT: PUSHA
MOV BX, 10
XOR CX, CX
NO10: CWD
IDIV BX
PUSH DX
INC CX
TEST AX, AX
JNE NO10
NO20: MOV AH, 02H
POP DX
ADD DL, '0'
INT 21H
LOOP NO20
POPA
RET
;DISPLAY CX SPACE CHARACTERS
SPACE: PUSHA
SP10: MOV AH, 02H
MOV DL, 20H
INT 21H
LOOP SP10
POPA
RET
;START A NEW LINE
CRLF: MOV DX, OFFSET LCRLF
;DISPLAY STRING AT DX
TEXT: MOV AH, 09H
INT 21H
RET
SNOOPY DB "[SNOOPY]"
LCRLF DB 0DH, 0AH, '$'
MONAME DB " JANUARY $ FEBRUARY$ MARCH $ APRIL $ MAY $ JUNE $"
DB " JULY $ AUGUST $SEPTEMBER$ OCTOBER$ NOVEMBER$ DECEMBER$"
SUMO DB "SU MO TU WE TH FR SA$"
DAYS DB 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
DAY DB ?, ?, ?, ?, ?, ?
END START |
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.
| #Haskell | Haskell |
-- Calling a function with a fixed number of arguments
multiply x y = x * y
multiply 10 20 -- returns 200
-- Calling a function that requires no arguments
-- Normally, you use constant instead of function without arguments:
twopi = 6.28
-- But you can also pass special value as the first argument indicating function call:
twopi () = 6.28 -- definition
twopi :: Num a => () -> a -- its type
twopi () -- returns 6.28
-- Partial application and auto-currying is built-in.
multiply_by_10 = (10 * )
map multiply_by_10 [1, 2, 3] -- [10, 20, 30]
multiply_all_by_10 = map multiply_by_10
multiply_all_by_10 [1, 2, 3] -- [10, 20, 30]
-- TODO:
-- 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
|
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function n = catalanNumber(n)
for i = (1:length(n))
n(i) = (1/(n(i)+1))*nchoosek(2*n(i),n(i));
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
| #Ruby | Ruby | def getitem(s, depth=0)
out = [""]
until s.empty?
c = s[0]
break if depth>0 and (c == ',' or c == '}')
if c == '{' and x = getgroup(s[1..-1], depth+1)
out = out.product(x[0]).map{|a,b| a+b}
s = x[1]
else
s, c = s[1..-1], c + s[1] if c == '\\' and s.size > 1
out, s = out.map{|a| a+c}, s[1..-1]
end
end
return out, s
end
def getgroup(s, depth)
out, comma = [], false
until s.empty?
g, s = getitem(s, depth)
break if s.empty?
out += g
case s[0]
when '}' then return (comma ? out : out.map{|a| "{#{a}}"}), s[1..-1]
when ',' then comma, s = true, s[1..-1]
end
end
end
strs = <<'EOS'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
EOS
strs.each_line do |s|
puts s.chomp!
puts getitem(s)[0].map{|str| "\t"+str}
puts
end |
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
| #Lua | Lua | function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) then
return true
end
for b=2,n-2 do
if sameDigits(n,b) then
return true
end
end
return false
end
function isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
local d = 5
while d * d <= n do
if n % d == 0 then
return false
end
d = d + 2
if n % d == 0 then
return false
end
d = d + 4
end
return true
end
function main()
local kinds = {" ", " odd ", " prime "}
for i=1,3 do
print("First 20" .. kinds[i] .. "Brazillion numbers:")
local c = 0
local n = 7
while true do
if isBrazilian(n) then
io.write(n .. " ")
c = c + 1
if c == 20 then
print()
print()
break
end
end
if i == 1 then
n = n + 1
elseif i == 2 then
n = n + 2
elseif i == 3 then
repeat
n = n + 2
until isPrime(n)
end
end
end
end
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
| #Java | Java | import java.text.*;
import java.util.*;
public class CalendarTask {
public static void main(String[] args) {
printCalendar(1969, 3);
}
static void printCalendar(int year, int nCols) {
if (nCols < 1 || nCols > 12)
throw new IllegalArgumentException("Illegal column width.");
Calendar date = new GregorianCalendar(year, 0, 1);
int nRows = (int) Math.ceil(12.0 / nCols);
int offs = date.get(Calendar.DAY_OF_WEEK) - 1;
int w = nCols * 24;
String[] monthNames = new DateFormatSymbols(Locale.US).getMonths();
String[][] mons = new String[12][8];
for (int m = 0; m < 12; m++) {
String name = monthNames[m];
int len = 11 + name.length() / 2;
String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len);
mons[m][0] = String.format(format, name, "");
mons[m][1] = " Su Mo Tu We Th Fr Sa";
int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int d = 1; d < 43; d++) {
boolean isDay = d > offs && d <= offs + dim;
String entry = isDay ? String.format(" %2s", d - offs) : " ";
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);
}
System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]");
System.out.printf("%" + (w / 2 + 4) + "s%n%n", year);
for (int r = 0; r < nRows; r++) {
for (int i = 0; i < 8; i++) {
for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++)
System.out.printf(" %s", mons[c][i]);
System.out.println();
}
System.out.println();
}
}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.