task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to 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.
| #Julia | Julia |
# IF THIS SMALL FUNCTION IS PLACED IN THE STARTUP.JL
# FILE, IT WILL BE LOADED ON STARTUP. THE REST OF
# THIS EXAMPLE IS IN ALL UPPERCASE.
function RUNUPPERCASECODE(CO)
COD = replace(lowercase(CO), "date" => "Date")
for E in Meta.parse(COD, 1) eval(E) end
end
CODE = """BEGIN
USING DATES;
CENTEROBJECT(X, N) = BEGIN S = UPPERCASE(STRING(X)); RPAD(LPAD(S, DIV(N + LENGTH(S), 2)), N) END;
FUNCTION FORMATMONTH(YR, MO)
DT = DATE(\"\$YR-\$MO-01\");
DAYOFWEEKFIRST = DAYOFWEEK(DT);
NUMWEEKLINES = 1;
STR = UPPERCASE(CENTEROBJECT(MONTHNAME(DT), 20) * \"\\NMO TU WE TH FR SA SU\\N\");
STR *= \" \" ^ (3 * (DAYOFWEEKFIRST - 1)) * LPAD(STRING(1), 2);
FOR I = 2:DAYSINMONTH(DT)
IF (I + DAYOFWEEKFIRST + 5) % 7 == 0
STR *= \"\\N\" * LPAD(I, 2);
NUMWEEKLINES += 1;
ELSE
STR *= LPAD(STRING(I), 3);
END;
END;
STR *= NUMWEEKLINES < 6 ? \"\\N\\N\\N\" : \"\\N\\N\";
ARR = [];
FOR S IN SPLIT(STR, \"\\N\")
PUSH!(ARR, RPAD(S, 20)[1:20])
END;
JOIN(ARR, \"\\N\");
END;
FUNCTION FORMATYEAR(DISPLAYYEAR)
CALMONTHS = [FORMATMONTH(DISPLAYYEAR, MO) FOR MO IN 1:12];
MONTHSPERLINE = 6;
JOINSPACES = 2;
STR = \"\\N\" * CENTEROBJECT(DISPLAYYEAR, 132) * \"\\N\";
MONTHCAL = [SPLIT(FORMATMONTH(DISPLAYYEAR, I), \"\\N\") FOR I IN 1:12];
FOR I IN 1:MONTHSPERLINE:LENGTH(CALMONTHS) - 1
FOR J IN 1:LENGTH(MONTHCAL[1])
MONTHLINES = MAP(X->MONTHCAL[X][J], I:I + MONTHSPERLINE - 1);
STR *= RPAD(JOIN(MONTHLINES, \" \" ^ JOINSPACES), 132) * \"\\N\";
END;
STR *= \"\\N\";
END;
STR;
END;
PRINTLN(FORMATYEAR(1969));
END;
"""
RUNUPPERCASECODE(CODE)
|
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
| #Modula-2 | Modula-2 | #include <vga.h>
int Initialize (void)
{
if ( vga_init () == 0 )
return 1;
else
return 0;
}
void SetMode (int newmode)
{
vga_setmode (newmode);
}
int GetMode (void)
{
return vga_getcurrentmode ();
}
int MaxWidth (void)
{
return vga_getxdim ();
}
int MaxHeight (void)
{
return vga_getydim ();
}
void Clear (void)
{
vga_clear ();
}
void SetColour (int colour)
{
vga_setcolor (colour);
}
void SetEGAcolour (int colour)
{
vga_setegacolor (colour);
}
void SetRGB (int red, int green, int blue)
{
vga_setrgbcolor (red, green, blue);
}
void DrawLine (int x0, int y0, int dx, int dy)
{
vga_drawline (x0, y0, x0 + dx, y0 + dy);
}
void Plot (int x, int y)
{
vga_drawpixel (x, y);
}
int ThisColour (int x, int y)
{
return vga_getpixel (x, y);
}
void GetKey (char *ch)
{
*ch = vga_getkey ();
} |
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.
| #CoffeeScript | CoffeeScript |
# Calling a function that requires no arguments
foo()
# Calling a function with a fixed number of arguments
foo 1
# Calling a function with optional arguments
# (Optional arguments are done using an object with named keys)
foo 1, optionalBar: 1, optionalBaz: 'bax'
# Calling a function with a variable number of arguments
# for a function `foo` defined as `foo = ( args... ) ->`
foo 1, 2, 3, 4
# Calling a function with named arguments
# (Named arguments are done using an object with named keys)
foo bar: 1, bax: 'baz'
# Using a function in statement context
x = foo 1
# Using a function in first-class context within an expression
# (For `foo` defined as `foo = ( x ) -> x + 1`
x = [ 1, 2, 3 ].map foo
# Obtaining the return value of a function
x = foo 1
# Arguments are passed by value, even objects. Objects
# are passed as the _value_ of the reference to an object.
# Example:
bar = ( person ) ->
# Since `person` is a reference
# to the person passed in, we can assign
# a new value to its `name` key.
person.name = 'Bob'
# Since `person` is just the value of
# the original reference, assigning to it
# does not modify the original reference.
person = new Person 'Frank'
# Partial application is only possible manually through closures
curry = ( f, fixedArgs... ) ->
( args... ) -> f fixedArgs..., args...
# Example usage
add = ( x, y ) -> x + y
add2 = curry add, 2
add2 1 #=> 3
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Raku | Raku | sub cantor ( Int $height ) {
my $width = 3 ** ($height - 1);
my @lines = ( "\c[FULL BLOCK]" x $width ) xx $height;
my sub _trim_middle_third ( $len, $start, $index ) {
my $seg = $len div 3
or return;
for ( $index ..^ $height ) X ( 0 ..^ $seg ) -> ( $i, $j ) {
@lines[$i].substr-rw( $start + $seg + $j, 1 ) = ' ';
}
_trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;
}
_trim_middle_third( $width, 0, 1 );
return @lines;
}
.say for cantor(5); |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def add + enddef
def sub - enddef
def mul * enddef
def reduce >ps
1 get
swap len 2 swap 2 tolist for
get rot swap tps exec swap
endfor
ps> drop
swap
enddef
( 1 2 3 4 5 )
getid add reduce ?
getid sub reduce ?
getid mul reduce ? |
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
| #PicoLisp | PicoLisp | (de reduce ("Fun" "Lst")
(let "A" (car "Lst")
(for "N" (cdr "Lst")
(setq "A" ("Fun" "A" "N")) )
"A" ) )
(println
(reduce + (1 2 3 4 5))
(reduce * (1 2 3 4 5)) )
(bye) |
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}
| #Ring | Ring |
# Project : Cartesian product of two or more lists
list1 = [[1,2],[3,4]]
list2 = [[3,4],[1,2]]
cartesian(list1)
cartesian(list2)
func cartesian(list1)
for n = 1 to len(list1[1])
for m = 1 to len(list1[2])
see "(" + list1[1][n] + ", " + list1[2][m] + ")" + nl
next
next
see nl
|
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
| #FunL | FunL | import integers.choose
import util.TextTable
def
catalan( n ) = choose( 2n, n )/(n + 1)
catalan2( n ) = product( (n + k)/k | k <- 2..n )
catalan3( 0 ) = 1
catalan3( n ) = 2*(2n - 1)/(n + 1)*catalan3( n - 1 )
t = TextTable()
t.header( 'n', 'definition', 'product', 'recursive' )
t.line()
for i <- 1..4
t.rightAlignment( i )
for i <- 0..15
t.row( i, catalan(i), catalan2(i), catalan3(i) )
println( t ) |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #XPL0 | XPL0 |
func NumDigits(N); \Return number of digits in N
int N, Cnt;
[Cnt:= 0;
repeat N:= N/10;
Cnt:= Cnt+1;
until N = 0;
return Cnt;
];
func Brilliant(N); \Return 'true' if N is a brilliant number
int N, Limit, Cnt, F;
int A(3);
[Limit:= sqrt(N);
Cnt:= 0; F:= 2;
loop [if rem(N/F) = 0 then
[A(Cnt):= F;
Cnt:= Cnt+1;
if Cnt > 2 then quit;
N:= N/F;
]
else F:= F+1;
if F > N then quit;
if F > Limit then
[A(Cnt):= N;
Cnt:= Cnt+1;
quit;
];
];
if Cnt # 2 then return false;
return NumDigits(A(0)) = NumDigits(A(1));
];
int Cnt, N, Mag;
[Format(5, 0);
Cnt:= 0; N:= 4;
loop [if Brilliant(N) then
[RlOut(0, float(N));
Cnt:= Cnt+1;
if Cnt >= 100 then quit;
if rem(Cnt/10) = 0 then CrLf(0);
];
N:= N+1;
];
CrLf(0); CrLf(0);
Format(7, 0);
Cnt:= 0; N:= 4; Mag:= 10;
loop [if Brilliant(N) then
[Cnt:= Cnt+1;
if N >= Mag then
[Text(0, "First >= ");
RlOut(0, float(Mag));
Text(0, " is ");
RlOut(0, float(Cnt));
Text(0, " in series: ");
RlOut(0, float(N));
CrLf(0);
if Mag >= 1_000_000 then quit;
Mag:= Mag*10;
];
];
N:= N+1;
];
] |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Linq.Enumerable;
public static class BraceExpansion
{
enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }
const char L = '{', R = '}', S = ',';
public static void Main() {
string[] input = {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
@"{,{,gotta have{ ,\, again\, }}more }cowbell!",
@"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
};
foreach (string text in input) Expand(text);
}
static void Expand(string input) {
Token token = Tokenize(input);
foreach (string value in token) Console.WriteLine(value);
Console.WriteLine();
}
static Token Tokenize(string input) {
var tokens = new List<Token>();
var buffer = new StringBuilder();
bool escaping = false;
int level = 0;
foreach (char c in input) {
(escaping, level, tokens, buffer) = c switch {
_ when escaping => (false, level, tokens, buffer.Append(c)),
'\\' => (true, level, tokens, buffer.Append(c)),
L => (escaping, level + 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),
S when level > 0 => (escaping, level,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),
R when level > 0 => (escaping, level - 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),
_ => (escaping, level, tokens, buffer.Append(c))
};
}
if (buffer.Length > 0) tokens.Add(buffer.Flush());
for (int i = 0; i < tokens.Count; i++) {
if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {
tokens[i] = tokens[i].Value; //Change to text
}
}
return new Token(tokens, TokenType.Concat);
}
static List<Token> Merge(this List<Token> list) {
int separators = 0;
int last = list.Count - 1;
for (int i = list.Count - 3; i >= 0; i--) {
if (list[i].Type == TokenType.Separator) {
separators++;
Concat(list, i + 1, last);
list.RemoveAt(i);
last = i;
} else if (list[i].Type == TokenType.OpenBrace) {
Concat(list, i + 1, last);
if (separators > 0) {
list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);
list.RemoveRange(i+1, list.Count - i - 1);
} else {
list[i] = L.ToString();
list[^1] = R.ToString();
Concat(list, i, list.Count);
}
break;
}
}
return list;
}
static void Concat(List<Token> list, int s, int e) {
for (int i = e - 2; i >= s; i--) {
(Token a, Token b) = (list[i], list[i+1]);
switch (a.Type, b.Type) {
case (TokenType.Text, TokenType.Text):
list[i] = a.Value + b.Value;
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Concat):
a.SubTokens.AddRange(b.SubTokens);
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Text) when b.Value == "":
list.RemoveAt(i+1);
break;
case (TokenType.Text, TokenType.Concat) when a.Value == "":
list.RemoveAt(i);
break;
default:
list[i] = new Token(new [] { a, b }, TokenType.Concat);
list.RemoveAt(i+1);
break;
}
}
}
private struct Token : IEnumerable<string>
{
private List<Token>? _subTokens;
public string Value { get; }
public TokenType Type { get; }
public List<Token> SubTokens => _subTokens ??= new List<Token>();
public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);
public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList());
public static implicit operator Token(string value) => new Token(value, TokenType.Text);
public IEnumerator<string> GetEnumerator() => (Type switch
{
TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)),
TokenType.Alternate => from t in SubTokens from s in t select s,
_ => Repeat(Value, 1)
}).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
//===Extension methods===
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
static List<Token> With(this List<Token> list, Token token) {
list.Add(token);
return list;
}
static IEnumerable<Token> Range(this List<Token> list, Range range) {
int start = range.Start.GetOffset(list.Count);
int end = range.End.GetOffset(list.Count);
for (int i = start; i < end; i++) yield return list[i];
}
static string Flush(this StringBuilder builder) {
string result = builder.ToString();
builder.Clear();
return result;
}
} |
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
| #Arturo | Arturo | brazilian?: function [n][
if n < 7 -> return false
if zero? and n 1 -> return true
loop 2..n-2 'b [
if 1 = size unique digits.base:b n ->
return true
]
return false
]
printFirstByRule: function [rule,title][
print ~"First 20 |title|brazilian numbers:"
i: 7
found: new []
while [20 > size found][
if brazilian? i ->
'found ++ i
do.import rule
]
print found
print ""
]
printFirstByRule [i: i+1] ""
printFirstByRule [i: i+2] "odd "
printFirstByRule [i: i+2, while [not? prime? i] -> i: i+2] "prime " |
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
| #Batch_File | Batch File | ::Calender Task from Rosetta Code Wiki
::Batch File Implementation
@echo off
setlocal enabledelayedexpansion
%== Set a valid year [will not be validated] ==%
set y=1969
%== Set the variables for months (feb_l=the normal 28 days) ==%
set jan_l=31&set apr_l=30
set mar_l=31&set jun_l=30
set may_l=31&set sep_l=30
set jul_l=31&set nov_l=30
set aug_l=31&set feb_l=28
set oct_l=31
set dec_l=31
%== Compute day for first day of the year ==%
set /a d=(y/4+y)-(y/100-y/400)
%== Check if that year is a leap year ==%
set /a "op1=y%%4","op2=y%%100","op3=y%%400"
if not "%op1%"=="0" (goto :no_leap)
if not "%op2%"=="0" (goto :yes_leap)
if not "%op3%"=="0" (goto :no_leap)
:yes_leap
%== Ooops... Leap year. Change feb_l to 29. ==%
set feb_l=29
set/a d-=1
:no_leap
%== Compute weekday of the first day... ==%
set /a d%%=7
%== Generate everything that's inside the calendar ==%
for %%a in (jan feb mar apr may jun jul aug sep oct nov dec) do (
set %%a=
set chars_added=0
for /l %%b in (1,1,!d!) do (set "%%a=!%%a! "&set /a chars_added+=3)
for /l %%c in (1,1,!%%a_l!) do (
if %%c lss 10 (set "%%a=!%%a! %%c ") else (set "%%a=!%%a!%%c ")
set /a chars_added+=3
)
for /l %%d in (!chars_added!,1,124) do set "%%a=!%%a! "
set /a d=^(d+%%a_l^)%%7
)
%== Display the calendar ==%
cls
echo.
echo. [SNOOPY]
echo.
echo. YEAR = %y%
echo.
echo. January February March
echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
echo. %jan:~0,20% %feb:~0,20% %mar:~0,20%
echo. %jan:~21,20% %feb:~21,20% %mar:~21,20%
echo. %jan:~42,20% %feb:~42,20% %mar:~42,20%
echo. %jan:~63,20% %feb:~63,20% %mar:~63,20%
echo. %jan:~84,20% %feb:~84,20% %mar:~84,20%
echo. %jan:~105% %feb:~105% %mar:~105%
echo.
echo. April May June
echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
echo. %apr:~0,20% %may:~0,20% %jun:~0,20%
echo. %apr:~21,20% %may:~21,20% %jun:~21,20%
echo. %apr:~42,20% %may:~42,20% %jun:~42,20%
echo. %apr:~63,20% %may:~63,20% %jun:~63,20%
echo. %apr:~84,20% %may:~84,20% %jun:~84,20%
echo. %apr:~105% %may:~105% %jun:~105%
echo.
echo. July August September
echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
echo. %jul:~0,20% %aug:~0,20% %sep:~0,20%
echo. %jul:~21,20% %aug:~21,20% %sep:~21,20%
echo. %jul:~42,20% %aug:~42,20% %sep:~42,20%
echo. %jul:~63,20% %aug:~63,20% %sep:~63,20%
echo. %jul:~84,20% %aug:~84,20% %sep:~84,20%
echo. %jul:~105% %aug:~105% %sep:~105%
echo.
echo. October November December
echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
echo. %oct:~0,20% %nov:~0,20% %dec:~0,20%
echo. %oct:~21,20% %nov:~21,20% %dec:~21,20%
echo. %oct:~42,20% %nov:~42,20% %dec:~42,20%
echo. %oct:~63,20% %nov:~63,20% %dec:~63,20%
echo. %oct:~84,20% %nov:~84,20% %dec:~84,20%
echo. %oct:~105% %nov:~105% %dec:~105%
echo.
pause
endlocal |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Java | Java | import java.lang.reflect.*;
class Example {
private String _name;
public Example(String name) { _name = name; }
public String toString() { return "Hello, I am " + _name; }
}
public class BreakPrivacy {
public static final void main(String[] args) throws Exception {
Example foo = new Example("Eric");
for (Field f : Example.class.getDeclaredFields()) {
if (f.getName().equals("_name")) {
// make it accessible
f.setAccessible(true);
// get private field
System.out.println(f.get(foo));
// set private field
f.set(foo, "Edith");
System.out.println(foo);
break;
}
}
}
} |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Julia | Julia | import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
class ToBeBroken {
@Suppress("unused")
private val secret: Int = 42
}
fun main(args: Array<String>) {
val tbb = ToBeBroken()
val props = ToBeBroken::class.declaredMemberProperties
for (prop in props) {
prop.isAccessible = true // make private properties accessible
println("${prop.name} -> ${prop.get(tbb)}")
}
} |
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.
| #C.2B.2B | C++ | #include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------
enum states { SEED, GROWING, MOVING, REST };
enum treeStates { NONE, MOVER, TREE };
const int MAX_SIDE = 480, MAX_MOVERS = 511, MAX_CELLS = 15137;
//--------------------------------------------------------------------
class point
{
public:
point() { x = y = 0; }
point( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
int x, y;
};
//--------------------------------------------------------------------
class movers
{
public:
point pos;
bool moving;
movers() : moving( false ){}
};
//--------------------------------------------------------------------
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear()
{
ZeroMemory( pBits, width * height * sizeof( DWORD ) );
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
void *pBits;
int width, height;
};
//--------------------------------------------------------------------
class brownianTree
{
public:
brownianTree()
{
_bmp.create( MAX_SIDE, MAX_SIDE );
init();
}
void init()
{
_cellCount = 0;
ZeroMemory( _grid, sizeof( _grid ) );
_bmp.clear();
_state = SEED;
}
bool mainLoop()
{
switch( _state )
{
case REST: saveTree(); return false;
case SEED: doSeed(); break;
case GROWING: startMovers(); break;
case MOVING: moveMovers();
}
return true;
}
myBitmap* getBmp() { return &_bmp; }
private:
void saveTree()
{
for( int y = 0; y < MAX_SIDE; y++ )
for( int x = 0; x < MAX_SIDE; x++ )
if( _grid[x][y] == TREE )
SetPixel( _bmp.getDC(), x, y, RGB( 255, 120, 0 ) );
_bmp.saveBitmap( "f:\\rc\\tree.bmp" );
}
void doSeed()
{
int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4;
_grid[rand() % x + y][rand() % x + y] = TREE;
_cellCount++;
_state = GROWING;
}
void addMover( movers* m )
{
m->moving = true;
int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4, a, b;
while( true )
{
a = rand() % x + y; b = rand() % x + y;
if( _grid[a][b] == NONE ) break;
}
m->pos.set( a, b );
_grid[a][b] = MOVER;
}
void startMovers()
{
movers* m;
for( int c = 0; c < MAX_MOVERS; c++ )
{
m = &_movers[c];
addMover( m );
}
_state = MOVING;
}
void addToTree( movers* m )
{
m->moving = false;
_grid[m->pos.x][m->pos.y] = TREE;
if( ++_cellCount >= MAX_CELLS ) _state = REST;
COORD c = { 0, 1 };
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
cout << "Cells added: " << _cellCount
<< " from " << MAX_CELLS << " => "
<< static_cast<float>( 100 * _cellCount ) /
static_cast<float>( MAX_CELLS )
<< "% ";
}
bool moveIt( movers* m )
{
point f[8]; int ff = 0;
for( int y = -1; y < 2; y++ )
{
for( int x = -1; x < 2; x++ )
{
if( !x && !y ) continue;
int a = m->pos.x + x, b = m->pos.y + y;
if( a < 0 || b < 0 || a >= MAX_SIDE || b >= MAX_SIDE )
{
addToTree( m );
return true;
}
switch( _grid[a][b] )
{
case TREE:
addToTree( m );
return true;
case NONE:
f[ff++].set( a, b );
}
}
}
if( ff < 1 ) return false;
_grid[m->pos.x][m->pos.y] = NONE;
m->pos = f[rand() % ff];
_grid[m->pos.x][m->pos.y] = MOVER;
return false;
}
void moveMovers()
{
movers* mm;
for( int m = 0; m < MAX_MOVERS; m++ )
{
mm = &_movers[m];
if( !mm->moving ) continue;
if( moveIt( mm ) && _cellCount < MAX_CELLS ) addMover( mm );
}
}
states _state;
BYTE _grid[MAX_SIDE][MAX_SIDE];
myBitmap _bmp;
int _cellCount;
movers _movers[MAX_MOVERS];
};
//--------------------------------------------------------------------
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
brownianTree tree;
DWORD now = GetTickCount();
while( tree.mainLoop() );
now = GetTickCount() - now;
cout << endl << endl << "It took "
<< now / 1000
<< " seconds to complete the task!" << endl << endl;
BitBlt( GetDC( GetConsoleWindow() ), 20, 90, MAX_SIDE, MAX_SIDE,
tree.getBmp()->getDC(), 0, 0, SRCCOPY );
system( "pause" );
return 0;
}
//-------------------------------------------------------------------- |
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
| #Batch_File | Batch File | :: Bulls and Cows Task from Rosetta Code
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
:: initialization
:begin
set "list_chars=123456789"
set "list_length=9"
set "code="
set "code_length=4" %== this should be less than 10 ==%
set "tries=0" %== number of tries ==%
:: generate the code to be guessed by player
set "chars_left=%list_chars%"
for /l %%c in (1, 1, %code_length%) do (
set /a "rnd=!random! %% (%list_length% + 1 - %%c)"
for %%? in (!rnd!) do set "pick_char=!chars_left:~%%?,1!"
set "code=!code!!pick_char!"
for %%? in (!pick_char!) do set "chars_left=!chars_left:%%?=!"
)
:: get the min and max allowable guess for input validation
set "min=!list_chars:~0,%code_length%!"
set "max="
for /l %%c in (1, 1, %code_length%) do set "max=!max!!list_chars:~-%%c,1!"
:: display game
:display
cls
echo(
echo(Bulls and Cows Game
echo(Batch File Implementation
echo(
echo(Gameplay:
echo(
echo(I have generated a %code_length%-digit code from digits 1-9 without duplication.
echo(Your objective is to guess it. If your guess is equal to my code,
echo(then you WIN. If not, I will score your guess:
echo(
echo(** A score of one BULL is accumulated for each digit in your guess
echo(that equals the corresponding digit in my code.
echo(
echo(** A score of one COW is accumulated for each digit in your guess
echo(that also appears in my code, but in the WRONG position.
echo(
echo(Now, start guessing^^!
:: input guess
:guess
echo(
set "guess=" %== clear input ==%
set /p "guess=Your Guess: "
:: validate input
if "!guess!" gtr "%max%" goto invalid
if "!guess!" lss "%min%" goto invalid
set /a "last_idx=%code_length% - 1"
for /l %%i in (0, 1, %last_idx%) do (
set /a "next_idx=%%i + 1"
for /l %%j in (!next_idx!, 1, %last_idx%) do (
if "!guess:~%%i,1!" equ "!guess:~%%j,1!" goto invalid
)
)
goto score
:: display that input is invalid
:invalid
echo(Please input a valid guess.
goto guess
:: scoring section
:score
set /a "tries+=1"
if "%guess%" equ "%code%" goto win
set "cow=0"
set "bull=0"
for /l %%i in (0, 1, %last_idx%) do (
for /l %%j in (0, 1, %last_idx%) do (
if "!guess:~%%i,1!" equ "!code:~%%j,1!" (
if "%%i" equ "%%j" (
set /a "bull+=1"
) else (
set /a "cow+=1"
)
)
)
)
:: display score and go back to user input
echo(BULLS = %bull%; COWS = %cow%.
goto guess
:: player wins!
:win
echo(
echo(After %tries% tries, YOU CRACKED IT^^! My code is %code%.
echo(
set /p "opt=Play again? "
if /i "!opt!" equ "y" goto begin
exit /b 0 |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Phix | Phix | -- demo\rosetta\burrows_wheeler.exw
--/*
The traditional method:
7 banana$ $banana 6
6 $banana ===> a$banan 5
5 a$banan ana$ban 3
4 na$bana sort anana$b 1
3 ana$ban banana$ 7
2 nana$ba ===> na$bana 4
1 anana$b nana$ba 2
^ desired answer == "annb$aa"
First ignore the numbers: the desired answer is found by creating a table of all
rotations of "banana$", sorting it, and then extracting the right-hand column.
However, there is no need to actually create such a table, which could be very
expensive for long strings, instead just number them logically (admittedly that
was somewhat arbitrarily chosen to get the indexes to work out nicely, I picked
the original index of the last character), and perform a custom sort on those.
The latter effectively just recreates the rotations one character at a time until
there is a mismatch (which there always will be since there is only one $).
The left hand column is my arbitrary numbering scheme and the right hand column
is those sorted into order, which is also the indexes to the original string of
the characters that we want.
The code below uses $ as the terminator, but eg 1 (== '\#01') should be fine,
except of course for the display of that on a console.
--*/
with javascript_semantics
constant terminator = '$'
function rot_sort(integer i,j, sequence s)
-- i,j are indexes of the last character, so bump before first compare.
-- eg/ie rot_sort(i,j,s) should yield compare(rotate(s,i),rotate(s,j)),
-- as in rot_sort(7,6,"banana$") == compare("banana$","$banana")
-- - but one character at a time rather than constructing both.
integer l = length(s)
while true do
i = mod(i,l)+1
j = mod(j,l)+1
integer c = compare(s[i],s[j])
if c!=0 then return c end if
end while
end function
function burrows_wheeler_transform(string s)
if find(terminator,s) then return "error" end if
s &= terminator
integer l = length(s)
sequence t = custom_sort(routine_id("rot_sort"),tagset(l),{s})
string res = repeat(' ',l)
for i=1 to l do
res[i] = s[t[i]]
end for
return res
end function
--/*
Inversion. The traditional method is add column and sort, seven times,
to reconstruct the table above, then pick the entry that ends with the
marker. Showing that technique in full detail here is not helpful, and
like above that would be hideously inefficient for large strings.
$banana 1 $ (1 ) a 2
a$banan 2 a ( 1) n 6
ana$ban 3 a ( 2) n 7
anana$b 4 a ( 3) b 5
banana$ 5 b $ 1
na$bana 6 n (2 ) a 3
nana$ba 7 n (3 ) a 4
^ ^ ^ ^ ^
f l f l t
However, we already have the last column, and the first is just that
sorted alphabetically, and with just those two, we have all possible
character pairings of the original message. The trick is in figuring
out how to stitch them together in the right order. If you carefully
study the three that end in a, and the three that start in a, notice
the $banan,na$ban,nana$b parts are sorted in the same order, whether
they are prefixed with a or not. That is, the middle (parenthesised)
matching numbers are both 123, not 123 and say 231. It is quite hard
to see that being useful, but eventually the penny should drop. The
right-hand 1 with an a rotated right gives the left-hand 1, and the
same goes for 2 and 3: they are in fact links to the prior pairing.
In other words the first a in l always corresponds to the first in f,
the second to the second, and so on, and that (amazingly) forms the
order in which the pairings need to be daisy-chained together.
Try following (1->)2a->6n->3a->7n->4a->5b->$, == reverse("banana"),
in the above f and t tables.
The code below builds a queue of 'a' ({1,6,7}, built backwards) then
we pop {2,3,4} into those slots in t as we find 'a' in f, likewise
for all other letters, forming the links for each pairing as shown.
See the trivial step 3 scan below, then go back and stare at f and
t as shown above, and once again, eventually the penny should drop.
I will admit I had to read ten or so explanations before I got it.
--*/
function inverse_burrows_wheeler(string s)
if find('\0',s) then ?9/0 end if -- (doable, but needs some +1s)
integer l = length(s), c
string f = sort(s)
sequence q = repeat(0,256), -- queue heads (per char)
x = repeat(0,l), -- queue links
t = repeat(0,l) -- reformed/pairing links
-- Step 1. discover/build queues (backwards)
for i=l to 1 by -1 do
c = s[i]
x[i] = q[c]
q[c] = i
end for
-- Step 2. reform/pop char queues into pairing links
for i=1 to l do
c = f[i]
t[q[c]] = i
q[c] = x[q[c]]
end for
-- Step 3. rebuild (backwards)
c = find(terminator,f)
if c=0 then return "error" end if
string res = repeat(' ',l-1)
for i=l-1 to 1 by -1 do
c = t[c] -- (first time in, skip the end marker)
res[i] = f[c]
end for
return res
end function
procedure test(string src)
string enc = burrows_wheeler_transform(src),
dec = inverse_burrows_wheeler(enc)
src = shorten(src,"characters")
enc = shorten(enc,"characters")
dec = shorten(dec,"characters")
printf(1,"original: %s --> %s\n inverse: %s\n",{src,enc,dec})
end procedure
test("banana")
test("dogwood")
test("TO BE OR NOT TO BE OR WANT TO BE OR NOT?")
test("SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES")
|
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
| #AutoIt | AutoIt |
$Caesar = Caesar("Hi", 2, True)
MsgBox(0, "Caesar", $Caesar)
Func Caesar($String, $int, $encrypt = True)
If Not IsNumber($int) Or Not StringIsDigit($int) Then Return SetError(1, 0, 0)
If $int < 1 Or $int > 25 Then Return SetError(2, 0, 0)
Local $sLetters, $x
$String = StringUpper($String)
$split = StringSplit($String, "")
For $i = 1 To $split[0]
If Asc($split[$i]) - 64 > 26 Or Asc($split[$i]) - 64 < 1 Then
$sLetters &= $split[$i]
ContinueLoop
EndIf
If $encrypt = True Then
$move = Asc($split[$i]) - 64 + $int
Else
$move = Asc($split[$i]) - 64 - $int
EndIf
If $move > 26 Then
$move -= 26
ElseIf $move < 1 Then
$move += 26
EndIf
While $move
$x = Mod($move, 26)
If $x = 0 Then $x = 26
$sLetters &= Chr($x + 64)
$move = ($move - $x) / 26
WEnd
Next
Return $sLetters
EndFunc ;==>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
| #Fortran | Fortran |
Program eee
implicit none
integer, parameter :: QP = selected_real_kind(16)
real(QP), parameter :: one = 1.0
real(QP) :: ee
write(*,*) ' exp(1.) ', exp(1._QP)
ee = 1. +(one +(one +(one +(one +(one+ (one +(one +(one +(one +(one +(one &
+(one +(one +(one +(one +(one +(one +(one +(one +(one +(one) &
/21.)/20.)/19.)/18.)/17.)/16.)/15.)/14.)/13.)/12.)/11.)/10.)/9.) &
/8.)/7.)/6.)/5.)/4.)/3.)/2.)
write(*,*) ' polynomial ', ee
end Program eee |
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)
| #Java | Java |
public class BullsAndCowsPlayerGame {
private static int count;
private static Console io = System.console();
private final GameNumber secret;
private List<AutoGuessNumber> pool = new ArrayList<>();
public BullsAndCowsPlayerGame(GameNumber secret) {
this.secret = secret;
fillPool();
}
private void fillPool() {
for (int i = 123; i < 9877; i++) {
int[] arr = AutoGuessNumber.parseDigits(i, 4);
if (GameNumber.isGuess(arr)) {
pool.add(new AutoGuessNumber(i, 4));
}
}
}
public void play() {
io.printf("Bulls and Cows%n");
io.printf("==============%n");
io.printf("Secret number is %s%n", secret);
do {
AutoGuessNumber guess = guessNumber();
io.printf("Guess #%d is %s from %d%n", count, guess, pool.size());
GuessResult result = secret.match(guess);
if (result != null) {
printScore(io, result);
if (result.isWin()) {
io.printf("The answer is %s%n", guess);
break;
}
clearPool(guess, result);
} else {
io.printf("No more variants%n");
System.exit(0);
}
} while (true);
}
private AutoGuessNumber guessNumber() {
Random random = new Random();
if (pool.size() > 0) {
int number = random.nextInt(pool.size());
count++;
return pool.get(number);
}
return null;
}
private static void printScore(Console io, GuessResult result) {
io.printf("%1$d %2$d%n", result.getBulls(), result.getCows());
}
private void clearPool(AutoGuessNumber guess, GuessResult guessResult) {
pool.remove(guess);
for (int i = 0; i < pool.size(); i++) {
AutoGuessNumber g = pool.get(i);
GuessResult gr = guess.match(g);
if (!guessResult.equals(gr)) {
pool.remove(g);
}
}
}
public static void main(String[] args) {
new BullsAndCowsPlayerGame(new GameNumber()).play();
}
}
|
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.
| #Kotlin | Kotlin | IMPORT JAVA.TEXT.*
IMPORT JAVA.UTIL.*
IMPORT JAVA.IO.PRINTSTREAM
INTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) {
IF (NCOLS < 1 || NCOLS > 12)
THROW ILLEGALARGUMENTEXCEPTION("ILLEGAL COLUMN WIDTH.")
VAL W = NCOLS * 24
VAL NROWS = MATH.CEIL(12.0 / NCOLS).TOINT()
VAL DATE = GREGORIANCALENDAR(YEAR, 0, 1)
VAR OFFS = DATE.GET(CALENDAR.DAY_OF_WEEK) - 1
VAL DAYS = DATEFORMATSYMBOLS(LOCALE).SHORTWEEKDAYS.SLICE(1..7).MAP { IT.SLICE(0..1) }.JOINTOSTRING(" ", " ")
VAL MONS = ARRAY(12) { ARRAY(8) { "" } }
DATEFORMATSYMBOLS(LOCALE).MONTHS.SLICE(0..11).FOREACHINDEXED { M, NAME ->
VAL LEN = 11 + NAME.LENGTH / 2
VAL FORMAT = MESSAGEFORMAT.FORMAT("%{0}S%{1}S", LEN, 21 - LEN)
MONS[M][0] = STRING.FORMAT(FORMAT, NAME, "")
MONS[M][1] = DAYS
VAL DIM = DATE.GETACTUALMAXIMUM(CALENDAR.DAY_OF_MONTH)
FOR (D IN 1..42) {
VAL ISDAY = D > OFFS && D <= OFFS + DIM
VAL ENTRY = IF (ISDAY) STRING.FORMAT(" %2S", D - OFFS) ELSE " "
IF (D % 7 == 1)
MONS[M][2 + (D - 1) / 7] = ENTRY
ELSE
MONS[M][2 + (D - 1) / 7] += ENTRY
}
OFFS = (OFFS + DIM) % 7
DATE.ADD(CALENDAR.MONTH, 1)
}
PRINTF("%" + (W / 2 + 10) + "S%N", "[SNOOPY PICTURE]")
PRINTF("%" + (W / 2 + 4) + "S%N%N", YEAR)
FOR (R IN 0..NROWS - 1) {
FOR (I IN 0..7) {
VAR C = R * NCOLS
WHILE (C < (R + 1) * NCOLS && C < 12) {
PRINTF(" %S", MONS[C][I].TOUPPERCASE()) // ORIGINAL CHANGED TO PRINT IN UPPER CASE
C++
}
PRINTLN()
}
PRINTLN()
}
}
FUN MAIN(ARGS: ARRAY<STRING>) {
SYSTEM.OUT.PRINTCALENDAR(1969, 3, LOCALE.US)
} |
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
| #Modula-3 | Modula-3 | UNSAFE MODULE Foreign EXPORTS Main;
IMPORT IO, Ctypes, Cstring, M3toC;
VAR string1, string2: Ctypes.const_char_star;
BEGIN
string1 := M3toC.CopyTtoS("Foobar");
string2 := M3toC.CopyTtoS("Foobar2");
IF Cstring.strcmp(string1, string2) = 0 THEN
IO.Put("string1 = string2\n");
ELSE
IO.Put("string1 # string2\n");
END;
M3toC.FreeCopiedS(string1);
M3toC.FreeCopiedS(string2);
END Foreign. |
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
| #Mosaic | Mosaic | import clib
importdll msvcrt =
clang function "_strdup" (ref char)ref char
end
proc start=
[]char str:=z"hello strdup"
ref char str2
str2:=_strdup(&.str)
println str2
end |
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.
| #Common_Lisp | Common Lisp |
;Calling a function that requires no arguments
(defun a () "This is the 'A' function")
(a)
;Calling a function with a fixed number of arguments
(defun b (x y) (list x y))
(b 1 2)
;Calling a function with optional arguments
(defun c (&optional x y) (list x y))
(c 1)
;Calling a function with a variable number of arguments
(defun d (&rest args) args)
(d 1 2 3 4 5 6 7 8)
;Calling a function with named arguments
(defun e (&key (x 1) (y 2)) (list x y))
(e :x 10 :y 20)
;Using a function in first-class context within an expression
(defun f (func) (funcall func))
(f #'a)
;Obtaining the return value of a function
(defvar return-of-a (a))
;Is partial application possible and how
(defun curry (function &rest args-1)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
(funcall (curry #'+ 1) 2)
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #REXX | REXX | /*REXX program displays an ASCII diagram of a Canter Set as a set of (character) lines. */
w= linesize() /*obtain the width of the display term.*/
if w==0 then w= 81 /*Can't obtain width? Use the default.*/
do lines=0; _ = 3 ** lines /*calculate powers of three (# lines).*/
if _>w then leave /*Too large? We passed the max value. */
#=_ /*this value of a width─of─line is OK. */
end /*lines*/ /* [↑] calculate a useable line width.*/
w= # /*use the (last) useable line width. */
$= copies('■', #) /*populate the display line with blocks*/
do j=0 until #==0 /*show Cantor set as a line of chars. */
if j>0 then do k=#+1 by #+# to w /*skip 1st line blanking*/
$= overlay( left('', #), $, k) /*blank parts of a line.*/
end /*j*/
say $ /*display a line of the Cantor Set. */
#= # % 3 /*the part (thirds) to be blanked out. */
end /*j*/ /*stick a fork in it, we're all done. */ |
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
| #PowerShell | PowerShell |
1..5 | ForEach-Object -Begin {$result = 0} -Process {$result += $_} -End {$result}
|
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
| #Prolog | Prolog | :- use_module(library(lambda)).
catamorphism :-
numlist(1,10,L),
foldl(\XS^YS^ZS^(ZS is XS+YS), L, 0, Sum),
format('Sum of ~w is ~w~n', [L, Sum]),
foldl(\XP^YP^ZP^(ZP is XP*YP), L, 1, Prod),
format('Prod of ~w is ~w~n', [L, Prod]),
string_to_list(LV, ""),
foldl(\XC^YC^ZC^(string_to_atom(XS, XC),string_concat(YC,XS,ZC)),
L, LV, Concat),
format('Concat of ~w is ~w~n', [L, Concat]). |
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}
| #Ruby | Ruby | p [1, 2].product([3, 4])
p [3, 4].product([1, 2])
p [1, 2].product([])
p [].product([1, 2])
p [1776, 1789].product([7, 12], [4, 14, 23], [0, 1])
p [1, 2, 3].product([30], [500, 100])
p [1, 2, 3].product([], [500, 100])
|
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);
Catalan2 := n -> Binomial(2*n, n)/(n + 1);
Catalan3 := function(n)
local k, c;
c := 1;
k := 0;
while k < n do
k := k + 1;
c := 2*(2*k - 1)*c/(k + 1);
od;
return c;
end;
Catalan4_memo := [1];
Catalan4 := function(n)
if not IsBound(Catalan4_memo[n + 1]) then
Catalan4_memo[n + 1] := Sum([0 .. n - 1], i -> Catalan4(i)*Catalan4(n - 1 - i));
fi;
return Catalan4_memo[n + 1];
end;
# The first fifteen: 0 to 14 !
List([0 .. 14], Catalan1);
List([0 .. 14], Catalan2);
List([0 .. 14], Catalan3);
List([0 .. 14], Catalan4);
# Same output for all four:
# [ 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440 ] |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Common_Lisp | Common Lisp | (defstruct alternation
(alternatives nil :type list))
(defun alternatives-end-positions (string start)
(assert (char= (char string start) #\{))
(loop with level = 0
with end-positions
with escapep and commap
for index from start below (length string)
for c = (char string index)
do (cond (escapep
(setf escapep nil))
((char= c #\\)
(setf escapep t))
((char= c #\{)
(incf level))
((char= c #\})
(decf level)
(when (zerop level)
(push index end-positions)
(loop-finish)))
((and (char= c #\,) (= level 1))
(setf commap t)
(push index end-positions)))
finally (return (and (zerop level) commap (nreverse end-positions)))))
(defun parse-alternation (string start)
(loop with end-positions = (alternatives-end-positions string start)
for %start = (1+ start) then (1+ %end)
for %end in end-positions
collect (parse string :start %start :end %end) into alternatives
finally (return (and alternatives
(values (make-alternation :alternatives alternatives) (1+ %end))))))
(defun parse (string &key (start 0) (end (length string)))
(loop with result and escapep
for index = start then next
while (< index end)
for c = (char string index)
for next = (1+ index)
do (cond (escapep
(push c result)
(setf escapep nil))
((char= c #\\)
(push c result)
(setf escapep t))
((char= c #\{)
(multiple-value-bind (alternation next-index)
(parse-alternation string index)
(cond (alternation
(push alternation result)
(setf next next-index))
(t
(push c result)))))
(t
(push c result)))
finally (return (nreverse result))))
(defun traverse-alternation (alternation)
(mapcan #'traverse (alternation-alternatives alternation)))
(defun traverse (parsed)
(let ((results (list nil)))
(dolist (element parsed results)
(etypecase element
(character
(setf results (loop for r in results
collect (nconc r (list element)))))
(alternation
(setf results (loop for r in results
nconc (loop for ar in (traverse-alternation element)
collect (append r ar)))))))))
(defun expand (string)
(loop for result in (traverse (parse string))
collect (coerce result 'string)))
(defun main ()
(dolist (input '("~/{Downloads,Pictures}/*.{jpg,gif,png}"
"It{{em,alic}iz,erat}e{d,}, please."
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!"
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"))
(write-line input)
(dolist (output (expand input))
(format t " ~A~%" output))
(terpri))) |
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
| #AWK | AWK |
# syntax: GAWK -f BRAZILIAN_NUMBERS.AWK
# converted from C
BEGIN {
split(",odd ,prime ",kinds,",")
for (i=1; i<=3; ++i) {
printf("first 20 %sBrazilian numbers:",kinds[i])
c = 0
n = 7
while (1) {
if (is_brazilian(n)) {
printf(" %d",n)
if (++c == 20) {
printf("\n")
break
}
}
switch (i) {
case 1:
n++
break
case 2:
n += 2
break
case 3:
do {
n += 2
} while (!is_prime(n))
break
}
}
}
exit(0)
}
function is_brazilian(n, b) {
if (n < 7) { return(0) }
if (!(n % 2) && n >= 8) { return(1) }
for (b=2; b<n-1; ++b) {
if (same_digits(n,b)) { return(1) }
}
return(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (!(n % 2)) { return(n == 2) }
if (!(n % 3)) { return(n == 3) }
while (d*d <= n) {
if (!(n % d)) { return(0) }
d += 2
if (!(n % d)) { return(0) }
d += 4
}
return(1)
}
function same_digits(n,b, f) {
f = n % b
n = int(n/b)
while (n > 0) {
if (n % b != f) { return(0) }
n = int(n/b)
}
return(1)
}
|
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
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
VDU 23,22,640;570;8,15,16,128
year% = 1969
PRINT TAB(38); year%
DIM dom%(2), mjd%(2), dim%(2)
FOR day% = 1 TO 7
days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " "
NEXT
FOR month% = 1 TO 10 STEP 3
PRINT
FOR col% = 0 TO 2
mjd%(col%) = FN_mjd(1, month% + col%, year%)
month$ = FN_date$(mjd%(col%), "MMMM")
PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$;
NEXT
FOR col% = 0 TO 2
PRINT TAB(col%*24 + 6) days$;
dim%(col%) = FN_dim(month% + col%, year%)
NEXT
dom%() = 1
col% = 0
REPEAT
dow% = FN_dow(mjd%(col%))
IF dom%(col%)<=dim%(col%) THEN
PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%);
dom%(col%) += 1
mjd%(col%) += 1
ENDIF
IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3
UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2)
PRINT
NEXT
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Kotlin | Kotlin | import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
class ToBeBroken {
@Suppress("unused")
private val secret: Int = 42
}
fun main(args: Array<String>) {
val tbb = ToBeBroken()
val props = ToBeBroken::class.declaredMemberProperties
for (prop in props) {
prop.isAccessible = true // make private properties accessible
println("${prop.name} -> ${prop.get(tbb)}")
}
} |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Logtalk | Logtalk | :- object(foo).
% be sure that context switching calls are allowed
:- set_logtalk_flag(context_switching_calls, allow).
% declare and define a private method
:- private(bar/1).
bar(1).
bar(2).
bar(3).
:- end_object. |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Lua | Lua | local function Counter()
-- These two variables are "private" to this function and can normally
-- only be accessed from within this scope, including by any function
-- created inside here.
local counter = {}
local count = 0
function counter:increment()
-- 'count' is an upvalue here and can thus be accessed through the
-- debug library, as long as we have a reference to this function.
count = count + 1
end
return counter
end
-- Create a counter object and try to access the local 'count' variable.
local counter = Counter()
for i = 1, math.huge do
local name, value = debug.getupvalue(counter.increment, i)
if not name then break end -- No more upvalues.
if name == "count" then
print("Found 'count', which is "..tostring(value))
-- If the 'counter.increment' function didn't access 'count'
-- directly then we would never get here.
break
end
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.
| #Common_Lisp | Common Lisp | ;;; brownian.lisp
;;; sbcl compile: first load and then (sb-ext:save-lisp-and-die "brownian" :executable t :toplevel #'brownian::main)
(ql:quickload "cl-gd")
(defpackage #:brownian
(:use #:cl #:cl-gd))
(in-package #:brownian)
(defvar *size* 512)
(defparameter bitmap (make-array *size*))
(dotimes (i *size*)
(setf (svref bitmap i) (make-array *size* :element-type 'bit)))
;;; is pixel at coord set? returns coord if so otherwise nil if not set or invalid
;;; type:pair->pair|nil
(defun set-p (coord)
(and coord (= (sbit (svref bitmap (car coord)) (cdr coord)) 1) coord))
;;; valid coord predicate, return its arg if valid or nil otherwise
;;; type:pair->pair|nil
(defun coord-p (coord)
(and ((lambda (v hi) (and (>= v 0) (< v hi))) (car coord) *size*)
((lambda (v hi) (and (>= v 0) (< v hi))) (cdr coord) *size*)
coord))
;;; valid coord predicate for the ith neighbour, return its arg if valid or nil otherwise
;;; type:pair->pair|nil
(defun coordi-p (coord i)
(coord-p (cons (+ (car coord) (nth i '(-1 -1 -1 0 0 1 1 1)))
(+ (cdr coord) (nth i '(-1 0 1 -1 1 -1 0 1))))))
;;; random walk until out of bounds or hit occupied pixel
;;; assumes start is valid vacant coord, return start or nil if off-grid
;;; type:pair->pair|nil
(defun random-walk (start)
(let ((next (coordi-p start (random 8))))
(if (set-p next) start
(and next (random-walk next)))))
;;; random walk until out of bounds or or adjacent to occupied pixel
;;; assumes start is valid vacant coord, return start or nil if off-grid
;;; type:pair->pair|nil
(defun random-walk2 (start)
(if (some #'set-p
(remove-if #'null (mapcar (lambda (i) (coordi-p start i)) '(0 1 2 3 4 5 6 7))))
start
(let ((next (coordi-p start (random 8))))
(and next (random-walk2 next)))))
(defparameter use-walk2 nil)
(defun main ()
(setf *random-state* (make-random-state t)) ;; randomize
(when (cdr sb-ext:*posix-argv*) (setf use-walk2 t)) ;; any cmd line arg -> use alt walk algorithm
(with-image* (*size* *size*)
(allocate-color 0 0 0) ; background color
;;; set the desired number of pixels in image as a pct (10%) of total
(let ((target (truncate (* 0.10 (* *size* *size*))))
(green (allocate-color 104 156 84)))
(defun write-pixel (coord)
(set-pixel (car coord) (cdr coord) :color green)
(setf (sbit (svref bitmap (car coord)) (cdr coord)) 1)
coord)
;; initial point set
(write-pixel (cons (truncate (/ *size* 2)) (truncate (/ *size* 2))))
;; iterate until target # of pixels are set
(do ((i 0 i)
(seed (cons (random *size*) (random *size*)) (cons (random *size*) (random *size*))))
((= i target) )
(let ((newcoord (and (not (set-p seed)) (if use-walk2 (random-walk2 seed) (random-walk seed)))))
(when newcoord
(write-pixel newcoord)
(incf i)
;; report every 5% of progress
(when (zerop (rem i (round (* target 0.05))))
(format t "~A% done.~%" (round (/ i target 0.01))))))))
(write-image-to-file "brownian.png"
:compression-level 6 :if-exists :supersede)))
|
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
| #BBC_BASIC | BBC BASIC | secret$ = ""
REPEAT
c$ = CHR$(&30 + RND(9))
IF INSTR(secret$, c$) = 0 secret$ += c$
UNTIL LEN(secret$) = 4
PRINT "Guess a four-digit number with no digit used twice."'
guesses% = 0
REPEAT
REPEAT
INPUT "Enter your guess: " guess$
IF LEN(guess$) <> 4 PRINT "Must be a four-digit number"
UNTIL LEN(guess$) = 4
guesses% += 1
IF guess$ = secret$ PRINT "You won after "; guesses% " guesses!" : END
bulls% = 0
cows% = 0
FOR i% = 1 TO 4
c$ = MID$(secret$, i%, 1)
IF MID$(guess$, i%, 1) = c$ THEN
bulls% += 1
ELSE IF INSTR(guess$, c$) THEN
cows% += 1
ENDIF
ENDIF
NEXT i%
PRINT "You got " ;bulls% " bull(s) and " ;cows% " cow(s)."
UNTIL FALSE
|
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Python | Python |
def bwt(s):
"""Apply Burrows-Wheeler transform to input string."""
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003" # Add start and end of text marker
table = sorted(s[i:] + s[:i] for i in range(len(s))) # Table of rotations of string
last_column = [row[-1:] for row in table] # Last characters of each row
return "".join(last_column) # Convert list of characters into string
def ibwt(r):
"""Apply inverse Burrows-Wheeler transform."""
table = [""] * len(r) # Make empty table
for i in range(len(r)):
table = sorted(r[i] + table[i] for i in range(len(r))) # Add a column of r
s = [row for row in table if row.endswith("\003")][0] # Find the correct row (ending in ETX)
return s.rstrip("\003").strip("\002") # Get rid of start and end markers
|
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
| #AWK | AWK |
#!/usr/bin/awk -f
BEGIN {
message = "My hovercraft is full of eels."
key = 1
cypher = caesarEncode(key, message)
clear = caesarDecode(key, cypher)
print "message: " message
print " cypher: " cypher
print " clear: " clear
exit
}
function caesarEncode(key, message) {
return caesarXlat(key, message, "encode")
}
function caesarDecode(key, message) {
return caesarXlat(key, message, "decode")
}
function caesarXlat(key, message, dir, plain, cypher, i, num, s) {
plain = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cypher = substr(plain, key+1) substr(plain, 1, key)
if (toupper(substr(dir, 1, 1)) == "D") {
s = plain
plain = cypher
cypher = s
}
s = ""
message = toupper(message)
for (i = 1; i <= length(message); i++) {
num = index(plain, substr(message, i, 1))
if (num) s = s substr(cypher, num, 1)
else s = s substr(message, i, 1)
}
return s
}
|
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
| #Free_Pascal | Free Pascal | ' version 02-07-2018
' compile with: fbc -s console
Dim As Double e , e1
Dim As ULongInt n = 1, n1 = 1
e = 1 / 1
While e <> e1
e1 = e
e += 1 / n
n1 += 1
n *= n1
Wend
Print "The value of e ="; e
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #FreeBASIC | FreeBASIC | ' version 02-07-2018
' compile with: fbc -s console
Dim As Double e , e1
Dim As ULongInt n = 1, n1 = 1
e = 1 / 1
While e <> e1
e1 = e
e += 1 / n
n1 += 1
n *= n1
Wend
Print "The value of e ="; e
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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)
| #Julia | Julia |
countbulls(a, b) = sum([a[i] == b[i] for i in 1:length(a)])
countcows(a, b) = sum([a[i] == b[j] for i in 1:length(a), j in 1:length(b) if i != j])
validate(a, b) = typeof(a) == Int && typeof(b) == Int && a >= 0 && b >= 0 && a + b < 5
function doguess()
poss = [a for a in collect(Base.product(1:9,1:9,1:9,1:9)) if length(unique(a))[1]==4]
while(length(poss) > 0)
ans = rand(poss, 1)[1]
while true
println("My guess: $(ans[1])$(ans[2])$(ans[3])$(ans[4]). How many bulls and cows?")
regres = match(r"\D*(\d+)\D*(\d+)", readline())
bul, cow = parse(Int,regres[1]), parse(Int,regres[2])
if(validate(bul, cow))
break
else
println("Please enter an integer each for bulls and cows.")
end
end
if(bul == 4)
return ans
end
filter!(i -> (countbulls(ans,i), countcows(ans, i)) == (bul, cow), poss)
end
Base.throw("ERROR: No solutions found. Inconsistent scoring by other player?")
end
answ = doguess()
println("The winning pick: $(answ[1])$(answ[2])$(answ[3])$(answ[4])")
|
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)
| #Kotlin | Kotlin | // version 1.1.2
import java.util.Random
fun countBullsAndCows(guess: IntArray, answer: IntArray): Pair<Int,Int> {
var bulls = 0
var cows = 0
for ((i, d) in guess.withIndex()) {
if (answer[i] == d) bulls++
else if (d in answer) cows++
}
return bulls to cows
}
fun main(args: Array<String>) {
val r = Random()
val choices = mutableListOf<IntArray>()
// generate all possible distinct 4 digit (1 to 9) integer arrays
for (i in 1..9) {
for (j in 1..9) {
if (j == i) continue
for (k in 1..9) {
if (k == i || k == j) continue
for (l in 1..9) {
if (l == i || l == j || l == k) continue
choices.add(intArrayOf(i, j, k, l))
}
}
}
}
// pick one at random as the answer
val answer = choices[r.nextInt(choices.size)]
// keep guessing, pruning the list as we go based on the score, until answer found
while (true) {
val guess = choices[r.nextInt(choices.size)]
val (bulls, cows) = countBullsAndCows(guess, answer)
println("Guess = ${guess.joinToString("")} Bulls = $bulls Cows = $cows")
if (bulls == 4) {
println("You've just found the answer!")
return
}
for (i in choices.size - 1 downTo 0) {
val (bulls2, cows2) = countBullsAndCows(choices[i], answer)
// if score is no better remove it from the list of choices
if (bulls2 <= bulls && cows2 <= cows) choices.removeAt(i)
}
if (choices.size == 0)
println("Something went wrong as no choices left! Aborting program")
}
} |
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.
| #Lua | Lua | FUNCTION PRINT_CAL(YEAR)
LOCAL MONTHS={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
"JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}
LOCAL DAYSTITLE="MO TU WE TH FR SA SU"
LOCAL DAYSPERMONTH={31,28,31,30,31,30,31,31,30,31,30,31}
LOCAL STARTDAY=((YEAR-1)*365+MATH.FLOOR((YEAR-1)/4)-MATH.FLOOR((YEAR-1)/100)+MATH.FLOOR((YEAR-1)/400))%7
IF YEAR%4==0 AND YEAR%100~=0 OR YEAR%400==0 THEN
DAYSPERMONTH[2]=29
END
LOCAL SEP=5
LOCAL MONTHWIDTH=DAYSTITLE:LEN()
LOCAL CALWIDTH=3*MONTHWIDTH+2*SEP
FUNCTION CENTER(STR, WIDTH)
LOCAL FILL1=MATH.FLOOR((WIDTH-STR:LEN())/2)
LOCAL FILL2=WIDTH-STR:LEN()-FILL1
RETURN STRING.REP(" ",FILL1)..STR..STRING.REP(" ",FILL2)
END
FUNCTION MAKEMONTH(NAME, SKIP,DAYS)
LOCAL CAL={
CENTER(NAME,MONTHWIDTH),
DAYSTITLE
}
LOCAL CURDAY=1-SKIP
WHILE #CAL<9 DO
LINE={}
FOR I=1,7 DO
IF CURDAY<1 OR CURDAY>DAYS THEN
LINE[I]=" "
ELSE
LINE[I]=STRING.FORMAT("%2D",CURDAY)
END
CURDAY=CURDAY+1
END
CAL[#CAL+1]=TABLE.CONCAT(LINE," ")
END
RETURN CAL
END
LOCAL CALENDAR={}
FOR I,MONTH IN IPAIRS(MONTHS) DO
LOCAL DPM=DAYSPERMONTH[I]
CALENDAR[I]=MAKEMONTH(MONTH, STARTDAY, DPM)
STARTDAY=(STARTDAY+DPM)%7
END
PRINT(CENTER("[SNOOPY]",CALWIDTH):UPPER(),"\N")
PRINT(CENTER("--- "..YEAR.." ---",CALWIDTH):UPPER(),"\N")
FOR Q=0,3 DO
FOR L=1,9 DO
LINE={}
FOR M=1,3 DO
LINE[M]=CALENDAR[Q*3+M][L]
END
PRINT(TABLE.CONCAT(LINE,STRING.REP(" ",SEP)):UPPER())
END
END
END
PRINT_CAL(1969)
|
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
| #Never | Never | extern "libm.so.6" func sinhf(x : float) -> float
extern "libm.so.6" func coshf(x : float) -> float
extern "libm.so.6" func powf(base : float, exp : float) -> float
extern "libm.so.6" func atanf(x : float) -> float
func main() -> int
{
var v1 = sinhf(1.0);
var v2 = coshf(1.0);
var v3 = powf(10.0, 2.0);
var pi = 4.0 * atanf(1.0);
printf(v1);
printf(v2);
printf(v3);
printf(pi);
printf(sinhf(1.0));
0
} |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #NewLISP | NewLISP | ; simple FFI interface on Mac OSX
(import "libc.dylib" "strdup")
(println (get-string (strdup "hello world")))
; or extended FFI interface on Mac OSX
(import "libc.dylib" "strdup" "char*" "char*")
(println (strdup "hello world"))
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Cubescript | Cubescript |
// No arguments
myfunction
// All functions can take a variable number of arguments.
// These can be accessed from within the function with the aliases:
// $arg1, $arg2, $arg3... $numargs tells the amount of args passed.
myfunction word "text string" 1 3.14
// Getting a function's return value
retval = (myfunction)
// Trying to do a variable lookup on a builtin function will return an empty
// string. This can be used to distinguish builtin functions from user-defined
// ones.
if (strcmp $echo "") [echo builtin function] // true
if (strcmp $myfunction "") [echo builtin function] // false
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Ring | Ring |
# Project : Cantor set
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("")
setgeometry(100,100,800,600)
label1 = new qlabel(win1) {
setgeometry(10,10,800,600)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(10)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
cantor(10,20,600)
endpaint()
}
label1 { setpicture(p1) show() }
return
func cantor(x,y,lens)
if lens >= 10
paint.drawline(x,y,x+lens,y)
y = y + 20
cantor(x,y,floor(lens/3))
cantor(x+floor(lens*2/3),y,floor(lens/3))
ok
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Ruby | Ruby | lines = 5
(0..lines).each do |exp|
seg_size = 3**(lines-exp-1)
chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "█"}
puts chars.map{ |c| c * seg_size }.join
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
| #PureBasic | PureBasic | Procedure.i reduce(List l(),op$="+")
If FirstElement(l())
x=l()
While NextElement(l())
Select op$
Case "+" : x+l()
Case "-" : x-l()
Case "*" : x*l()
EndSelect
Wend
EndIf
ProcedureReturn x
EndProcedure
NewList fold()
For i=1 To 5 : AddElement(fold()) : fold()=i : Next
Debug reduce(fold())
Debug reduce(fold(),"-")
Debug reduce(fold(),"*") |
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}
| #Rust | Rust | fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
let mut res = vec![];
let mut list_iter = lists.iter();
if let Some(first_list) = list_iter.next() {
for &i in first_list {
res.push(vec![i]);
}
}
for l in list_iter {
let mut tmp = vec![];
for r in res {
for &el in l {
let mut tmp_el = r.clone();
tmp_el.push(el);
tmp.push(tmp_el);
}
}
res = tmp;
}
res
}
fn main() {
let cases = vec![
vec![vec![1, 2], vec![3, 4]],
vec![vec![3, 4], vec![1, 2]],
vec![vec![1, 2], vec![]],
vec![vec![], vec![1, 2]],
vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]],
vec![vec![1, 2, 3], vec![30], vec![500, 100]],
vec![vec![1, 2, 3], vec![], vec![500, 100]],
];
for case in cases {
println!(
"{}\n{:?}\n",
case.iter().map(|c| format!("{:?}", c)).collect::<Vec<_>>().join(" × "),
cartesian_product(&case)
)
}
}
|
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
| #GAP | GAP | Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);
Catalan2 := n -> Binomial(2*n, n)/(n + 1);
Catalan3 := function(n)
local k, c;
c := 1;
k := 0;
while k < n do
k := k + 1;
c := 2*(2*k - 1)*c/(k + 1);
od;
return c;
end;
Catalan4_memo := [1];
Catalan4 := function(n)
if not IsBound(Catalan4_memo[n + 1]) then
Catalan4_memo[n + 1] := Sum([0 .. n - 1], i -> Catalan4(i)*Catalan4(n - 1 - i));
fi;
return Catalan4_memo[n + 1];
end;
# The first fifteen: 0 to 14 !
List([0 .. 14], Catalan1);
List([0 .. 14], Catalan2);
List([0 .. 14], Catalan3);
List([0 .. 14], Catalan4);
# Same output for all four:
# [ 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440 ] |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #D | D | import std.stdio, std.typecons, std.array, std.range, std.algorithm, std.string;
Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth)
pure nothrow @safe {
string[] sout;
auto comma = false;
while (!s.empty) {
// {const g, s} = getItems(s, depth);
const r = getItems(s, depth);
const g = r[0];
s = r[1];
if (s.empty)
break;
sout ~= g;
if (s[0] == '}') {
if (comma)
return typeof(return)(tuple(sout, s[1 .. $]));
return typeof(return)(tuple(
sout.map!(a => '{' ~ a ~ '}').array, s[1 .. $]));
}
if (s[0] == ',') {
comma = true;
s = s[1 .. $];
}
}
return typeof(return)();
}
Tuple!(string[], string) getItems(string s, in uint depth=0) pure @safe nothrow {
auto sout = [""];
while (!s.empty) {
auto c = s[0 .. 1];
if (depth && (c == "," || c == "}"))
return tuple(sout, s);
if (c == "{") {
/*const*/ auto x = getGroup(s.dropOne, depth + 1);
if (!x.isNull) {
sout = cartesianProduct(sout, x[0])
.map!(ab => ab[0] ~ ab[1])
.array;
s = x[1];
continue;
}
}
if (c == "\\" && s.length > 1) {
c ~= s[1];
s = s[1 .. $];
}
sout = sout.map!(a => a ~ c).array;
s = s[1 .. $];
}
return tuple(sout, s);
}
void main() @safe {
immutable testCases = r"~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
a{b{1,2}c
a{1,2}b}c
a{1,{2},3}b
a{b{1,2}c{}}
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
{a,b{{1,2}e}f";
foreach (const s; testCases.splitLines)
writefln("%s\n%-( %s\n%)\n", s, s.getItems[0]);
} |
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
| #C | C | #include <stdio.h>
typedef char bool;
#define TRUE 1
#define FALSE 0
bool same_digits(int n, int b) {
int f = n % b;
n /= b;
while (n > 0) {
if (n % b != f) return FALSE;
n /= b;
}
return TRUE;
}
bool is_brazilian(int n) {
int b;
if (n < 7) return FALSE;
if (!(n % 2) && n >= 8) return TRUE;
for (b = 2; b < n - 1; ++b) {
if (same_digits(n, b)) return TRUE;
}
return FALSE;
}
bool is_prime(int n) {
int d = 5;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
int main() {
int i, c, n;
const char *kinds[3] = {" ", " odd ", " prime "};
for (i = 0; i < 3; ++i) {
printf("First 20%sBrazilian numbers:\n", kinds[i]);
c = 0;
n = 7;
while (TRUE) {
if (is_brazilian(n)) {
printf("%d ", n);
if (++c == 20) {
printf("\n\n");
break;
}
}
switch (i) {
case 0: n++; break;
case 1: n += 2; break;
case 2:
do {
n += 2;
} while (!is_prime(n));
break;
}
}
}
for (n = 7, c = 0; c < 100000; ++n) {
if (is_brazilian(n)) c++;
}
printf("The 100,000th Brazilian number: %d\n", n - 1);
return 0;
} |
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
| #Befunge | Befunge | "P"00p&>:::4%!\"d"%*\45*:*%!+!!65*+31p:1-:::"I"5**\4/+\"d"/-\45*:*/+1+7%:0v
J!F?M!A M!J J!A!S O!N D!SaFrThWeTuMoSuvp01:_1#!-#%:#\>#+6<v-2g1+1g01p1p01:<
January February March April >:45**00g\-\1-:v:<<6>+7%:10g2+:38*\`|
May June July August v02-1:+4*-4\`\4:/_$:^^:/*2+92+2:g00$$$<
September October November December>p:45*+10g*\--2/00g4-2/>:#,1#*-#8\#4_$v
>20g>:#,1#*-#8\#4_$6"$S" v. .vp040\$_4#!8#\*#-,#1>#:<+5g03g01:,,:+55<0.p03<
^_v#:-1$_v#!:,*84,g1+1,< < ^ >::4%9*40g:8`!#v_$$$1+v^+g02_#v$#,$#+5<^_v#`\<
-#8\#4_$7>1-:2*64*+:1g>^ ^ ^,g+2/4\+p04+1:<>1#\-#<:66+\^ >>$10g30g>:#,1#*
> > $$55+,6>>40p:10g30g>:#,1#*-#8\#4_$>\:2*:1+1g2-50p1g640g-7*1+\-7v v@,<6
2:+g01$_55+,^ > > > > #^>#g>#0>#2_v v*2!!\%+55:\/+55:**`0\!`g05:::\< >2-^^
->:> >#^>#<>#<^#!:-1g04$$ < < < < < >4+8*+\:!!2*4+8*+,,48*,1+\1-:>#^_$$1+\1 |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Group Alfa {
Private:
X=10, Y=20
Public:
Module SetXY (.X, .Y) {}
Module Print {
Print .X, .Y
}
}
Alfa.Print ' 10 20
\\ we have to KnΟw position in group
\\ so we make references from two first
Read From Alfa, K, M
Print K=10, M=20
K+=10
M+=1000
Alfa.Print ' 20 1020
}
CheckIt
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Nim | Nim | type Foo* = object
a: string
b: string
c: int
proc createFoo*(a, b, c): Foo =
Foo(a: a, b: b, c: c) |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface Example : NSObject {
@private
NSString *_name;
}
- (instancetype)initWithName:(NSString *)name;
@end
@implementation Example
- (NSString *)description {
return [NSString stringWithFormat:@"Hello, I am %@", _name];
}
- (instancetype)initWithName:(NSString *)name {
if ((self = [super init])) {
_name = [name copy];
}
return self;
}
@end
int main (int argc, const char * argv[]) {
@autoreleasepool{
Example *foo = [[Example alloc] initWithName:@"Eric"];
// get private field
NSLog(@"%@", [foo valueForKey:@"name"]);
// set private field
[foo setValue:@"Edith" forKey:@"name"];
NSLog(@"%@", foo);
}
return 0;
} |
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.
| #D | D | void main() {
import core.stdc.stdio, std.random, grayscale_image;
enum uint side = 600; // Square world side.
enum uint num_particles = 10_000;
static assert(side > 2 && num_particles < (side ^^ 2 * 0.7));
auto rng = unpredictableSeed.Xorshift;
ubyte[side][side] W; // World.
W[side / 2][side / 2] = 1; // Set tree root.
foreach (immutable _; 0 .. num_particles) {
// Random initial particle position.
OVER: uint x, y;
do {
x = uniform(1, side - 1, rng);
y = uniform(1, side - 1, rng);
} while (W[y][x]); // Assure the chosen cell is empty.
while (W[y-1][x-1] + W[y-1][x] + W[y-1][x+1] +
W[y][x-1] + W[y][x+1] +
W[y+1][x-1] + W[y+1][x] + W[y+1][x+1] == 0) {
// Randomly choose a direction (Moore neighborhood).
uint dxy = uniform(0, 8, rng);
if (dxy > 3) dxy++; // To avoid the center.
x += (dxy % 3) - 1;
y += (dxy / 3) - 1;
if (x < 1 || x >= side - 1 || y < 1 || y >= side - 1)
goto OVER;
}
W[y][x] = 1; // Touched, set the cell.
}
ubyte[] data = (&W[0][0])[0 .. side ^^ 2]; // Flat view.
data[] += 255;
Image!ubyte.fromData(data, side, side).savePGM("brownian_tree.pgm");
} |
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
| #BCPL | BCPL | get "libhdr"
static $( randstate = ? $)
let randdigit() = valof
$( let x = ?
$( randstate := random(randstate)
x := (randstate >> 7) & 15
$) repeatuntil 0 < x <= 9
resultis x
$)
let gensecret(s) be
for i=0 to 3
s!i := randdigit() repeatuntil valof
$( for j=0 to i-1 if s!i = s!j then resultis false
resultis true
$)
let bulls(secret, guess) = valof
$( let x = 0
for i=0 to 3 if secret!i = guess!i then x := x + 1
resultis x
$)
let cows(secret, guess) = valof
$( let x = 0
for i=0 to 3
for j=0 to 3
unless i=j
if secret!i = guess!j then x := x + 1
resultis x
$)
let readguess(guess) be
$( let g, v = ?, true
writes("Enter a guess, or 0 to quit: ")
g := readn()
if g=0 then finish
for i=3 to 0 by -1
$( guess!i := g rem 10
g := g / 10
$)
for i=0 to 2 for j = i+1 to 3
v := v & guess!i ~= 0 & guess!j ~= 0 & guess!i ~= guess!j
if v then return
writes("Invalid guess.*N")
$) repeat
let play(secret) be
$( let tries, b, c = 0, ?, ?
let guess = vec 3
$( readguess(guess)
b := bulls(secret, guess)
c := cows(secret, guess)
writef("Bulls: %N, cows: %N*N", b, c);
tries := tries + 1
$) repeatuntil b = 4
writef("You win in %N tries.*N", tries)
$)
let start() be
$( let secret = vec 3
writes("Bulls and cows*N----- --- ----*N")
writes("Please enter a random seed: ")
randstate := readn()
wrch('*N')
gensecret(secret)
play(secret)
$) |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Raku | Raku | # STX can be any character that doesn't appear in the text.
# Using a visible character here for ease of viewing.
constant \STX = '👍';
# Burrows-Wheeler transform
sub transform (Str $s is copy) {
note "String can't contain STX character." and exit if $s.contains: STX;
$s = STX ~ $s;
(^$s.chars).map({ $s.comb.list.rotate: $_ }).sort[*;*-1].join
}
# Burrows-Wheeler inverse transform
sub ɯɹoɟsuɐɹʇ (Str $s) {
my @t = $s.comb.sort;
@t = ($s.comb Z~ @t).sort for 1..^$s.chars;
@t.first( *.ends-with: STX ).chop
}
# TESTING
for |<BANANA dogwood SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES>,
'TO BE OR NOT TO BE OR WANT TO BE OR NOT?', "Oops{STX}"
-> $phrase {
say 'Original: ', $phrase;
say 'Transformed: ', transform $phrase;
say 'Inverse transformed: ', ɯɹoɟsuɐɹʇ transform $phrase;
say '';
} |
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
| #Babel | Babel | ((main
{"The quick brown fox jumps over the lazy dog.\n"
dup <<
17 caesar_enc !
dup <<
17 caesar_dec !
<<})
(caesar_enc
{ 2 take
{ caesar_enc_loop ! }
nest })
(caesar_enc_loop {
give
<- str2ar
{({ dup is_upper ! }
{ 0x40 -
-> dup <-
encrypt !
0x40 + }
{ dup is_lower ! }
{ 0x60 -
-> dup <-
encrypt !
0x60 + }
{ 1 }
{fnord})
cond}
eachar
collect !
ls2lf ar2str})
(collect { -1 take })
(encrypt { + 1 - 26 % 1 + })
(caesar_dec { <- 26 -> - caesar_enc ! })
(is_upper
{ dup
<- 0x40 cugt ->
0x5b cult
cand })
(is_lower
{ dup
<- 0x60 cugt ->
0x7b cult
cand })) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
###sysinclude math.uh
1.0e-15 sto EPSILON
one fact
2. sto e
2 sto n
((
@e sto e0
#g @n++ prd fact
1.0 @fact !(#d) / sum e
( @e @e0 - abs @EPSILON < )))
."e = " @e printnl
end
{ „EPSILON” }
{ „fact” }
{ „e” }
{ „e0” }
{ „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
| #Furor | Furor |
###sysinclude math.uh
1.0e-15 sto EPSILON
one fact
2. sto e
2 sto n
((
@e sto e0
#g @n++ prd fact
1.0 @fact !(#d) / sum e
( @e @e0 - abs @EPSILON < )))
."e = " @e printnl
end
{ „EPSILON” }
{ „fact” }
{ „e” }
{ „e0” }
{ „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)
| #Liberty_BASIC | Liberty BASIC |
guesses =0
do while len( secret$) <4 ' zero not allowed <<<<<<<<<
n$ =chr$( int( rnd( 1) *9) +49)
if not( instr( secret$, n$)) then secret$ =secret$ +n$
loop
print " Secretly, my opponent just chose a number. But she didn't tell anyone! "; secret$; "."
print " I can however be given a score for my guesses."
for i =1234 to 9876 ' <<<<<<<<<
if check( str$( i)) =0 then available$ =available$ +" " +str$( i): k =k +1
next i
available$ =trim$( available$) ' remove the surplus, leading space
print
print "Currently holding "; k; " possible numbers. "
while 1
guess$ =word$( available$, 1 +int( k *rnd( 1)), " ")
print
print "Computer guessed "; guess$; " & got ";
bulls =0
cows =0
guesses =guesses +1
r$ =score$( guess$, secret$)
bulls =val( word$( r$, 1, ","))
cows =val( word$( r$, 2, ","))
print bulls; " bull(s), and "; cows; " cow(s), .... ";
if guess$ =secret$ then
print "Computer won after "; guesses; " guesses!";
secs =( time$( "seconds") -now +86400) mod 86400
print " That took "; secs; " seconds. ENDED!"
print
print " Now scroll right to see original choice and check!"
exit while
end if
print " so possible numbers are now only..."
kk =0
new$ =""
for j =1 to k
bullsT =0
cowsT =0
possible$ =word$( available$, j, " ")
r$ =score$( guess$, possible$)
bullsT =val( word$( r$, 1, ","))
cowsT =val( word$( r$, 2, ","))
if ( bullsT =bulls) and ( cowsT =cows) then
new$ =new$ +" " +possible$ ' keep those with same score
kk =kk +1
print possible$; " ";
if ( kk mod 20) =0 then print
end if
scan
next j
available$ =trim$( new$)
k =kk
scan
wend
end
function score$( a$, b$) ' return as a csv string the number of bulls & cows.
bulls = 0: cows = 0
for i = 1 to 4
c$ = mid$( a$, i, 1)
if mid$( b$, i, 1) = c$ then
bulls = bulls + 1
else
if instr( b$, c$) <>0 and instr( b$, c$) <>i then cows = cows + 1
end if
next i
score$ =str$( bulls); ","; str$( cows)
end function
function check( i$)
check =0 ' zero flags available: 1 means not available
for i =1 to 3
for j =i +1 to 4
if mid$( i$, i, 1) =mid$( i$, j, 1) then check =1
next j
next i
if instr( i$, "0") then check =1
end function
|
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.
| #M2000_Interpreter | M2000 Interpreter |
\\ Calendar - for "REAL" programmers
\\ All statements in UPPERCASE
\\ Output to 132 characters console - as a line printer
\\ USE COURIER NEW (FONT "COURIER NEW")
\\ CHANGE THE VALUE OF PRINT_IT TO TRUE FOR PRINTING
GLOBAL CONST PRINT_IT AS BOOLEAN=FALSE
MODULE GLOBAL SNOOPY {
IF NOT PRINT_IT THEN CURSOR 0,ROW ELSE IF ROW>0 THEN PAGE 1
PRINT $(,8)
PRINT #-2, {
XXXX
X XX
X *** X XXXXX
X ***** X XXX XX
XXXX ******* XXX XXXX XX
XX X ****** XXXXXXXXX El@ XX XXX
XX X **** X X** X
X XX XX X X***X
X //XXXX X XXXX
X // X XX
X // X XXXXXXXXXXXXXXXXXX/
X XXX// X X
X X X X X
X X X X X
X X X X X XX
X X X X X XXX XX
X XXX X X X X X X
X X X XX X XXXX
X X XXXXXXXX\ XX XX X
XX XX X X @X XX
XX XXXX XXXXXX/ X XXXX
XXX XX*** X X
XXXXXXXXXXXXX * * X X
*---* X X X
*-* * XXX X X
*- * XXX X
*- *X XXX
*- *X X XXX
*- *X X XX
*- *XX X X
* *X* X X X
* *X * X X X
* * X** X XXXX X
* * X** XX X X
* ** X** X XX X
* ** X* XXX X X
* ** XX XXXX XXX
* * * XXXX X X
* * * X X X
=======******* * * X X XXXXXXXX\
* * * /XXXXX XXXXXXXX\ )
=====********** * X ) \ )
====* * X \ \ )XXXXX
=========********** XXXXXXXXXXXXXXXXXXXXXX
}
}
MODULE CALENDAR (YEAR, LOCALEID) {
FUNCTION GETMAX(YEAR, MONTH) {
A=DATE(STR$(YEAR)+"-"+STR$(MONTH)+"-1")
MAX=32
DO {
MAX--
M=VAL(STR$(CDATE(A,0,0,MAX), "M"))
} UNTIL M=MONTH
=MAX+1
}
FUNCTION SKIPMO(YEAR, MONTH) {
A=DATE(STR$(YEAR)+"-"+STR$(MONTH)+"-1")
=(VAL(STR$(A, "W"))-8) MOD 7 +7
}
FUNCTION TITLE$(A$) {
=UCASE$(LEFT$(A$,1))+LCASE$(MID$(A$, 2))
}
LOCALE LOCALEID
IF NOT PRINT_IT THEN CURSOR 0,HEIGHT-1 ' LAST LINE, SO EACH NEW LINE SCROLL ALL LINES UP
SNOOPY
PRINT UNDER ' PRINT UNDERLINE
PRINT OVER $(2), YEAR
PRINT
FOR J=0 TO 1 {
PRINT
FOR I=1 TO 6 {
MONTH=I+J*6
PRINT PART @((I-1)*22+1), $(2,21), UCASE$(LOCALE$(55+MONTH))
}
PRINT
DIM SKIP(1 TO 6), COUNT(1 TO 6), D(1 TO 6)=1
FOR I=1 TO 6 {
MONTH=I+J*6
IF I>1 THEN PRINT " ";
FOR K=42 TO 48 :PRINT " ";UCASE$(LEFT$(LOCALE$(K),2));:NEXT K
SKIP(I)=SKIPMO(YEAR, MONTH)
COUNT(I)=GETMAX(YEAR, MONTH)
}
PRINT
IF PRINT_IT ELSE REFRESH 1000
FOR I=1 TO 6 {
IF I>1 THEN PRINT " ";
FOR K=1 TO 7 {
SKIP(I)--
IF SKIP(I)>0 THEN PRINT " "; :CONTINUE
COUNT(I)--
PRINT FORMAT$(" {0::-2}", D(I));
D(I)++
}
}
PRINT
IF PRINT_IT ELSE REFRESH 1000
PRINT @(0)
FOR M=1 TO 5 {
FOR I=1 TO 6 {
IF I>1 THEN PRINT " ";
FOR K=1 TO 7 {
COUNT(I)--
IF COUNT(I)<0 THEN PRINT " "; : CONTINUE
PRINT FORMAT$(" {0::-2}", D(I));
D(I)++
}
}
PRINT
IF PRINT_IT ELSE REFRESH 1000
}
}
}
WHILE INKEY$<>"" : END WHILE
IF PRINT_IT THEN PRINTING ON ELSE REFRESH 1000
FONT "COURIER NEW"
PEN 0
CLS 15, 0
FORM 132,68
CALENDAR 1966, 1032 ' GREEK
GOSUB WAITKEY_OR_MOUSE
FOR I=2020 TO 2026
CALENDAR I, 1033 ' ENGLISH
GOSUB WAITKEY_OR_MOUSE
NEXT I
IF PRINT_IT THEN PRINTING OFF ELSE REFRESH 50
CLEAR ' CLEAR VARIABLES FROM THIS MODULE
END
WAITKEY_OR_MOUSE:
IF PRINT_IT THEN RETURN
WHILE INKEY$="" AND MOUSE=0
END WHILE
RETURN
|
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
| #Nim | Nim | proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
echo strcmp("abc", "def")
echo strcmp("hello", "hello")
proc printf(formatstr: cstring) {.header: "<stdio.h>", varargs.}
var x = "foo"
printf("Hello %d %s!\n", 12, x) |
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
| #OCaml | OCaml | void myfunc_a();
float myfunc_b(int, float);
char *myfunc_c(int *, int); |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #D | D | import std.traits;
enum isSubroutine(alias F) = is(ReturnType!F == void);
void main() {
void foo1() {}
// Calling a function that requires no arguments:
foo1();
foo1; // Alternative syntax.
void foo2(int x, int y) {}
immutable lambda = function int(int x) => x ^^ 2;
// Calling a function with a fixed number of arguments:
foo2(1, 2);
foo2(1, 2);
cast(void)lambda(1);
void foo3(int x, int y=2) {}
// Calling a function with optional arguments:
foo3(1);
foo3(1, 3);
int sum(int[] arr...) {
int tot = 0;
foreach (immutable x; arr)
tot += x;
return tot;
}
real sum2(Args...)(Args arr) {
typeof(return) tot = 0;
foreach (immutable x; arr)
tot += x;
return tot;
}
// Calling a function with a variable number of arguments:
assert(sum(1, 2, 3) == 6);
assert(sum(1, 2, 3, 4) == 10);
assert(sum2(1, 2.5, 3.5) == 7);
// Calling a function with named arguments:
// Various struct or tuple-based tricks can be used for this,
// but currently D doesn't have named arguments.
// Using a function in statement context (?):
if (1)
foo1;
// Using a function in first-class context within an expression:
assert(sum(1) == 1);
auto foo4() { return 1; }
// Obtaining the return value of a function:
immutable x = foo4;
// Distinguishing built-in functions and user-defined functions:
// There are no built-in functions, beside the operators, and
// pseudo-functions like assert().
int myFynction(int x) { return x; }
void mySubroutine(int x) {}
// Distinguishing subroutines and functions:
// (A subroutine is merely a function that has no explicit
// return statement and will return void).
pragma(msg, isSubroutine!mySubroutine); // Prints: true
pragma(msg, isSubroutine!myFynction); // Prints: false
void foo5(int a, in int b, ref int c, out int d, lazy int e, scope int f) {}
// Stating whether arguments are passed by value, by reference, etc:
alias STC = ParameterStorageClass;
alias psct = ParameterStorageClassTuple!foo5;
static assert(psct.length == 6); // Six parameters.
static assert(psct[0] == STC.none);
static assert(psct[1] == STC.none);
static assert(psct[2] == STC.ref_);
static assert(psct[3] == STC.out_);
static assert(psct[4] == STC.lazy_);
static assert(psct[5] == STC.scope_);
// There are also inout and auto ref.
int foo6(int a, int b) { return a + b; }
// Is partial application possible and how:
import std.functional;
alias foo6b = partial!(foo6, 5);
assert(foo6b(6) == 11);
} |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Rust | Rust |
use convert_base::Convert;
use std::fmt;
struct CantorSet {
cells: Vec<Vec<bool>>,
}
fn number_to_vec(n: usize) -> Vec<u32> {
// for the conversion we need the digits in reverse order
// i.e the least significant digit in the first element of the vector
n.to_string()
.chars()
.rev()
.map(|c| c.to_digit(10).unwrap())
.collect()
}
impl CantorSet {
fn new(lines: usize) -> CantorSet {
// Convert from base 10- to base 3
let mut base = Convert::new(10, 3);
let mut cells: Vec<Vec<bool>> = vec![];
for line in 0..lines {
// calculate how many repeating sequence will be in the given line
let segment_size = 3_usize.pow((lines - line - 1) as u32);
let segment: Vec<bool> = (0..3_usize.pow(line as u32))
.map(|n| {
let output = base.convert::<u32, u32>(&number_to_vec(n));
// return false in case the base 3 number contains at least one "1"
// otherwise return true
!output.contains(&1)
})
.collect();
// copy the segment "segment_size" time
let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size);
for c in segment.iter() {
accum.extend(std::iter::repeat(*c).take(segment_size))
}
cells.push(accum);
}
CantorSet { cells }
}
}
impl fmt::Display for CantorSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for line in self.cells.iter() {
for c in line {
write!(f, "{}", if *c { "█" } else { " " })?
}
writeln!(f)?;
}
Ok(())
}
}
fn main() {
let cs = CantorSet::new(5);
println!("Cantor set:");
println!("{}", cs);
}
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Scala | Scala | object CantorSetQD extends App {
val (width, height) = (81, 5)
val lines = Seq.fill[Array[Char]](height)(Array.fill[Char](width)('*'))
def cantor(start: Int, len: Int, index: Int) {
val seg = len / 3
println(start, len, index)
if (seg != 0) {
for (i <- index until height;
j <- (start + seg) until (start + seg * 2)) lines(i)(j) = ' '
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
}
}
cantor(0, width, 1)
lines.foreach(l => println(l.mkString))
} |
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
| #Python | Python | >>> # Python 2.X
>>> from operator import add
>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]
>>> help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
>>> reduce(add, listoflists, [])
['the', 'cat', 'sat', 'on', 'the', 'mat']
>>> |
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}
| #Scala | Scala | def cartesianProduct[T](lst: List[T]*): List[List[T]] = {
/**
* Prepend single element to all lists of list
* @param e single elemetn
* @param ll list of list
* @param a accumulator for tail recursive implementation
* @return list of lists with prepended element e
*/
def pel(e: T,
ll: List[List[T]],
a: List[List[T]] = Nil): List[List[T]] =
ll match {
case Nil => a.reverse
case x :: xs => pel(e, xs, (e :: x) :: a )
}
lst.toList match {
case Nil => Nil
case x :: Nil => List(x)
case x :: _ =>
x match {
case Nil => Nil
case _ =>
lst.par.foldRight(List(x))( (l, a) =>
l.flatMap(pel(_, a))
).map(_.dropRight(x.size))
}
}
} |
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
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
var b, c big.Int
for n := int64(0); n < 15; n++ {
fmt.Println(c.Div(b.Binomial(n*2, n), c.SetInt64(n+1)))
}
} |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Elixir | Elixir | defmodule Brace_expansion do
def getitem(s), do: getitem(String.codepoints(s), 0, [""])
defp getitem([], _, out), do: {out,[]}
defp getitem([c|_]=s, depth, out) when depth>0 and (c == "," or c == "}"), do: {out,s}
defp getitem([c|t], depth, out) do
x = getgroup(t, depth+1, [], false)
if (c == "{") and x do
{y, z} = x
out2 = for a <- out, b <- y, do: a<>b
getitem(z, depth, out2)
else
if c == "\\" and length(t) > 0 do
c2 = c <> hd(t)
getitem(tl(t), depth, Enum.map(out, fn a -> a <> c2 end))
else
getitem(t, depth, Enum.map(out, fn a -> a <> c end))
end
end
end
defp getgroup([], _, _, _), do: nil
defp getgroup(s, depth, out, comma) do
{g, s2} = getitem(s, depth, [""])
if s2 == [] do
nil
else
out2 = out ++ g
case hd(s2) do
"}" -> if comma, do: {out2, tl(s2)},
else: {Enum.map(out2, &"{#{&1}}"), tl(s2)}
"," -> getgroup(tl(s2), depth, out2, true)
_ -> getgroup(s2, depth, out2, comma)
end
end
end
end
test_cases = ~S"""
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
""" |> String.split("\n", trim: true)
Enum.each(test_cases, fn s ->
IO.puts s
Brace_expansion.getitem(s)
|> elem(0)
|> Enum.each(fn str -> IO.puts "\t#{str}" end)
IO.puts ""
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
| #Go | Go | package expand
// Expander is anything that can be expanded into a slice of strings.
type Expander interface {
Expand() []string
}
// Text is a trivial Expander that expands to a slice with just itself.
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
// Alternation is an Expander that expands to the union of its
// members' expansions.
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
// Sequence is an Expander that expands to the combined sequence of its
// members' expansions.
type Sequence []Expander
func (seq Sequence) Expand() []string {
if len(seq) == 0 {
return nil
}
out := seq[0].Expand()
for _, e := range seq[1:] {
out = combine(out, e.Expand())
}
return out
}
func combine(al, bl []string) []string {
out := make([]string, 0, len(al)*len(bl))
for _, a := range al {
for _, b := range bl {
out = append(out, a+b)
}
}
return out
}
// Currently only single byte runes are supported for these.
const (
escape = '\\'
altStart = '{'
altEnd = '}'
altSep = ','
)
type piT struct{ pos, cnt, depth int }
type Brace string
// Expand takes an input string and returns the expanded list of
// strings. The input string can contain any number of nested
// alternation specifications of the form "{A,B}" which is expanded to
// the strings "A", then "B".
//
// E.g. Expand("a{2,1}b{X,Y,X}c") returns ["a2bXc", "a2bYc", "a2bXc",
// "a1bXc", "a1bYc", "a1bXc"].
//
// Unmatched '{', ',', and '}' characters are passed through to the
// output. The special meaning of these characters can be escaped with
// '\', (which itself can be escaped).
// Escape characters are not removed, but passed through to the output.
func Expand(s string) []string { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
s := string(b)
//log.Printf("Exapand(%#q)\n", s)
var posInfo []piT
var stack []int // indexes into posInfo
removePosInfo := func(i int) {
end := len(posInfo) - 1
copy(posInfo[i:end], posInfo[i+1:])
posInfo = posInfo[:end]
}
inEscape := false
for i, r := range s {
if inEscape {
inEscape = false
continue
}
switch r {
case escape:
inEscape = true
case altStart:
stack = append(stack, len(posInfo))
posInfo = append(posInfo, piT{i, 0, len(stack)})
case altEnd:
if len(stack) == 0 {
continue
}
si := len(stack) - 1
pi := stack[si]
if posInfo[pi].cnt == 0 {
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == len(stack) {
removePosInfo(pi)
} else {
pi++
}
}
} else {
posInfo = append(posInfo, piT{i, -2, len(stack)})
}
stack = stack[:si]
case altSep:
if len(stack) == 0 {
continue
}
posInfo = append(posInfo, piT{i, -1, len(stack)})
posInfo[stack[len(stack)-1]].cnt++
}
}
//log.Println("stack:", stack)
for len(stack) > 0 {
si := len(stack) - 1
pi := stack[si]
depth := posInfo[pi].depth
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == depth {
removePosInfo(pi)
} else {
pi++
}
}
stack = stack[:si]
}
return buildExp(s, 0, posInfo)
}
func buildExp(s string, off int, info []piT) Expander {
if len(info) == 0 {
return Text(s)
}
//log.Printf("buildExp(%#q, %d, %v)\n", s, off, info)
var seq Sequence
i := 0
var dj, j, depth int
for dk, piK := range info {
k := piK.pos - off
switch s[k] {
case altStart:
if depth == 0 {
dj = dk
j = k
depth = piK.depth
}
case altEnd:
if piK.depth != depth {
continue
}
if j > i {
seq = append(seq, Text(s[i:j]))
}
alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
seq = append(seq, alt)
i = k + 1
depth = 0
}
}
if j := len(s); j > i {
seq = append(seq, Text(s[i:j]))
}
if len(seq) == 1 {
return seq[0]
}
return seq
}
func buildAlt(s string, depth, off int, info []piT) Alternation {
//log.Printf("buildAlt(%#q, %d, %d, %v)\n", s, depth, off, info)
var alt Alternation
i := 0
var di int
for dk, piK := range info {
if piK.depth != depth {
continue
}
if k := piK.pos - off; s[k] == altSep {
sub := buildExp(s[i:k], i+off, info[di:dk])
alt = append(alt, sub)
i = k + 1
di = dk + 1
}
}
sub := buildExp(s[i:], i+off, info[di:])
alt = append(alt, sub)
return alt
} |
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
| #C.23 | C# | using System;
class Program {
static bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) if (n % b != f) return false;
return true;
}
static bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0) return true;
for (int b = 2; b < n - 1; b++) if (sameDigits(n, b)) return true;
return false;
}
static bool isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false; d += 2;
if (n % d == 0) return false; d += 4;
}
return true;
}
static void Main(string[] args) {
foreach (string kind in ",odd ,prime ".Split(',')) {
bool quiet = false; int BigLim = 99999, limit = 20;
Console.WriteLine("First {0} {1}Brazilian numbers:", limit, kind);
int c = 0, n = 7;
while (c < BigLim) {
if (isBrazilian(n)) {
if (!quiet) Console.Write("{0:n0} ", n);
if (++c == limit) { Console.Write("\n\n"); quiet = true; }
}
if (quiet && kind != "") continue;
switch (kind) {
case "": n++; break;
case "odd ": n += 2; break;
case "prime ":
while (true) {
n += 2;
if (isPrime(n)) break;
} break;
}
}
if (kind == "") Console.WriteLine("The {0:n0}th Brazilian number is: {1:n0}\n", BigLim + 1, n);
}
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int width = 80, year = 1969;
int cols, lead, gap;
const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
struct months {
const char *name;
int days, start_wday, at;
} months[12] = {
{ "January", 31, 0, 0 },
{ "February", 28, 0, 0 },
{ "March", 31, 0, 0 },
{ "April", 30, 0, 0 },
{ "May", 31, 0, 0 },
{ "June", 30, 0, 0 },
{ "July", 31, 0, 0 },
{ "August", 31, 0, 0 },
{ "September", 30, 0, 0 },
{ "October", 31, 0, 0 },
{ "November", 30, 0, 0 },
{ "December", 31, 0, 0 }
};
void space(int n) { while (n-- > 0) putchar(' '); }
void init_months()
{
int i;
if ((!(year % 4) && (year % 100)) || !(year % 400))
months[1].days = 29;
year--;
months[0].start_wday
= (year * 365 + year/4 - year/100 + year/400 + 1) % 7;
for (i = 1; i < 12; i++)
months[i].start_wday =
(months[i-1].start_wday + months[i-1].days) % 7;
cols = (width + 2) / 22;
while (12 % cols) cols--;
gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0;
if (gap > 4) gap = 4;
lead = (width - (20 + gap) * cols + gap + 1) / 2;
year++;
}
void print_row(int row)
{
int c, i, from = row * cols, to = from + cols;
space(lead);
for (c = from; c < to; c++) {
i = strlen(months[c].name);
space((20 - i)/2);
printf("%s", months[c].name);
space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap));
}
putchar('\n');
space(lead);
for (c = from; c < to; c++) {
for (i = 0; i < 7; i++)
printf("%s%s", wdays[i], i == 6 ? "" : " ");
if (c < to - 1) space(gap);
else putchar('\n');
}
while (1) {
for (c = from; c < to; c++)
if (months[c].at < months[c].days) break;
if (c == to) break;
space(lead);
for (c = from; c < to; c++) {
for (i = 0; i < months[c].start_wday; i++) space(3);
while(i++ < 7 && months[c].at < months[c].days) {
printf("%2d", ++months[c].at);
if (i < 7 || c < to - 1) putchar(' ');
}
while (i++ <= 7 && c < to - 1) space(3);
if (c < to - 1) space(gap - 1);
months[c].start_wday = 0;
}
putchar('\n');
}
putchar('\n');
}
void print_year()
{
int row;
char buf[32];
sprintf(buf, "%d", year);
space((width - strlen(buf)) / 2);
printf("%s\n\n", buf);
for (row = 0; row * cols < 12; row++)
print_row(row);
}
int main(int c, char **v)
{
int i, year_set = 0;
for (i = 1; i < c; i++) {
if (!strcmp(v[i], "-w")) {
if (++i == c || (width = atoi(v[i])) < 20)
goto bail;
} else if (!year_set) {
if (!sscanf(v[i], "%d", &year) || year <= 0)
year = 1969;
year_set = 1;
} else
goto bail;
}
init_months();
print_year();
return 0;
bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]);
exit(1);
} |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #OCaml | OCaml | class point x y =
object
val mutable x = x
val mutable y = y
method print = Printf.printf "(%d, %d)\n" x y
method dance =
x <- x + Random.int 3 - 1;
y <- y + Random.int 3 - 1
end
type evil_point {
blah : int;
blah2 : int;
mutable x : int;
mutable y : int;
}
let evil_reset p =
let ep = Obj.magic p in
ep.x <- 0;
ep.y <- 0
let () =
let p = new point 0 0 in
p#print;
p#dance;
p#print;
p#dance;
p#print;
let (_, _, x, y) : int * int * int * int = Obj.magic p in
Printf.printf "Broken coord: (%d, %d)\n" x y;
evil_reset p
p#print |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Oforth | Oforth | package Foo;
sub new {
my $class = shift;
my $self = { _bar => 'I am ostensibly private' };
return bless $self, $class;
}
sub get_bar {
my $self = shift;
return $self->{_bar};
}
package main;
my $foo = Foo->new();
print "$_\n" for $foo->get_bar(), $foo->{_bar}; |
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.
| #Delphi | Delphi | const
SIZE = 256;
NUM_PARTICLES = 1000;
procedure TForm1.Button1Click(Sender: TObject);
type
TByteArray = array[0..0] of Byte;
PByteArray = ^TByteArray;
var
B: TBitmap;
I: Integer;
P, D: TPoint;
begin
Randomize;
B := TBitmap.Create;
try
B.Width := SIZE;
B.Height := SIZE;
B.PixelFormat := pf8bit;
B.Canvas.Brush.Color := clBlack;
B.Canvas.FillRect(B.Canvas.ClipRect);
B.Canvas.Pixels[Random(SIZE), Random(SIZE)] := clWhite;
For I := 0 to NUM_PARTICLES - 1 do
Begin
P.X := Random(SIZE);
P.Y := Random(SIZE);
While true do
Begin
D.X := Random(3) - 1;
D.Y := Random(3) - 1;
Inc(P.X, D.X);
Inc(P.Y, D.Y);
If ((P.X or P.Y) < 0) or (P.X >= SIZE) or (P.Y >= SIZE) Then
Begin
P.X := Random(SIZE);
P.Y := Random(SIZE);
end
else if PByteArray(B.ScanLine[P.Y])^[P.X] <> 0 then
begin
PByteArray(B.ScanLine[P.Y-D.Y])^[P.X-D.X] := $FF;
Break;
end;
end;
end;
Canvas.Draw(0, 0, B);
finally
FreeAndNil(B);
end;
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
| #Brat | Brat | secret_length = 4
secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length
score = { guess |
cows = 0
bulls = 0
guess.each_with_index { digit, index |
true? digit == secret[index]
{ bulls = bulls + 1 }
{ true? secret.include?(digit)
{ cows = cows + 1 }
}
}
[cows: cows, bulls: bulls]
}
won = false
guesses = 1
p "I have chosen a number with four unique digits from 1 through 9. Can you guess it?"
while { not won }
{
print "Guess #{guesses}: "
guess = g.strip.dice.map { d | d.to_i }
when { guess == secret } { p "You won in #{guesses} guesses!"; won = true }
{ guess.include?(0) || guess.include?(null) } { p "Your guess should only include digits 1 through 9." }
{ guess.length != secret.length } { p "Your guess was not the correct length. The number has exactly #{secret.length} digits." }
{ guess.unique.length != secret.length } { p "Each digit should only appear once in your guess." }
{ true } {
result = score guess
p "Score: #{result[:bulls]} bulls, #{result[:cows]} cows."
guesses = guesses + 1
}
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #REXX | REXX | /*REXX program performs a Burrows─Wheeler transform (BWT) on a character string(s). */
$.= /*the default text for (all) the inputs*/
parse arg $.1 /*obtain optional arguments from the CL*/
if $.1='' then do; $.1= "banana" /*Not specified? Then use the defaults*/
$.2= "BANANA"
$.3= "appellee"
$.4= "dogwood"
$.5= "TO BE OR NOT TO BE OR WANT TO BE OR NOT?"
$.6= "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES"
$.7= "^ABC|"
$.7= "bad─bad thingy"'fd'x /* ◄─── this string can't be processed.*/
end
/* [↑] show blank line between outputs*/
do t=1 while $.t\=''; if t\==1 then say /*process each of the inputs (or input)*/
out= BWT($.t) /*invoke the BWT function, get result*/
ori= iBWT(out) /* " " iBWT " " " */
say ' input ───► ' $.t /*display input string to term.*/
say ' output ───► ' out /* " output " " " */
say 'original ───► ' ori /* " reconstituted " " " */
end /*t*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
BWT: procedure expose ?.; parse arg y,,$ /*obtain the input; nullify $ string. */
?.1= 'fd'x; ?.2= "fc"x /*assign the STX and ETX strings. */
do i=1 for 2 /* [↓] check for invalid input string.*/
_= verify(y, ?.i, 'M'); if _==0 then iterate; er= '***error*** BWT: '
say er "invalid input: " y
say er 'The input string contains an invalid character at position' _"."; exit _
end /*i*/ /* [↑] if error, perform a hard exit.*/
y= ?.1 || y || ?.2; L= length(y) /*get the input & add a fence; gel len.*/
@.1= y; m= L - 1 /*define the first element of the table*/
do j=2 for m; _= j-1 /*now, define the rest of the elements.*/
@.j= right(@._,1)left(@._,m) /*construct a table from the Y input.*/
end /*j*/ /* [↑] each element: left & right part*/
call cSort L /*invoke lexicographical sort for array*/
do k=1 for L /* [↓] construct the answer from array*/
$= $ || right(@.k, 1) /*build the answer from each of ··· */
end /*k*/ /* ··· the array's right─most character*/
return $ /*return the constructed answer. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
iBWT: procedure expose ?.; parse arg y,,@. /*obtain the input; nullify @. string.*/
L= length(y) /*compute the length of the input str. */
do j=1 for L /* [↓] step through each input letters*/
do k=1 for L /* [↓] step through each row of table.*/
@.k= substr(y, k, 1) || @.k /*construct a row of the table of chars*/
end /*k*/ /* [↑] order of table row is inverted.*/
call cSort L /*invoke lexicographical sort for array*/
end /*j*/ /* [↑] answer is the penultimate entry*/
do #=1
if right(@.#, 1)==?.2 then return substr(@.#, 2, L-2) /*return correct result*/
end /*#*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
cSort: procedure expose @.; parse arg n; m=n-1 /*N: is the number of @ array elements.*/
do m=m for m by -1 until ok; ok=1 /*keep sorting the @ array until done.*/
do j=1 for m; k= j+1; if @.j<<[email protected] then iterate /*elements in order?*/
_= @.j; @.j= @.k; @.k= _; ok= 0 /*swap two elements; flag as not done.*/
end /*j*/
end /*m*/; return |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #BaCon | BaCon | CONST lc$ = "abcdefghijklmnopqrstuvwxyz"
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CONST txt$ = "The quick brown fox jumps over the lazy dog."
FUNCTION Ceasar$(t$, k)
lk$ = MID$(lc$ & lc$, k+1, 26)
uk$ = MID$(uc$ & uc$, k+1, 26)
RETURN REPLACE$(t$, lc$ & uc$, lk$ & uk$, 2)
END FUNCTION
tokey = RANDOM(25)+1
PRINT "Encrypting text with key: ", tokey
en$ = Ceasar$(txt$, tokey)
PRINT "Encrypted: ", en$
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey) |
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
| #Go | Go | package main
import (
"fmt"
"math"
)
const epsilon = 1.0e-15
func main() {
fact := uint64(1)
e := 2.0
n := uint64(2)
for {
e0 := e
fact *= n
n++
e += 1.0 / float64(fact)
if math.Abs(e - e0) < epsilon {
break
}
}
fmt.Printf("e = %.15f\n", e)
} |
http://rosettacode.org/wiki/Bulls_and_cows/Player | Bulls and cows/Player | Task
Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list.
Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
Related tasks
Bulls and cows
Guess the number
Guess the number/With Feedback (Player)
| #Lua | Lua | local line = "---------+----------------------------------+-------+-------+"
local digits = {1,2,3,4,5,6,7,8,9}
function and_bits (a, b)
-- print (a, b)
return a & b -- Lua 5.3
end
function or_bits (a, b)
return a | b -- Lua 5.3
end
function get_digits (n)
local tDigits = {}
for i = 1, #digits do tDigits[i] = digits[i] end
local ret = {}
math.randomseed(os.time())
for i = 1, n do
local d = table.remove (tDigits, math.random(#tDigits))
table.insert (ret, d)
end
return ret
end
function mask (x)
return 3*x-1 -- any function
end
function score (guess, goal)
local bits, bulls, cows = 0, 0, 0
for i = 1, #guess do
if (guess[i] == goal[i]) then
bulls = bulls + 1
else
bits = bits + mask (goal[i])
end
end
for i = 1, #guess do
if not (guess[i] == goal[i]) then
local nCow = (and_bits (bits, mask(guess[i])) == 0) and 0 or 1
cows = cows + nCow
end
end
return bulls, cows
end
function iCopy (list)
local nList = {}
for i = 1, #list do nList[i] = list[i] end
return nList
end
function pick (list, n, got, marker, buf)
-- print ('pick', #list, n)
local bits = 1
if got >= n then
table.insert (list, buf)
else
local bits = 1
for i = 1, #digits do
if and_bits(marker,bits) == 0 then
buf[got+1] = i
pick (list, n, got+1, or_bits (marker, bits), iCopy(buf))
end
bits = bits * 2
end
end
end
function filter_list (list, guess, bulls, cows)
local index = 1
for i = 1, #list do
-- print ('filter_list i: ' .. i)
local scoreBulls, scoreCows = score (guess, list[i])
if bulls == scoreBulls and cows == scoreCows then
list[index] = list[i]
index = index + 1
end
end
for i = #list, index+1, -1 do
table.remove (list, i)
end
end
function game (goal)
local n = #goal
local attempt = 1
local guess = {} -- n-length guess numbers array
for i = 1, n do table.insert (guess, 0) end -- empty buffer
local list = {}
pick (list, n, 0, 0, guess)
local bulls, cows = 0, 0
while true do
guess = list[1]
bulls, cows = score (guess, goal)
print (' Guess ' .. attempt .. ' | ' ..table.concat(guess), '('..#list..' variants) ', bulls, cows)
if bulls == n then return end
filter_list (list, guess, bulls, cows)
attempt = attempt + 1
end
end
local n = 4
local secret = get_digits (n)
print (line..'\nSecret '.. #secret.. ' | '..table.concat(secret) .. ' | Bulls | Cows |' .. '\n' .. line)
game (secret) |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #Nim | Nim | import strutils
const progUpper = staticRead("calendar_upper.txt")
proc transformed(s: string): string {.compileTime.} =
## Return a transformed version (which can compile) of a program in uppercase.
let upper = s.toLower() # Convert all to lowercase.
var inString = false # Text in string should be in uppercase…
var inBraces = false # … except if this is in an expression to interpolate.
for ch in upper:
case ch
of '"':
inString = not inString
of '{':
if inString: inBraces = true
of '}':
if inString: inBraces = false
of 'a'..'z':
if inString and not inBraces:
result.add(ch.toUpperAscii()) # Restore content of strings to uppercase.
continue
else:
discard
result.add(ch)
const prog = progUpper.transformed()
static: writeFile("calendar_transformed.nim", prog)
include "calendar_transformed.nim" |
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
| #Ol | Ol |
(import (otus ffi))
(define self (load-dynamic-library #f))
(define strdup (self type-string "strdup" type-string))
(print (strdup "Hello World!"))
|
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Oz | Oz | #include "mozart.h"
#include <string.h>
OZ_BI_define(c_strdup,1,1)
{
OZ_declareVirtualString(0, s1);
char* s2 = strdup(s1);
OZ_Term s3 = OZ_string(s2);
free( s2 );
OZ_RETURN( s3 );
}
OZ_BI_end
OZ_C_proc_interface * oz_init_module(void)
{
static OZ_C_proc_interface table[] = {
{"strdup",1,1,c_strdup},
{0,0,0,0}
};
return table;
} |
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.
| #Dart | Dart | void main() {
// Function definition
// See the "Function definition" task for more info
void noArgs() {}
void fixedArgs(int arg1, int arg2) {}
void optionalArgs([int arg1 = 1]) {}
void namedArgs({required int arg1}) {}
int returnsValue() {return 1;}
// Calling a function that requires no arguments
noArgs();
// Calling a function with a fixed number of arguments
fixedArgs(1, 2);
// Calling a function with optional arguments
optionalArgs();
optionalArgs(2);
// Calling a function with named arguments
namedArgs(arg1: 1);
// Using a function in statement context
if (true) {
noArgs();
}
// Obtaining the return value of a function
var value = returnsValue();
} |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Sidef | Sidef | func cantor (height) {
var width = 3**(height - 1)
var lines = height.of { "\N{FULL BLOCK}" * width }
func trim_middle_third (len, start, index) {
var seg = (len // 3) || return()
for i, j in ((index ..^ height) ~X (0 ..^ seg)) {
lines[i].replace!(Regex("^.{#{start + seg + j}}\\K."), ' ')
}
[0, 2*seg].each { |k|
trim_middle_third(seg, start + k, index + 1)
}
}
trim_middle_third(width, 0, 1)
return lines
}
cantor(5).each { .say } |
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
| #Quackery | Quackery | /O> 0 ' [ 1 2 3 4 5 ] witheach +
... 1 ' [ 1 2 3 4 5 ] witheach *
...
Stack: 15 120 |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #R | R |
Reduce('+', c(2,30,400,5000))
5432
|
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}
| #Scheme | Scheme |
(define cartesian-product (lambda (xs ys)
(if (or (zero? (length xs)) (zero? (length ys)))
'()
(fold append (map (lambda (x) (map (lambda (y) (list x y)) ys)) xs)))))
(define nary-cartesian-product (lambda (ls)
(if (fold (lambda (a b) (or a b)) (map (compose zero? length) ls))
'()
(map flatten (fold cartesian-product ls)))))
> (cartesian-product '(1 2) '(3 4))
((1 3) (1 4) (2 3) (2 4))
> (cartesian-product '(3 4) '(1 2))
((3 1) (3 2) (4 1) (4 2))
> (cartesian-product '(1 2) '())
()
> (cartesian-product '() '(1 2))
()
> (nary-cartesian-product '((1 2)(a b)(x y)))
((1 a x) (1 a y) (1 b x) (1 b y) (2 a x) (2 a y) (2 b x) (2 b y))
|
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
| #Groovy | Groovy |
class Catalan
{
public static void main(String[] args)
{
BigInteger N = 15;
BigInteger k,n,num,den;
BigInteger catalan;
print(1);
for(n=2;n<=N;n++)
{
num = 1;
den = 1;
for(k=2;k<=n;k++)
{
num = num*(n+k);
den = den*k;
catalan = num/den;
}
println(catalan);
}
}
}
|
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
| #Groovy | Groovy | class BraceExpansion {
static void main(String[] args) {
for (String s : [
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
]) {
println()
expand(s)
}
}
static void expand(String s) {
expandR("", s, "")
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ")
StringBuilder sb = null
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1
sb = new StringBuilder(s)
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2)
depth = (c == ('{' as char)) ? ++depth : depth
depth = (c == ('}' as char)) ? --depth : depth
if (c == (',' as char) && depth == 1) {
sb.setCharAt(i2, '\u0000' as char)
} else if (c == ('}' as char) && depth == 0 && sb.indexOf("\u0000") != -1) {
break outer
}
}
}
if (i1 == -1) {
if (suf.length() > 0) {
expandR(pre + s, suf, "")
} else {
printf("%s%s%s%n", pre, s, suf)
}
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) {
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf)
}
}
}
} |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #C.2B.2B | C++ | #include <iostream>
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0)return true;
for (int b = 2; b < n - 1; b++) {
if (sameDigits(n, b)) {
return true;
}
}
return false;
}
bool isPrime(int n) {
if (n < 2)return false;
if (n % 2 == 0)return n == 2;
if (n % 3 == 0)return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0)return false;
d += 2;
if (n % d == 0)return false;
d += 4;
}
return true;
}
int main() {
for (auto kind : { "", "odd ", "prime " }) {
bool quiet = false;
int BigLim = 99999;
int limit = 20;
std::cout << "First " << limit << ' ' << kind << "Brazillian numbers:\n";
int c = 0;
int n = 7;
while (c < BigLim) {
if (isBrazilian(n)) {
if (!quiet)std::cout << n << ' ';
if (++c == limit) {
std::cout << "\n\n";
quiet = true;
}
}
if (quiet && kind != "") continue;
if (kind == "") {
n++;
}
else if (kind == "odd ") {
n += 2;
}
else if (kind == "prime ") {
while (true) {
n += 2;
if (isPrime(n)) break;
}
} else {
throw new std::runtime_error("Unexpected");
}
}
if (kind == "") {
std::cout << "The " << BigLim + 1 << "th Brazillian number is: " << n << "\n\n";
}
}
return 0;
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CalendarStuff
{
class Program
{
static void Main(string[] args)
{
Console.WindowHeight = 46;
Console.Write(buildMonths(new DateTime(1969, 1, 1)));
Console.Read();
}
private static string buildMonths(DateTime date)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(center("[Snoop]", 24 * 3));
sb.AppendLine();
sb.AppendLine(center(date.Year.ToString(), 24 * 3));
List<DateTime> dts = new List<DateTime>();
while (true)
{
dts.Add(date);
if (date.Year != ((date = date.AddMonths(1)).Year))
{
break;
}
}
var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray();
int sCur=0;
while (sCur<dts.Count)
{
sb.AppendLine();
int curMonth=0;
var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); //grab the next 3
sCur += j.Length;
bool breakOut = false;
while (!breakOut)
{
int inj = 1;
foreach (var cd in j)
{
if (cd.MoveNext())
{
sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " ");
}
else
{
sb.Append("".PadRight(21, ' ') + " ");
breakOut = true;
}
if (inj++ % 3 == 0) sb.AppendLine();
}
}
}
return sb.ToString();
}
private static IEnumerable<string> buildMonth(DateTime date)
{
yield return center(date.ToString("MMMM"),7*3);
var j = DateTime.DaysInMonth(date.Year, date.Month);
yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " "));
string cur = "";
int total = 0;
foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek))
{
cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" ";
if (total++ > 0 && (total ) % 7 == 0)
{
yield return cur;
cur = "";
}
}
yield return cur;
}
private static string center(string s, int len)
{
return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' '));
}
}
}
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Perl | Perl | package Foo;
sub new {
my $class = shift;
my $self = { _bar => 'I am ostensibly private' };
return bless $self, $class;
}
sub get_bar {
my $self = shift;
return $self->{_bar};
}
package main;
my $foo = Foo->new();
print "$_\n" for $foo->get_bar(), $foo->{_bar}; |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Phix | Phix | without js -- (no class under p2js)
class test
private string msg = "this is a test"
procedure show() ?this.msg end procedure
end class
test t = new()
t.show()
--?t.msg -- illegal
--t.msg = "this is broken" -- illegal
include builtins\structs.e as structs
constant ctx = routine_id("test") -- magic/context
--constant ctx = "test" -- also works
--constant ctx = test -- also works
?structs:fetch_field(t,"msg",ctx)&" (with some magic)"
structs:store_field(t,"msg","this breaks privacy",ctx)
t.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.