task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Elena | Elena |
var c0 := { console.writeLine("No argument provided") };
var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") };
|
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
| #Scala | Scala | object Main extends App {
val a = Seq(1, 2, 3, 4, 5)
println(s"Array : ${a.mkString(", ")}")
println(s"Sum : ${a.sum}")
println(s"Difference : ${a.reduce { (x, y) => x - y }}")
println(s"Product : ${a.product}")
println(s"Minimum : ${a.min}")
println(s"Maximum : ${a.max}")
} |
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}
| #Swift | Swift | func + <T>(el: T, arr: [T]) -> [T] {
var ret = arr
ret.insert(el, at: 0)
return ret
}
func cartesianProduct<T>(_ arrays: [T]...) -> [[T]] {
guard let head = arrays.first else {
return []
}
let first = Array(head)
func pel(
_ el: T,
_ ll: [[T]],
_ a: [[T]] = []
) -> [[T]] {
switch ll.count {
case 0:
return a.reversed()
case _:
let tail = Array(ll.dropFirst())
let head = ll.first!
return pel(el, tail, el + head + a)
}
}
return arrays.reversed()
.reduce([first], {res, el in el.flatMap({ pel($0, res) }) })
.map({ $0.dropLast(first.count) })
}
print(cartesianProduct([1, 2], [3, 4]))
print(cartesianProduct([3, 4], [1, 2]))
print(cartesianProduct([1, 2], []))
print(cartesianProduct([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))
print(cartesianProduct([1, 2, 3], [30], [500, 100]))
print(cartesianProduct([1, 2, 3], [], [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
| #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CatlanNumbers {
public static void main(String[] args) {
Catlan f1 = new Catlan1();
Catlan f2 = new Catlan2();
Catlan f3 = new Catlan3();
System.out.printf(" Formula 1 Formula 2 Formula 3%n");
for ( int n = 0 ; n <= 15 ; n++ ) {
System.out.printf("C(%2d) = %,12d %,12d %,12d%n", n, f1.catlin(n), f2.catlin(n), f3.catlin(n));
}
}
private static interface Catlan {
public BigInteger catlin(long n);
}
private static class Catlan1 implements Catlan {
// C(n) = (2n)! / (n+1)!n!
@Override
public BigInteger catlin(long n) {
List<Long> numerator = new ArrayList<>();
for ( long k = n+2 ; k <= 2*n ; k++ ) {
numerator.add(k);
}
List<Long> denominator = new ArrayList<>();
for ( long k = 2 ; k <= n ; k++ ) {
denominator.add(k);
}
for ( int i = numerator.size()-1 ; i >= 0 ; i-- ) {
for ( int j = denominator.size()-1 ; j >= 0 ; j-- ) {
if ( denominator.get(j) == 1 ) {
continue;
}
if ( numerator.get(i) % denominator.get(j) == 0 ) {
long val = numerator.get(i) / denominator.get(j);
numerator.set(i, val);
denominator.remove(denominator.get(j));
if ( val == 1 ) {
break;
}
}
}
}
BigInteger catlin = BigInteger.ONE;
for ( int i = 0 ; i < numerator.size() ; i++ ) {
catlin = catlin.multiply(BigInteger.valueOf(numerator.get(i)));
}
for ( int i = 0 ; i < denominator.size() ; i++ ) {
catlin = catlin.divide(BigInteger.valueOf(denominator.get(i)));
}
return catlin;
}
}
private static class Catlan2 implements Catlan {
private static Map<Long,BigInteger> CACHE = new HashMap<>();
static {
CACHE.put(0L, BigInteger.ONE);
}
// C(0) = 1, C(n+1) = sum(i=0..n,C(i)*C(n-i))
@Override
public BigInteger catlin(long n) {
if ( CACHE.containsKey(n) ) {
return CACHE.get(n);
}
BigInteger catlin = BigInteger.ZERO;
n--;
for ( int i = 0 ; i <= n ; i++ ) {
//System.out.println("n = " + n + ", i = " + i + ", n-i = " + (n-i));
catlin = catlin.add(catlin(i).multiply(catlin(n-i)));
}
CACHE.put(n+1, catlin);
return catlin;
}
}
private static class Catlan3 implements Catlan {
private static Map<Long,BigInteger> CACHE = new HashMap<>();
static {
CACHE.put(0L, BigInteger.ONE);
}
// C(0) = 1, C(n+1) = 2*(2n-1)*C(n-1)/(n+1)
@Override
public BigInteger catlin(long n) {
if ( CACHE.containsKey(n) ) {
return CACHE.get(n);
}
BigInteger catlin = BigInteger.valueOf(2).multiply(BigInteger.valueOf(2*n-1)).multiply(catlin(n-1)).divide(BigInteger.valueOf(n+1));
CACHE.put(n, catlin);
return catlin;
}
}
}
|
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
| #Julia | Julia | function getitem(s, depth=0)
out = [""]
while s != ""
c = s[1]
if depth > 0 && (c == ',' || c == '}')
return out, s
elseif c == '{'
x = getgroup(s[2:end], depth+1)
if x != ""
out, s = [a * b for a in out, b in x[1]], x[2]
continue
end
elseif c == '\\' && length(s) > 1
s, c = s[2:end], c * s[2]
end
out, s = [a * c for a in out], s[2:end]
end
return out, s
end
function getgroup(s, depth)
out, comma = "", false
while s != ""
g, s = getitem(s, depth)
if s == ""
break
end
out = vcat([out...], [g...])
if s[1] == '}'
if comma
return out, s[2:end]
end
return ["{" * a * "}" for a in out], s[2:end]
end
if s[1] == ','
comma, s = true, s[2:end]
end
end
return ""
end
const teststrings = [raw"~/{Downloads,Pictures}/*.{jpg,gif,png}",
raw"It{{em,alic}iz,erat}e{d,}, please.",
raw"{,{,gotta have{ ,\, again\, }}more }cowbell!",
raw"{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}'''"]
for s in teststrings
println("\n", s, "\n--------------------------------------------")
for ans in getitem(s)[1]
println(ans)
end
end |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Kotlin | Kotlin | // version 1.1.2
object BraceExpansion {
fun expand(s: String) = expandR("", s, "")
private val r = Regex("""([\\]{2}|[\\][,}{])""")
private fun expandR(pre: String, s: String, suf: String) {
val noEscape = s.replace(r, " ")
var sb = StringBuilder("")
var i1 = noEscape.indexOf('{')
var i2 = 0
outer@ while (i1 != -1) {
sb = StringBuilder(s)
var depth = 1
i2 = i1 + 1
while (i2 < s.length && depth > 0) {
val c = noEscape[i2]
if (c == '{') depth++
else if (c == '}') depth--
if (c == ',' && depth == 1) sb[i2] = '\u0000'
else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break@outer
i2++
}
i1 = noEscape.indexOf('{', i1 + 1)
}
if (i1 == -1) {
if (suf.isNotEmpty()) expandR(pre + s, suf, "")
else println("$pre$s$suf")
} else {
for (m in sb.substring(i1 + 1, i2).split('\u0000')) {
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf)
}
}
}
}
fun main(args: Array<String>) {
val strings = arrayOf(
"""~/{Downloads,Pictures}/*.{jpg,gif,png}""",
"""It{{em,alic}iz,erat}e{d,}, please.""",
"""{,{,gotta have{ ,\, again\, }}more }cowbell!""",
"""{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"""
)
for (s in strings) {
println()
BraceExpansion.expand(s)
}
} |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | : prime? ( n -- flag )
dup 2 < if drop false exit then
dup 2 mod 0= if 2 = exit then
dup 3 mod 0= if 3 = exit then
5
begin
2dup dup * >=
while
2dup mod 0= if 2drop false exit then
2 +
2dup mod 0= if 2drop false exit then
4 +
repeat
2drop true ;
: same_digits? ( n b -- ? )
2dup mod >r
begin
tuck / swap
over 0 >
while
2dup mod r@ <> if
2drop rdrop false exit
then
repeat
2drop rdrop true ;
: brazilian? ( n -- ? )
dup 7 < if drop false exit then
dup 1 and 0= if drop true exit then
dup 1- 2 do
dup i same_digits? if
unloop drop true exit
then
loop
drop false ;
: next_prime ( n -- n )
begin 2 + dup prime? until ;
: print_brazilian ( n1 n2 -- )
>r 7
begin
r@ 0 >
while
dup brazilian? if
dup .
r> 1- >r
then
over 0= if
next_prime
else
over +
then
repeat
2drop rdrop cr ;
." First 20 Brazilian numbers:" cr
1 20 print_brazilian
cr
." First 20 odd Brazilian numbers:" cr
2 20 print_brazilian
cr
." First 20 prime Brazilian numbers:" cr
0 20 print_brazilian
bye |
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
| #D | D | import std.stdio, std.datetime, std.string, std.conv;
void printCalendar(in uint year, in uint nCols)
in {
assert(nCols > 0 && nCols <= 12);
} body {
immutable rows = 12 / nCols + (12 % nCols != 0);
auto date = Date(year, 1, 1);
int offs = date.dayOfWeek;
const months = "January February March April May June
July August September October November December".split;
string[8][12] mons;
foreach (immutable m; 0 .. 12) {
mons[m][0] = months[m].center(21);
mons[m][1] = " Su Mo Tu We Th Fr Sa";
immutable dim = date.daysInMonth;
foreach (immutable d; 1 .. 43) {
immutable day = d > offs && d <= offs + dim;
immutable str = day ? format(" %2s", d-offs) : " ";
mons[m][2 + (d - 1) / 7] ~= str;
}
offs = (offs + dim) % 7;
date.add!"months"(1);
}
"[Snoopy Picture]".center(nCols * 24 + 4).writeln;
writeln(year.text.center(nCols * 24 + 4), "\n");
foreach (immutable r; 0 .. rows) {
string[8] s;
foreach (immutable c; 0 .. nCols) {
if (r * nCols + c > 11)
break;
foreach (immutable i, line; mons[r * nCols + c])
s[i] ~= format(" %s", line);
}
writefln("%-(%s\n%)\n", s);
}
}
void main() {
printCalendar(1969, 3);
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Gnuplot | Gnuplot |
## plotff.gp 11/27/16 aev
## Plotting from any data-file with 2 columns (space delimited), and writing to png-file.
## Especially useful to plot colored fractals using points.
## Note: assign variables: clr, filename and ttl (before using load command).
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border; unset xtics; unset ytics; unset key;
set size square
dfn=filename.".dat"
set title ttl font "Arial:Bold,12"
plot dfn using 1:2 with points pt 7 ps 0.5 lc @clr
set output
|
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
| #CLU | CLU | % This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
% pclu -merge $CLUHOME/lib/misc.lib -compile bulls_cows.clu
% Seed the random number generator with the current time
init_rng = proc ()
d: date := now()
seed: int := ((d.hour*60) + d.minute)*60 + d.second
random$seed(seed)
end init_rng
% Generate a secret
make_secret = proc () returns (sequence[int])
secret: array[int] := array[int]$[0,0,0,0]
for i: int in int$from_to(1,4) do
digit: int
valid: bool := false
while ~valid do
digit := 1+random$next(9)
valid := true
for j: int in int$from_to(1, i-1) do
if secret[i] = digit then
valid := false
break
end
end
end
secret[i] := digit
end
return(sequence[int]$a2s(secret))
end make_secret
% Count the bulls
bulls = proc (secret, input: sequence[int]) returns (int)
n_bulls: int := 0
for i: int in int$from_to(1,4) do
if secret[i] = input[i] then n_bulls := n_bulls + 1 end
end
return(n_bulls)
end bulls
% Count the cows
cows = proc (secret, input: sequence[int]) returns (int)
n_cows: int := 0
for i: int in int$from_to(1,4) do
for j: int in int$from_to(1,4) do
if i ~= j cand secret[i] = input[j] then
n_cows := n_cows + 1
end
end
end
return(n_cows)
end cows
% Read a guess
player_guess = proc () returns (sequence[int])
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
while true do % we will keep reading until the guess is valid
stream$puts(po, "Guess? ")
guess: string := stream$getl(pi)
% check length
if string$size(guess) ~= 4 then
stream$putl(po, "Invalid guess: need four digits.")
continue
end
% get and check digits
valid: bool := true
digits: sequence[int] := sequence[int]$[]
for c: char in string$chars(guess) do
i: int := char$c2i(c) - 48
if ~(i>=1 & i<=9) then
valid := false
break
end
digits := sequence[int]$addh(digits,i)
end
if ~valid then
stream$putl(po, "Invalid guess: each position needs to be a digit 1-9.")
continue
end
% check that there are no duplicates
valid := true
for i: int in int$from_to(1,4) do
for j: int in int$from_to(i+1,4) do
if digits[i] = digits[j] then
valid := false
break
end
end
end
if ~valid then
stream$putl(po, "Invalid guess: there must be no duplicate digits.")
continue
end
return(digits)
end
end player_guess
% Play a game
play_game = proc (secret: sequence[int])
po: stream := stream$primary_output()
n_guesses: int := 0
while true do
n_guesses := n_guesses + 1
guess: sequence[int] := player_guess()
n_bulls: int := bulls(secret, guess)
n_cows: int := cows(secret, guess)
stream$putl(po, "Bulls: " || int$unparse(n_bulls)
|| ", cows: " || int$unparse(n_cows))
if n_bulls = 4 then
stream$putl(po, "Congratulations! You won in "
|| int$unparse(n_guesses) || " tries.")
break
end
end
end play_game
start_up = proc ()
po: stream := stream$primary_output()
init_rng()
stream$putl(po, "Bulls and cows\n----- --- ----\n")
play_game(make_secret())
end start_up |
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
| #zkl | zkl | class BurrowsWheelerTransform{
fcn init(chr="$"){ var special=chr; }
fcn encode(str){
_assert_(not str.holds(special), "String cannot contain char \"%s\"".fmt(special) );
str=str.append(special);
str.len().pump(List().merge,'wrap(n){ String(str[n,*],str[0,n]) })
.pump(String,T("get",-1)); // last char of each "permutation"
}
fcn decode(str){
table:=List.createLong(str.len(),""); // ("",""..), mutable
do(str.len()){
foreach n in (str.len()){ table[n]=str[n] + table[n] }
table.sort();
} // --> ("$dogwood","d$dogwoo","dogwood$",...)
table.filter1("%s*".fmt(special).glob)[1,*]; // str[0]==$, often first element
}
} |
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
| #BQN | BQN | o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0 |
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
| #K | K |
/ Computing value of e
/ ecomp.k
\p 17
fact: {*/1+!:x}
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue[]
|
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
| #Klingphix | Klingphix | %e0 %e %n %fact %v
0 !e0 2 !e 0 !n 1 !fact
1e-15 !v
:printOp swap print print nl ;
:test $e $e0 - abs $v >= ;
[$e !e0
$n 1 + !n
2 $n * 2 $n * 1 + * $fact * !fact
2 $n * 2 + $fact / $e + !e]
[test]
while
%rE
2.718281828459045 !rE
"Computed e = " $e tostr printOp
"Real e = " $rE tostr printOp
"Error = " $rE $e sub printOp
"Number of iterations = " $n printOp
" " input |
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)
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de bullsAndCows ()
(let Choices (shuffle (mapcan permute (subsets 4 (range 1 9))))
(use (Guess Bulls Cows)
(loop
(prinl "Guessing " (setq Guess (pop 'Choices)))
(prin "How many bulls and cows? ")
(setq Bulls (read) Cows (read))
(setq Choices
(filter
'((C)
(let B (cnt = Guess C)
(and
(= Bulls B)
(= Cows (- (length (sect Guess C)) B)) ) ) )
Choices ) )
(NIL Choices "No matching solution")
(NIL (cdr Choices) (pack "The answer is " (car Choices))) ) ) ) ) |
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.
| #Racket | Racket |
#CI(MODULE NAME-OF-THIS-FILE RACKET
(REQUIRE RACKET/DATE)
(DEFINE (CALENDAR YR)
(DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N)))))
(DEFINE MONTHS
(FOR/LIST ([MN (IN-NATURALS 1)]
[MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY
AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER)])
(DEFINE S (FIND-SECONDS 0 0 12 1 MN YR))
(DEFINE PFX (DATE-WEEK-DAY (SECONDS->DATE S)))
(DEFINE DAYS
(LET ([? (IF (= MN 12) (Λ(X Y) Y) (Λ(X Y) X))])
(ROUND (/ (- (FIND-SECONDS 0 0 12 1 (? (+ 1 MN) 1) (? YR (+ 1 YR))) S)
60 60 24))))
(LIST* (~A MNAME #:WIDTH 20 #:ALIGN 'CENTER) "SU MO TU WE TH FR SA"
(MAP STRING-JOIN
(NSPLIT 7 `(,@(MAKE-LIST PFX " ")
,@(FOR/LIST ([D DAYS])
(~A (+ D 1) #:WIDTH 2 #:ALIGN 'RIGHT))
,@(MAKE-LIST (- 42 PFX DAYS) " ")))))))
(LET* ([S '(" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\ 40~A! 9( 3( 80 39-4! 10\\._\\"
", ,-4'! 5#2X3@7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\! "
"2/_23\\! /_25\\!/_27\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!")]
[S (REGEXP-REPLACE* "!" (STRING-APPEND* S) "~%")]
[S (REGEXP-REPLACE* "@" S (STRING-FOLDCASE "X"))]
[S (REGEXP-REPLACE* ".(?:[1-7][0-9]*|[1-9])" S
(Λ(M) (MAKE-STRING (STRING->NUMBER (SUBSTRING M 1))
(STRING-REF M 0))))])
(PRINTF S YR))
(FOR-EACH (COMPOSE1 DISPLAYLN STRING-TITLECASE)
(DROPF-RIGHT (FOR*/LIST ([3MS (NSPLIT 3 MONTHS)] [S (APPLY MAP LIST 3MS)])
(REGEXP-REPLACE " +$" (STRING-JOIN S " ") ""))
(Λ(S) (EQUAL? "" S)))))
(CALENDAR 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
| #Raku | Raku | use NativeCall;
sub strdup(Str $s --> Pointer) is native {*}
sub puts(Pointer $p --> int32) is native {*}
sub free(Pointer $p --> int32) is native {*}
my $p = strdup("Success!");
say 'puts returns ', puts($p);
say 'free returns ', free($p); |
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
| #REALbasic | REALbasic |
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _
overlapped As Ptr) As Boolean
Declare Function GetLastError Lib "Kernel32" () As Integer
Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean
Const FILE_SHARE_READ = &h00000001
Const FILE_SHARE_WRITE = &h00000002
Const OPEN_EXISTING = 3
Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
If fHandle > 0 Then
Dim mb As MemoryBlock = "Hello, World!"
Dim bytesWritten As Integer
If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then
MsgBox("Error Number: " + Str(GetLastError))
End If
Call CloseHandle(fHandle)
Else
MsgBox("Error Number: " + Str(GetLastError))
End If
|
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.
| #Elixir | Elixir |
# Anonymous function
foo = fn() ->
IO.puts("foo")
end
foo() #=> undefined function foo/0
foo.() #=> "foo"
# Using `def`
defmodule Foo do
def foo do
IO.puts("foo")
end
end
Foo.foo #=> "foo"
Foo.foo() #=> "foo"
# Calling a function with a fixed number of arguments
defmodule Foo do
def foo(x) do
IO.puts(x)
end
end
Foo.foo("foo") #=> "foo"
# Calling a function with a default argument
defmodule Foo do
def foo(x \\ "foo") do
IO.puts(x)
end
end
Foo.foo() #=> "foo"
Foo.foo("bar") #=> "bar"
# There is no such thing as a function with a variable number of arguments. So in Elixir, you'd call the function with a list
defmodule Foo do
def foo(args) when is_list(args) do
Enum.each(args, &(IO.puts(&1)))
end
end
# Calling a function with named arguments
defmodule Foo do
def foo([x: x]) do
IO.inspect(x)
end
end
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Scheme | Scheme | (define (reduce fn init lst)
(do ((val init (fn (car rem) val)) ; accumulated value passed as second argument
(rem lst (cdr rem)))
((null? rem) val)))
(display (reduce + 0 '(1 2 3 4 5))) (newline) ; => 15
(display (reduce expt 2 '(3 4))) (newline) ; => 262144 |
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}
| #Tailspin | Tailspin |
'{1,2}x{3,4} = $:[by [1,2]..., by [3,4]...];
' -> !OUT::write
'{3,4}x{1,2} = $:[by [3,4]..., by [1,2]...];
' -> !OUT::write
'{1,2}x{} = $:[by [1,2]..., by []...];
' -> !OUT::write
'{}x{1,2} = $:[by []..., by [1,2]...];
' -> !OUT::write
'{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} = $:[by [1776, 1789]..., by [7, 12]..., by [4, 14, 23]..., by [0, 1]...];
' -> !OUT::write
'{1, 2, 3} × {30} × {500, 100} = $:[by [1, 2, 3] ..., by [30]..., by [500, 100]...];
' -> !OUT::write
'{1, 2, 3} × {} × {500, 100} = $:[by [1, 2, 3]..., by []..., by [500, 100]...];
' -> !OUT::write
// You can also generate structures with named fields
'year {1776, 1789} × month {7, 12} × day {4, 14, 23} = $:{by [1776, 1789]... -> (year:$), by [7, 12]... -> (month:$), by [4, 14, 23]... -> (day:$)};
' -> !OUT::write
|
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
| #JavaScript | JavaScript | <html><head><title>Catalan</title></head>
<body><pre id='x'></pre><script type="application/javascript">
function disp(x) {
var e = document.createTextNode(x + '\n');
document.getElementById('x').appendChild(e);
}
var fc = [], c2 = [], c3 = [];
function fact(n) { return fc[n] ? fc[n] : fc[n] = (n ? n * fact(n - 1) : 1); }
function cata1(n) { return Math.floor(fact(2 * n) / fact(n + 1) / fact(n) + .5); }
function cata2(n) {
if (n == 0) return 1;
if (!c2[n]) {
var s = 0;
for (var i = 0; i < n; i++) s += cata2(i) * cata2(n - i - 1);
c2[n] = s;
}
return c2[n];
}
function cata3(n) {
if (n == 0) return 1;
return c3[n] ? c3[n] : c3[n] = (4 * n - 2) * cata3(n - 1) / (n + 1);
}
disp(" meth1 meth2 meth3");
for (var i = 0; i <= 15; i++)
disp(i + '\t' + cata1(i) + '\t' + cata2(i) + '\t' + cata3(i));
</script></body></html> |
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
| #Lua | Lua | local function wrapEachItem(items, prefix, suffix)
local itemsWrapped = {}
for i, item in ipairs(items) do
itemsWrapped[i] = prefix .. item .. suffix
end
return itemsWrapped
end
local function getAllItemCombinationsConcatenated(aItems, bItems)
local combinations = {}
for _, a in ipairs(aItems) do
for _, b in ipairs(bItems) do
table.insert(combinations, a..b)
end
end
return combinations
end
local getItems -- Forward declaration.
local function getGroup(s, pos, depth)
local groupItems = {}
local foundComma = false
while pos <= #s do
local items
items, pos = getItems(s, pos, depth)
if pos > #s then break end
for _, item in ipairs(items) do
table.insert(groupItems, item)
end
local c = s:sub(pos, pos)
if c == "}" then -- Possibly end of group.
if foundComma then return groupItems, pos+1 end
return wrapEachItem(groupItems, "{", "}"), pos+1 -- No group.
elseif c == "," then
foundComma, pos = true, pos+1
end
end
return nil -- No group.
end
function getItems(s, pos, depth)
local items = {""}
while pos <= #s do
local c = s:sub(pos, pos)
if depth > 0 and (c == "," or c == "}") then -- End of item in surrounding group.
return items, pos
end
local groupItems, nextPos = nil
if c == "{" then -- Possibly start of a group.
groupItems, nextPos = getGroup(s, pos+1, depth+1)
end
if groupItems then
items, pos = getAllItemCombinationsConcatenated(items, groupItems), nextPos
else
if c == "\\" and pos < #s then -- Escaped character.
pos = pos + 1
c = c .. s:sub(pos, pos)
end
items, pos = wrapEachItem(items, "", c), pos+1
end
end
return items, pos
end
local tests = [[
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
]]
for test in tests:gmatch"[^\n]+" do
print(test)
for _, item in ipairs(getItems(test, 1, 0)) do
print("\t"..item)
end
print()
end |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #Forth | Forth | : prime? ( n -- flag )
dup 2 < if drop false exit then
dup 2 mod 0= if 2 = exit then
dup 3 mod 0= if 3 = exit then
5
begin
2dup dup * >=
while
2dup mod 0= if 2drop false exit then
2 +
2dup mod 0= if 2drop false exit then
4 +
repeat
2drop true ;
: same_digits? ( n b -- ? )
2dup mod >r
begin
tuck / swap
over 0 >
while
2dup mod r@ <> if
2drop rdrop false exit
then
repeat
2drop rdrop true ;
: brazilian? ( n -- ? )
dup 7 < if drop false exit then
dup 1 and 0= if drop true exit then
dup 1- 2 do
dup i same_digits? if
unloop drop true exit
then
loop
drop false ;
: next_prime ( n -- n )
begin 2 + dup prime? until ;
: print_brazilian ( n1 n2 -- )
>r 7
begin
r@ 0 >
while
dup brazilian? if
dup .
r> 1- >r
then
over 0= if
next_prime
else
over +
then
repeat
2drop rdrop cr ;
." First 20 Brazilian numbers:" cr
1 20 print_brazilian
cr
." First 20 odd Brazilian numbers:" cr
2 20 print_brazilian
cr
." First 20 prime Brazilian numbers:" cr
0 20 print_brazilian
bye |
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
| #Delphi | Delphi |
program Calendar;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.DateUtils;
function Center(s: string; width: Integer): string;
var
side: Integer;
begin
if s.Length >= width then
exit(s);
side := (width - s.Length) div 2;
Result := s + string.Create(' ', side);
Result := string.Create(' ', width - Result.Length) + Result;
end;
procedure PrintCalendar(year, nCols: word; local: string = 'en-US');
var
fmt: TFormatSettings;
begin
if (nCols <= 0) or (nCols > 12) then
exit;
fmt := TFormatSettings.Create(local);
var rows := 12 div nCols + ord(12 mod nCols <> 0);
var date := EncodeDate(year, 1, 1);
var offs := DayOfTheWeek(date);
var months: TArray<string>;
setlength(months, 12);
for var i := 1 to 12 do
months[i - 1] := fmt.LongMonthNames[i];
var sWeek := '';
for var i := 1 to 7 do
sWeek := sWeek + ' ' + copy(fmt.ShortDayNames[i], 1, 2);
var mons: TArray<TArray<string>>;
SetLength(mons, 12, 8);
for var m := 0 to 11 do
begin
mons[m, 0] := Center(months[m], 21);
mons[m, 1] := sWeek;
var dim := DaysInMonth(date);
for var d := 1 to 43 do
begin
var day := (d > offs) and (d <= offs + dim);
var str := ' ';
if day then
str := format(' %2d', [d - offs]);
mons[m, 2 + (d - 1) div 7] := mons[m, 2 + (d - 1) div 7] + str;
end;
offs := (offs + dim) mod 7;
date := IncMonth(date, 1);
end;
writeln(Center('[Snoopy Picture]', nCols * 24 + 4));
Writeln(Center(year.ToString, nCols * 24 + 4));
writeln;
for var r := 0 to rows - 1 do
begin
var s: TArray<string>;
SetLength(s, 8);
for var c := 0 to nCols - 1 do
begin
if r * nCols + c > 11 then
Break;
for var i := 0 to High(mons[r * nCols + c]) do
begin
var line := mons[r * nCols + c, i];
s[i] := s[i] + ' ' + line;
end;
end;
for var ss in s do
begin
writeln(ss, ' ');
end;
writeln;
end;
end;
begin
printCalendar(1969, 4);
readln;
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.
| #Go | Go | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math/rand"
"os"
)
const w = 400 // image width
const h = 300 // image height
const n = 15000 // number of particles to add
const frost = 255 // white
var g *image.Gray
func main() {
g = image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
// off center seed position makes pleasingly asymetrical tree
g.SetGray(w/3, h/3, color.Gray{frost})
generate:
for a := 0; a < n; {
// generate random position for new particle
rp := image.Point{rand.Intn(w), rand.Intn(h)}
if g.At(rp.X, rp.Y).(color.Gray).Y == frost {
// position is already set. find a nearby free position.
for {
rp.X += rand.Intn(3) - 1
rp.Y += rand.Intn(3) - 1
// execpt if we run out of bounds, consider the particle lost.
if !rp.In(g.Rect) {
continue generate
}
if g.At(rp.X, rp.Y).(color.Gray).Y != frost {
break
}
}
} else {
// else particle is in free space. let it wander
// until it touches tree
for !hasNeighbor(rp) {
rp.X += rand.Intn(3) - 1
rp.Y += rand.Intn(3) - 1
// but again, if it wanders out of bounds consider it lost.
if !rp.In(g.Rect) {
continue generate
}
}
}
// x, y now specify a free position toucing the tree.
g.SetGray(rp.X, rp.Y, color.Gray{frost})
a++
// progress indicator
if a%100 == 0 {
fmt.Println(a, "of", n)
}
}
f, err := os.Create("tree.png")
if err != nil {
fmt.Println(err)
return
}
err = png.Encode(f, g)
if err != nil {
fmt.Println(err)
}
f.Close()
}
var n8 = []image.Point{
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}}
func hasNeighbor(p image.Point) bool {
for _, n := range n8 {
o := p.Add(n)
if o.In(g.Rect) && g.At(o.X, o.Y).(color.Gray).Y == frost {
return true
}
}
return false
} |
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
| #Coco | Coco | say = print
prompt = (str) ->
putstr str
readline! ? quit! |
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
| #Brainf.2A.2A.2A | Brainf*** | Author: Ettore Forigo | Hexwell
+ start the key input loop
[
memory: | c | 0 | cc | key |
^
, take one character of the key
:c : condition for further ifs
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
(testing for the condition deletes it so duplication is needed)
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
[ if :cc
|
> | :key : already converted digits
|
[>++++++++++<-] | multiply by 10
> | |
[<+>-] | |
< | |
|
< | :cc
[-] | clear (making the loop an if)
] |
<< :c
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc
[ if :cc
---------------- | subtract 16 (difference between ascii for ' ' (already subtracted before) and ascii for '0'
| making '0' 0; '1' 1; etc to transform ascii to integer)
|
[>+<-] | move/add :cc to :key
] |
<< :c
]
memory: | 0 | 0 | 0 | key |
^
>>> :key
[<<<+>>>-] move key
memory: | key | 0 | 0 | 0 |
^
< ^
+ start the word input loop
[
memory: | key | 0 | c | 0 | cc |
^
, take one character of the word
:c : condition for further if
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
[ if :cc
| subtract 65 (difference between ascii for ' ' (already subtracted before) and ascii for 'a'; making a 0; b 1; etc)
-----------------------------------------------------------------
|
<<<< | :key
|
[>>>>+<<<+<-] | add :key to :cc := :shifted
> | |
[<+>-] | |
|
| memory: | key | 0 | c | 0 | cc/shifted | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
>>>>>>>>> | :divisor
++++++++++++++++++++++++++ | = 26
|
<<<<<< | :shifted
|
| memory: | shifted/remainder | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
| shifted % divisor
[ | | while :remainder
| | |
| | | memory: | shifted | 0 | 0 | 0 | 0 | 0 | divisor | 0 |
| | | ^
| | |
[>>>>>>>+<<<<+<<<-] | | | duplicate :cshifted : copy of shifted
| | |
| | | memory: | 0 | 0 | 0 | shifted | 0 | 0 | divisor | cshifted |
| | | ^
>>>>>> | | | :divisor ^
| | |
[<<+>+>-] | | | duplicate
< | | | |
[>+<-] | | | |
< | | | | :cdiv : copy of divisor
| | |
| | | memory: | 0 | 0 | 0 | shifted | cdiv | 0 | divisor | cshifted |
| | | ^
| | |
| | | subtract :cdiv from :shifted until :shifted is 0
[ | | | | while :cdiv
< | | | | | :shifted
| | | | |
[<<+>+>-] | | | | | duplicate
< | | | | | |
[>+<-] | | | | | |
< | | | | | | :csh
| | | | |
| | | | | memory: | 0 | csh | 0 | shifted/remainder | cdiv | 0 | divisor | cshifted |
| | | | | ^
| | | | |
| | | | | subtract 1 from :shifted if not 0
[ | | | | | | if :csh
>>-<< | | | | | | | subtract 1 from :shifted
[-] | | | | | | | clear
] | | | | | | |
| | | | |
>>> | | | | | :cdiv
- | | | | | subtract 1
] | | | | |
| | |
| | |
| | | memory: | 0 | 0 | 0 | remainder | 0 | 0 | divisor | cshifted |
| | | ^
< | | | :remainder ^
| | |
[>+<<<<+>>>-] | | | duplicate
| | |
| | | memory: | remainder | 0 | 0 | 0 | crem | 0 | divisor | shifted/modulus |
| | | ^
> | | | :crem ^
| | |
| | | clean up modulus if a remainder is left
[ | | | if :crem
>>>[-]<<< | | | | clear :modulus
[-] | | | | clear
] | | | |
| | |
| | | if subtracting :cdiv from :shifted left a remainder we need to do continue subtracting;
| | | otherwise modulus is the modulus between :divisor and :shifted
| | |
<<<< | | | :remainder
] | | |
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
>>>>>>> | :modulus
|
[>>+<+<-] | duplicate
> | |
[<+>-] | |
> | | :cmod : copy of :modulus
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
-------------------------- | subtract 26
|
> | :eq26 : condition equal to 26
+ | add 1 (set true)
|
< | :cmod
[ | if :cmod not equal 26
>-< | | subtract 1 from :eq26 (set false)
[-] | | clear
] | |
|
> | :eq26
|
[ | if :eq26
<<<[-]>>> | | clear :modulus
[-] | | clear
] | |
|
| the modulus operation above gives 26 as a valid modulus; so this is a workaround for setting a
| modulus value of 26 to 0
|
<<<< |
[-] | clear :divisor
|
| memory: | c | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | modulus |
| ^
> | :modulus ^
[<<<<<<<+>>>>>>>-] | move :modulus
|
| memory: | c | 0 | modulus/cc | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| ^
<<<<<<< | :modulus/cc ^
|
| add 97 (ascii for 'a'; making 0 a; 1 b; etc)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
. | print
[-] | clear
] |
memory: | c | 0 | modulus/cc |
^
<< :c ^
] |
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
| #Kotlin | Kotlin | // Version 1.2.40
import kotlin.math.abs
const val EPSILON = 1.0e-15
fun main(args: Array<String>) {
var fact = 1L
var e = 2.0
var n = 2
do {
val e0 = e
fact *= n++
e += 1.0 / fact
}
while (abs(e - e0) >= EPSILON)
println("e = %.15f".format(e))
} |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Lambdatalk | Lambdatalk |
1) straightforward
{+ 1 {S.map {lambda {:n} {/ 1 {* {S.serie 1 :n}}}} {S.serie 1 17}}}
-> 2.7182818284590455
which is the value given by javascript : 2.718281828459045.
2) using recursion
{def fac
{lambda {:a :b}
{if {< :b 1}
then :a
else {fac {* :a :b} {- :b 1}}}}}
-> fac
{def euler
{lambda {:a :b}
{if {< :b 1}
then :a
else {euler {+ :a {/ 1 {fac 1 :b}}} {- :b 1}}}}}
-> euler
{euler 1 17}
-> 2.7182818284590455
|
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)
| #Prolog | Prolog | :- module('ia.pl', [tirage/1]).
:- use_module(library(clpfd)).
% to store the previous guesses and the answers
:- dynamic guess/2.
% parameters of the engine
% length of the guess
proposition(4).
% Numbers of digits
% 0 -> 8
digits(8).
% tirage(-)
tirage(Ms) :-
% are there previous guesses ?
( bagof([P, R], guess(P,R), Propositions)
-> tirage(Propositions, Ms)
; % First try
tirage_1(Ms)),
!.
% tirage_1(-)
% We choose the first Len numbers
tirage_1(L):-
proposition(Len),
Max is Len-1,
numlist(0, Max, L).
% tirage(+,-)
tirage(L, Ms) :-
proposition(Len),
length(Ms, Len),
digits(Digits),
% The guess contains only this numbers
Ms ins 0..Digits,
all_different(Ms),
% post the constraints
maplist(placees(Ms), L),
% compute a possible solution
label(Ms).
% placees(+, +])
placees(Sol, [Prop, [BP, MP]]) :-
V #= 0,
% compute the numbers of digits in good places
compte_bien_placees(Sol, Prop, V, BP1),
BP1 #= BP,
% compute the numbers of digits inbad places
compte_mal_placees(Sol, Prop, 0, V, MP1),
MP1 #= MP.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% compte_mal_placees(+, +, +, +, -).
% @arg1 : guess to create
% @arg2 : guess already used
% @arg3 : range of the first digit of the previuos arg
% @arg4 : current counter of the digit in bad places
% @arg5 : final counter of the digit in bad places
%
%
compte_mal_placees(_, [], _, MP, MP).
compte_mal_placees(Sol, [H | T], N, MPC, MPF) :-
compte_une_mal_placee(H, N, Sol, 0, 0, VF),
MPC1 #= MPC + VF,
N1 is N+1,
compte_mal_placees(Sol, T, N1, MPC1, MPF).
% Here we check one digit of an already done guess
% compte_une_mal_placee(+, +, +, +, -).
% @arg1 : the digit
% @arg2 : range of this digit
% @arg3 : guess to create
% we check each digit of this guess
% @arg4 : range of the digit of this guess
% @arg5 : current counter of the digit in bad places
% @arg6 : final counter of the digit in bad places
%
compte_une_mal_placee(_H, _N, [], _, TT, TT).
% digit in the same range, continue
compte_une_mal_placee(H, NH, [_H1 | T], NH, TTC, TTF) :-
NH1 is NH + 1, !,
compte_une_mal_placee(H, NH, T, NH1, TTC, TTF).
% same digit in different places
% increment the counter and continue continue
compte_une_mal_placee(H, NH, [H1 | T], NH1, TTC, TTF) :-
H #= H1,
NH \= NH1,
NH2 is NH1 + 1,
TTC1 #= TTC + 1,
compte_une_mal_placee(H, NH, T, NH2, TTC1, TTF).
compte_une_mal_placee(H, NH, [H1 | T], NH1, TTC, TTF) :-
H #\= H1,
NH2 is NH1 + 1,
compte_une_mal_placee(H, NH, T, NH2, TTC, TTF).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% compte_bien_placees(+, +, +, -)
% @arg1 : guess to create
% @arg2 : previous guess
% @arg3 : current counter of the digit in good places
% @arg4 : final counter of the digit in good places
%
%
compte_bien_placees([], [], MP, MP).
compte_bien_placees([H | T], [H1 | T1], MPC, MPF) :-
H #= H1,
MPC1 #= MPC + 1,
compte_bien_placees(T, T1, MPC1, MPF).
compte_bien_placees([H | T], [H1 | T1], MPC, MPF) :-
H #\= H1,
compte_bien_placees(T, T1, MPC, MPF).
|
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.
| #Raku | Raku | $_="\0".."~";<
115 97 121 32 34 91 73 78 83 69 82 84 32 83 78 79 79 80 89 32 72 69 82 69 93 34
59 114 117 110 32 60 99 97 108 62 44 64 42 65 82 71 83 91 48 93 47 47 49 57 54 57
>."$_[99]$_[104]$_[114]$_[115]"()."$_[69]$_[86]$_[65]$_[76]"() |
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
| #REXX | REXX | /*REXX program calls (invoke) a "foreign" (non-REXX) language routine/program. */
cmd = "MODE" /*define the command that is to be used*/
opts= 'CON: CP /status' /*define the options to be used for cmd*/
address 'SYSTEM' cmd opts /*invoke a cmd via the SYSTEM interface*/
/*stick a fork in it, we're all done. */ |
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
| #Ruby | Ruby | /* rc_strdup.c */
#include <stdlib.h> /* free() */
#include <string.h> /* strdup() */
#include <ruby.h>
static VALUE
rc_strdup(VALUE obj, VALUE str_in)
{
VALUE str_out;
char *c, *d;
/*
* Convert Ruby value to C string. May raise TypeError if the
* value isn't a string, or ArgumentError if it contains '\0'.
*/
c = StringValueCStr(str_in);
/* Call strdup() and perhaps raise Errno::ENOMEM. */
d = strdup(c);
if (d == NULL)
rb_sys_fail(NULL);
/* Convert C string to Ruby string. */
str_out = rb_str_new_cstr(d);
free(d);
return str_out;
}
void
Init_rc_strdup(void)
{
VALUE mRosettaCode = rb_define_module("RosettaCode");
rb_define_module_function(mRosettaCode, "strdup", rc_strdup, 1);
} |
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.
| #Erlang | Erlang |
no_argument()
one_argument( Arg )
optional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] )
variable_arguments( [Arg1, Arg2 | Rest] )
names_arguments([{name1, Arg1}, {another_name, Another}] )
% Statement context?
% First class context?
Result = obtain_result( Arg1 )
% No way to distinguish builtin/user functions
% Subroutines?
% Arguments are passed by reference, but you can not change them.
% Partial application is possible (a function returns a function that has one argument bound)
|
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
| #Sidef | Sidef | say (1..10 -> reduce('+'));
say (1..10 -> reduce{|a,b| a + b}); |
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}
| #Tcl | Tcl |
proc cartesianProduct {l1 l2} {
set result {}
foreach el1 $l1 {
foreach el2 $l2 {
lappend result [list $el1 $el2]
}
}
return $result
}
puts "simple"
puts "result: [cartesianProduct {1 2} {3 4}]"
puts "result: [cartesianProduct {3 4} {1 2}]"
puts "result: [cartesianProduct {1 2} {}]"
puts "result: [cartesianProduct {} {3 4}]"
proc cartesianNaryProduct {lists} {
set result {{}}
foreach l $lists {
set res {}
foreach comb $result {
foreach el $l {
lappend res [linsert $comb end $el]
}
}
set result $res
}
return $result
}
puts "n-ary"
puts "result: [cartesianNaryProduct {{1776 1789} {7 12} {4 14 23} {0 1}}]"
puts "result: [cartesianNaryProduct {{1 2 3} {30} {500 100}}]"
puts "result: [cartesianNaryProduct {{1 2 3} {} {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
| #jq | jq | def catalan:
if . == 0 then 1
elif . < 0 then error("catalan is not defined on \(.)")
else (2 * (2*. - 1) * ((. - 1) | catalan)) / (. + 1)
end; |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (*The strategy is to first capture all special sub-expressions and reformat them so they are semantically clear. The built in function Distribute could then do the work of creating the alternatives, but the order wouldn't match that given in the instructions (although as a set the alternatives would be correct). I'll take a more complicated route so as to follow the instructions exactly.*)
(*A few named constants for readability.*)
EscapeToken="\\";(*In Mathematica, backslash is an escape character when inputing a string, so we need to escape it.*)
LeftBraceToken="{";
RightBraceToken="}";
(*This basically sequesters escaped substrings so that they don't get matched during later processing.*)
CaptureEscapes[exp:{___String}]:=SequenceReplace[exp,{EscapeToken,x_}:>EscapeToken<>x];
(*Any remaining braces are un-escaped. I'm "unstringifying" them to more easily pick them out during later processing.*)
CaptureBraces[exp:{___String}]:=ReplaceAll[exp,{LeftBraceToken->LeftBrace,RightBraceToken->RightBrace}];
(*Building up trees for the braced expressions. Extra braces are just raw data, so transform them back to strings.*)
CaptureBraceTrees[exp:{(_String|LeftBrace|RightBrace)...}]:=ReplaceAll[FixedPoint[SequenceReplace[{LeftBrace,seq:(_String|_BraceTree)...,RightBrace}:>BraceTree[seq]],exp],{LeftBrace->LeftBraceToken,RightBrace->RightBraceToken}];
(*At thie point, we should have an expression with well-braced substructures representing potential alternatives. We must expand brace trees to alternatives in the correct order.*)
ExpandBraceTrees[exp:Expr[head___String,bt_BraceTree,tail___]]:=ReplaceAll[Thread[Expr[head,ToAlternatives[bt],tail]],alt_Alt:>Sequence@@alt];
ExpandBraceTrees[exp:Expr[___String]]:={exp};
ExpandBraceTrees[exps:{__Expr}]:=Catenate[ExpandBraceTrees/@exps];
(*If there are no commas, then it's a literal sub-expression. Otherwise, it's a set of alternatives.*)
ToAlternatives[bt_BraceTree]:={LeftBraceToken<>StringJoin@@bt<>RightBraceToken}/;FreeQ[bt,","];
ToAlternatives[BraceTree[","]]=ToAlternatives[BraceTree["",",",""]];
ToAlternatives[bt:BraceTree[",",__]]:=ToAlternatives[Prepend[bt,""]];
ToAlternatives[bt:BraceTree[__,","]]:=ToAlternatives[Append[bt,""]];
ToAlternatives[bt_BraceTree]:=Alt@@@SequenceSplit[List@@bt,{","}];
NormalizeExpression=Apply[Expr]@*CaptureBraceTrees@*CaptureBraces@*CaptureEscapes@*Characters;
BraceExpand[str_String]:=ReplaceAll[FixedPoint[ExpandBraceTrees,NormalizeExpression[str]],Expr->StringJoin];
(*Data was stored in a local file.*)
BraceTestData=ReadList[FileNameJoin[{NotebookDirectory[],"BraceTestData.txt"}],String];BraceTestData//TableForm |
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
| #Fortran | Fortran |
!Constructs a sieve of Brazilian numbers from the definition.
!From the Algol W algorithm, somewhat "Fortranized"
PROGRAM BRAZILIAN
IMPLICIT NONE
!
! PARAMETER definitions
!
INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20
!
! Local variables
!
LOGICAL , DIMENSION(1:MAX_NUMBER) :: b
INTEGER :: bcount
INTEGER :: bpos
CHARACTER(15) :: holder
CHARACTER(100) :: outline
LOGICAL , DIMENSION(1:MAX_NUMBER) :: p
!
! find some Brazilian numbers - numbers N whose representation in some !
! base B ( 1 < B < N-1 ) has all the same digits !
! set b( 1 :: n ) to a sieve of Brazilian numbers where b( i ) is true !
! if i is Brazilian and false otherwise - n must be at least 8 !
! sets p( 1 :: n ) to a sieve of primes up to n
CALL BRAZILIANSIEVE(b , MAX_NUMBER)
WRITE(6 , 34)"The first 20 Brazilian numbers:"
bcount = 0
outline = ''
holder = ''
bpos = 1
DO WHILE ( bcount<NUMVARS )
IF( b(bpos) )THEN
bcount = bcount + 1
WRITE(holder , *)bpos
outline = TRIM(outline) // " " // ADJUSTL(holder)
END IF
bpos = bpos + 1
END DO
WRITE(6 , 34)outline
WRITE(6 , 34)"The first 20 odd Brazilian numbers:"
outline = ''
holder = ''
bcount = 0
bpos = 1
DO WHILE ( bcount<NUMVARS )
IF( b(bpos) )THEN
bcount = bcount + 1
WRITE(holder , *)bpos
outline = TRIM(outline) // " " // ADJUSTL(holder)
END IF
bpos = bpos + 2
END DO
WRITE(6 , 34)outline
WRITE(6 , 34)"The first 20 prime Brazilian numbers:"
CALL ERATOSTHENES(p , MAX_NUMBER)
bcount = 0
outline = ''
holder = ''
bpos = 1
DO WHILE ( bcount<NUMVARS )
IF( b(bpos) .AND. p(bpos) )THEN
bcount = bcount + 1
WRITE(holder , *)bpos
outline = TRIM(outline) // " " // ADJUSTL(holder)
END IF
bpos = bpos + 1
END DO
WRITE(6 , 34)outline
WRITE(6 , 34)"Various Brazilian numbers:"
bcount = 0
bpos = 1
DO WHILE ( bcount<1000000 )
IF( b(bpos) )THEN
bcount = bcount + 1
IF( (bcount==100) .OR. (bcount==1000) .OR. (bcount==10000) .OR. &
& (bcount==100000) .OR. (bcount==1000000) )WRITE(* , *)bcount , &
&"th Brazilian number: " , bpos
END IF
bpos = bpos + 1
END DO
STOP
34 FORMAT(/ , a)
END PROGRAM BRAZILIAN
!
SUBROUTINE BRAZILIANSIEVE(B , N)
IMPLICIT NONE
!
! Dummy arguments
!
INTEGER :: N
LOGICAL , DIMENSION(*) :: B
INTENT (IN) N
INTENT (OUT) B
!
! Local variables
!
INTEGER :: b11
INTEGER :: base
INTEGER :: bn
INTEGER :: bnn
INTEGER :: bpower
INTEGER :: digit
INTEGER :: i
LOGICAL :: iseven
INTEGER :: powermax
!
iseven = .FALSE.
B(1:6) = .FALSE. ! numbers below 7 are not Brazilian (see task notes)
DO i = 7 , N
B(i) = iseven
iseven = .NOT.iseven
END DO
DO base = 2 , (N/2)
b11 = base + 1
bnn = b11
DO digit = 3 , base - 1 , 2
bnn = bnn + b11 + b11
IF( bnn>N )EXIT
B(bnn) = .TRUE.
END DO
END DO
DO base = 2 , INT(SQRT(FLOAT(N)))
powermax = HUGE(powermax)/base ! avoid 32 bit !
IF( powermax>N )powermax = N ! integer overflow !
DO digit = 1 , base - 1 , 2
bpower = base*base
bn = digit*(bpower + base + 1)
DO WHILE ( (bn<=N) .AND. (bpower<=powermax) )
IF( bn<=N )B(bn) = .TRUE.
bpower = bpower*base
bn = bn + (digit*bpower)
END DO
END DO
END DO
RETURN
END SUBROUTINE BRAZILIANSIEVE
!
SUBROUTINE ERATOSTHENES(P , N)
IMPLICIT NONE
!
! Dummy arguments
!
INTEGER :: N
LOGICAL , DIMENSION(*) :: P
INTENT (IN) N
INTENT (INOUT) P
!
! Local variables
!
INTEGER :: i
INTEGER :: ii
LOGICAL :: oddeven
INTEGER :: pr
!
P(1) = .FALSE.
P(2) = .TRUE.
oddeven = .TRUE.
DO i = 3 , N
P(i) = oddeven
oddeven = .NOT.oddeven
END DO
DO i = 2 , INT(SQRT(FLOAT(N)))
ii = i + i
IF( P(i) )THEN
DO pr = i*i , N , ii
P(pr) = .FALSE.
END DO
END IF
END DO
RETURN
END SUBROUTINE ERATOSTHENES
|
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
| #F.23 | F# | let getCalendar year =
let day_of_week month year =
let t = [|0; 3; 2; 5; 0; 3; 5; 1; 4; 6; 2; 4|]
let y = if month < 3 then year - 1 else year
let m = month
let d = 1
(y + y / 4 - y / 100 + y / 400 + t.[m - 1] + d) % 7
//0 = Sunday, 1 = Monday, ...
let last_day_of_month month year =
match month with
| 2 -> if (0 = year % 4 && (0 = year % 400 || 0 <> year % 100)) then 29 else 28
| 4 | 6 | 9 | 11 -> 30
| _ -> 31
let get_month_calendar year month =
let min (x: int, y: int) = if x < y then x else y
let ld = last_day_of_month month year
let dw = 7 - (day_of_week month year)
[|[|1..dw|];
[|dw + 1..dw + 7|];
[|dw + 8..dw + 14|];
[|dw + 15..dw + 21|];
[|dw + 22..min(ld, dw + 28)|];
[|min(ld + 1, dw + 29)..ld|]|]
let sb_fold (f:System.Text.StringBuilder -> 'a -> System.Text.StringBuilder) (sb:System.Text.StringBuilder) (xs:'a array) =
for x in xs do (f sb x) |> ignore
sb
let sb_append (text:string) (sb:System.Text.StringBuilder) = sb.Append(text)
let sb_appendln sb = sb |> sb_append "\n" |> ignore
let sb_fold_in_range a b f sb = [|a..b|] |> sb_fold f sb |> ignore
let mask_builder mask = Printf.StringFormat<string -> string>(mask)
let center n (s:string) =
let l = (n - s.Length) / 2 + s.Length
let f n s = sprintf (mask_builder ("%" + (n.ToString()) + "s")) s
(f l s) + (f (n - l) "")
let left n (s:string) = sprintf (mask_builder ("%-" + (n.ToString()) + "s")) s
let right n (s:string) = sprintf (mask_builder ("%" + (n.ToString()) + "s")) s
let array2string xs =
let ys = xs |> Array.map (fun x -> sprintf "%2d " x)
let sb = ys |> sb_fold (fun sb y -> sb.Append(y)) (new System.Text.StringBuilder())
sb.ToString()
let xsss =
let m = get_month_calendar year
[|1..12|] |> Array.map (fun i -> m i)
let months = [|"January"; "February"; "March"; "April"; "May"; "June"; "July"; "August"; "September"; "October"; "November"; "December"|]
let sb = new System.Text.StringBuilder()
sb |> sb_append "\n" |> sb_append (center 74 (year.ToString())) |> sb_appendln
for i in 0..3..9 do
sb |> sb_appendln
sb |> sb_fold_in_range i (i + 2) (fun sb i -> sb |> sb_append (center 21 months.[i]) |> sb_append " ")
sb |> sb_appendln
sb |> sb_fold_in_range i (i + 2) (fun sb i -> sb |> sb_append "Su Mo Tu We Th Fr Sa " |> sb_append " ")
sb |> sb_appendln
sb |> sb_fold_in_range i (i + 2) (fun sb i -> sb |> sb_append (right 21 (array2string (xsss.[i].[0]))) |> sb_append " ")
sb |> sb_appendln
for j = 1 to 5 do
sb |> sb_fold_in_range i (i + 2) (fun sb i -> sb |> sb_append (left 21 (array2string (xsss.[i].[j]))) |> sb_append " ")
sb |> sb_appendln
sb.ToString()
let printCalendar year = getCalendar year |
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.
| #Haskell | Haskell | import Control.Monad
import Control.Monad.ST
import Data.STRef
import Data.Array.ST
import System.Random
import Bitmap
import Bitmap.BW
import Bitmap.Netpbm
main = do
g <- getStdGen
(t, _) <- stToIO $ drawTree (50, 50) (25, 25) 300 g
writeNetpbm "/tmp/tree.pbm" t
drawTree :: (Int, Int) -> (Int, Int) -> Int -> StdGen -> ST s (Image s BW, StdGen)
drawTree (width, height) start steps stdgen = do
img <- image width height off
setPix img (Pixel start) on
gen <- newSTRef stdgen
let -- randomElem :: [a] -> ST s a
randomElem l = do
stdgen <- readSTRef gen
let (i, stdgen') = randomR (0, length l - 1) stdgen
writeSTRef gen stdgen'
return $ l !! i
-- newPoint :: ST s (Int, Int)
newPoint = do
p <- randomElem border
c <- getPix img $ Pixel p
if c == off then return p else newPoint
-- wander :: (Int, Int) -> ST s ()
wander p = do
next <- randomElem $ filter (inRange pointRange) $ adjacent p
c <- getPix img $ Pixel next
if c == on then setPix img (Pixel p) on else wander next
replicateM_ steps $ newPoint >>= wander
stdgen <- readSTRef gen
return (img, stdgen)
where pointRange = ((0, 0), (width - 1, height - 1))
adjacent (x, y) = [(x - 1, y - 1), (x, y - 1), (x + 1, y - 1),
(x - 1, y), (x + 1, y),
(x - 1, y + 1), (x, y + 1), (x + 1, y + 1)]
border = liftM2 (,) [0, width - 1] [0 .. height - 1] ++
liftM2 (,) [1 .. width - 2] [0, height - 1]
off = black
on = white |
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
| #Common_Lisp | Common Lisp | (defun get-number ()
(do ((digits '()))
((>= (length digits) 4) digits)
(pushnew (1+ (random 9)) digits)))
(defun compute-score (guess number)
(let ((cows 0)
(bulls 0))
(map nil (lambda (guess-digit number-digit)
(cond ((= guess-digit number-digit) (incf bulls))
((member guess-digit number) (incf cows))))
guess number)
(values cows bulls)))
(defun number->guess (number)
(when (integerp number)
(do ((digits '()))
((zerop number) digits)
(multiple-value-bind (quotient remainder) (floor number 10)
(push remainder digits)
(setf number quotient)))))
(defun valid-guess-p (guess)
(and (= 4 (length guess))
(every (lambda (digit) (<= 1 digit 9)) guess)
(equal guess (remove-duplicates guess))))
(defun play-game (&optional (stream *query-io*))
(do ((number (get-number))
(cows 0)
(bulls 0))
((= 4 bulls))
(format stream "~&Guess a 4-digit number: ")
(let ((guess (number->guess (read stream))))
(cond ((not (valid-guess-p guess))
(format stream "~&Malformed guess."))
(t
(setf (values cows bulls) (compute-score guess number))
(if (= 4 bulls)
(format stream "~&Correct, you win!")
(format stream "~&Score: ~a cows, ~a bulls."
cows bulls))))))) |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
#define decrypt_rot(x, y) rot((26-x), y)
void rot(int c, char *str)
{
int l = strlen(str);
const char* alpha_low = "abcdefghijklmnopqrstuvwxyz";
const char* alpha_high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char subst; /* substitution character */
int idx; /* index */
int i; /* loop var */
for (i = 0; i < l; i++) /* for each letter in string */
{
if( 0 == isalpha(str[i]) ) continue; /* not alphabet character */
idx = (int) (tolower(str[i]) - 'a') + c) % 26; /* compute index */
if( isupper(str[i]) )
subst = alpha_high[idx];
else
subst = alpha_low[idx];
str[i] = subst;
}
}
int main(int argc, char** argv)
{
char str[] = "This is a top secret text message!";
printf("Original: %s\n", str);
caesar(str);
printf("Encrypted: %s\n", str);
decaesar(str);
printf("Decrypted: %s\n", str);
return 0;
} |
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
| #langur | langur | mode divMaxScale = 104
val .epsilon = 1.0e-104
var .e = 2
for .fact, .n = 1, 2 ; ; .n += 1 {
val .e0 = .e
.fact x= .n
.e += 1 / .fact
if abs(.e - .e0) < .epsilon: break
}
writeln ".e = ", .e
# compare to built-in constant e
writeln " e = ", e |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Lua | Lua | EPSILON = 1.0e-15;
fact = 1
e = 2.0
e0 = 0.0
n = 2
repeat
e0 = e
fact = fact * n
n = n + 1
e = e + 1.0 / fact
until (math.abs(e - e0) < EPSILON)
io.write(string.format("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)
| #PureBasic | PureBasic | #answerSize = 4
Structure history
answer.s
bulls.i
cows.i
EndStructure
Procedure evaluateGuesses(*answer.history, List remainingGuesses.s())
Protected i, cows, bulls
ForEach remainingGuesses()
bulls = 0: cows = 0
For i = 1 To #answerSize
If Mid(remainingGuesses(), i, 1) = Mid(*answer\answer, i, 1)
bulls + 1
ElseIf FindString(remainingGuesses(), Mid(*answer\answer, i, 1), 1)
cows + 1
EndIf
Next
If bulls <> *answer\bulls Or cows <> *answer\cows
DeleteElement(remainingGuesses())
EndIf
Next
EndProcedure
Procedure findPermutations(List permutations.s(), elementChar.s, permSize)
Protected i, j, stackDepth, elementCount = Len(elementChar) - 1, working.s = Space(permSize), *working = @working
permSize - 1
Dim stack(permSize) ;holds index states
Dim elements(elementCount)
Dim elementChar.c(elementCount)
For i = 0 To elementCount
elementChar(i) = PeekC(@elementChar + i * SizeOf(Character))
Next
i = 0
Repeat
While i <= elementCount
If elements(i) = 0
stack(stackDepth) = i
If stackDepth = permSize
For j = 0 To permSize
PokeC(*working + j * SizeOf(Character), elementChar(stack(j)))
Next
AddElement(permutations())
permutations() = working
Else
elements(i) = 1
stackDepth + 1
i = 0
Continue ;skip update
EndIf
EndIf
i + 1
Wend
stackDepth - 1
If stackDepth < 0
Break
EndIf
i = stack(stackDepth) + 1
elements(i - 1) = 0
ForEver
EndProcedure
If OpenConsole()
Define guess.s, guessNum, score.s, delimeter.s
NewList remainingGuesses.s()
NewList answer.history()
findPermutations(remainingGuesses(), "123456789", 4)
PrintN("Playing Bulls & Cows with " + Str(#answerSize) + " unique digits." + #CRLF$)
Repeat
If ListSize(remainingGuesses()) = 0
If answer()\bulls = #answerSize And answer()\cows = 0
PrintN(#CRLF$ + "Solved!")
Break ;exit Repeat/Forever
EndIf
PrintN(#CRLF$ + "BadScoring! Nothing fits the scores you gave.")
ForEach answer()
PrintN(answer()\answer + " -> [" + Str(answer()\bulls) + ", " + Str(answer()\cows) + "]")
Next
Break ;exit Repeat/Forever
Else
guessNum + 1
SelectElement(remainingGuesses(), Random(ListSize(remainingGuesses()) - 1))
guess = remainingGuesses()
DeleteElement(remainingGuesses())
Print("Guess #" + Str(guessNum) + " is " + guess + ". What does it score (bulls, cows)?")
score = Input()
If CountString(score, ",") > 0: delimeter = ",": Else: delimeter = " ": EndIf
AddElement(answer())
answer()\answer = guess
answer()\bulls = Val(StringField(score, 1, delimeter))
answer()\cows = Val(StringField(score, 2, delimeter))
evaluateGuesses(@answer(), remainingGuesses())
EndIf
ForEver
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.
| #REXX | REXX | /*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/
@ABC=
PARSE VALUE SCRSIZE() WITH SD SW .
DO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END
@ABCU=@ABC; UPPER @ABCU
DAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
MONTHS_='JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER'
DAYS=; MONTHS=
DO J=1 FOR 7
_=LOWER(WORD(DAYS_,J))
DAYS=DAYS TRANSLATE(LEFT(_,1))SUBSTR(_,2)
END
DO J=1 FOR 12
_=LOWER(WORD(MONTHS_,J))
MONTHS=MONTHS TRANSLATE(LEFT(_,1))SUBSTR(_,2)
END
CALFILL=' '; MC=12; _='1 3 1234567890' "FB"X
PARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN
_=0; PARSE VAR _ COLS 1 JD 1 LOWERCASE 1 MAXKALPUTS 1 NARROW 1,
NARROWER 1 NARROWEST 1 SHORT 1 SHORTER 1 SHORTEST 1,
SMALL 1 SMALLER 1 SMALLEST 1 UPPERCASE
PARSE ARG MM '/' DD "/" YYYY _ '(' OPS; UOPS=OPS
IF _\=='' | \IS#(MM) | \IS#(DD) | \IS#(YYYY) THEN CALL ERX 86
@CALMONTHS ='CALMON' || LOWER('THS')
@CALSPACES ='CALSP' || LOWER('ACES')
@DEPTH ='DEP' || LOWER('TH')
@GRIDS ='GRID' || LOWER('S')
@LOWERCASE ='LOW' || LOWER('ERCASE')
@NARROW ='NAR' || LOWER('ROW')
@NARROWER ='NARROWER'
@NARROWEST ='NARROWES' || LOWER('T')
@SHORT ='SHOR' || LOWER('T')
@SHORTER ='SHORTER'
@SHORTEST ='SHORTES' || LOWER('T')
@UPPERCASE ='UPP' || LOWER('ERCASE')
@WIDTH ='WID' || LOWER('TH')
DO WHILE OPS\==''; OPS=STRIP(OPS,'L'); PARSE VAR OPS _1 2 1 _ . 1 _O OPS
UPPER _
SELECT
WHEN ABB(@CALMONTHS) THEN MC=NAI()
WHEN ABB(@CALSPACES) THEN CALSPACES=NAI()
WHEN ABB(@DEPTH) THEN SD=NAI()
WHEN ABBN(@GRIDS) THEN GRID=NO()
WHEN ABBN(@LOWERCASE) THEN LOWERCASE=NO()
WHEN ABBN(@NARROW) THEN NARROW=NO()
WHEN ABBN(@NARROWER) THEN NARROWER=NO()
WHEN ABBN(@NARROWEST) THEN NARROWEST=NO()
WHEN ABBN(@SHORT) THEN SHORT=NO()
WHEN ABBN(@SHORTER) THEN SHORTER=NO()
WHEN ABBN(@SHORTEST) THEN SHORTEST=NO()
WHEN ABBN(@SMALL) THEN SMALL=NO()
WHEN ABBN(@SMALLER) THEN SMALLER=NO()
WHEN ABBN(@SMALLEST) THEN SMALLEST=NO()
WHEN ABBN(@UPPERCASE) THEN UPPERCASE=NO()
WHEN ABB(@WIDTH) THEN SW=NAI()
OTHERWISE NOP
END /*SELECT*/
END /*DO WHILE OPTS\== ...*/
IF SD==0 THEN SD= 43; SD= SD-3
IF SW==0 THEN SW= 80; SW= SW-1
MC=INT(MC,'MONTHSCALENDER'); IF MC>0 THEN CAL=1
DAYS=' 'DAYS; MONTHS=' 'MONTHS
CYYYY=RIGHT(DATE(),4); HYY=LEFT(CYYYY,2); LYY=RIGHT(CYYYY,2)
DY.=31; _=30; PARSE VAR _ DY.4 1 DY.6 1 DY.9 1 DY.11; DY.2=28+LY(YYYY)
YY=RIGHT(YYYY,2); CW=10; CINDENT=1; CALWIDTH=76
IF SMALL THEN DO; NARROW=1 ; SHORT=1 ; END
IF SMALLER THEN DO; NARROWER=1 ; SHORTER=1 ; END
IF SMALLEST THEN DO; NARROWEST=1; SHORTEST=1; END
IF SHORTEST THEN SHORTER=1
IF SHORTER THEN SHORT =1
IF NARROW THEN DO; CW=9; CINDENT=3; CALWIDTH=69; END
IF NARROWER THEN DO; CW=4; CINDENT=1; CALWIDTH=34; END
IF NARROWEST THEN DO; CW=2; CINDENT=1; CALWIDTH=20; END
CV_=CALWIDTH+CALSPACES+2
CALFILL=LEFT(COPIES(CALFILL,CW),CW)
DO J=1 FOR 7; _=WORD(DAYS,J)
DO JW=1 FOR 3; _D=STRIP(SUBSTR(_,CW*JW-CW+1,CW))
IF JW=1 THEN _D=CENTRE(_D,CW+1)
ELSE _D=LEFT(_D,CW+1)
DAYS.JW=DAYS.JW||_D
END /*JW*/
__=DAYSN
IF NARROWER THEN DAYSN=__||CENTRE(LEFT(_,3),5)
IF NARROWEST THEN DAYSN=__||CENTER(LEFT(_,2),3)
END /*J*/
_YYYY=YYYY; CALPUTS=0; CV=1; _MM=MM+0; MONTH=WORD(MONTHS,MM)
DY.2=28+LY(_YYYY); DIM=DY._MM; _DD=01; DOW=DOW(_MM,_DD,_YYYY); $DD=DD+0
/*─────────────────────────────NOW: THE BUSINESS OF THE BUILDING THE CAL*/
CALL CALGEN
DO _J=2 TO MC
IF CV_\=='' THEN DO
CV=CV+CV_
IF CV+CV_>=SW THEN DO; CV=1; CALL CALPUT
CALL FCALPUTS;CALL CALPB
END
ELSE CALPUTS=0
END
ELSE DO;CALL CALPB;CALL CALPUT;CALL FCALPUTS;END
_MM=_MM+1; IF _MM==13 THEN DO; _MM=1; _YYYY=_YYYY+1; END
MONTH=WORD(MONTHS,_MM); DY.2=28+LY(_YYYY); DIM=DY._MM
DOW=DOW(_MM,_DD,_YYYY); $DD=0; CALL CALGEN
END /*_J*/
CALL FCALPUTS
RETURN _
/*─────────────────────────────CALGEN SUBROUTINE────────────────────────*/
CALGEN: CELLX=;CELLJ=;CELLM=;CALCELLS=0;CALLINE=0
CALL CALPUT
CALL CALPUTL COPIES('─',CALWIDTH),"┌┐"; CALL CALHD
CALL CALPUTL MONTH ' ' _YYYY ; CALL CALHD
IF NARROWEST | NARROWER THEN CALL CALPUTL DAYSN
ELSE DO JW=1 FOR 3
IF SPACE(DAYS.JW)\=='' THEN CALL CALPUTL DAYS.JW
END
CALFT=1; CALFB=0
DO JF=1 FOR DOW-1; CALL CELLDRAW CALFILL,CALFILL; END
DO JY=1 FOR DIM; CALL CELLDRAW JY; END
CALFB=1
DO 7; CALL CELLDRAW CALFILL,CALFILL; END
IF SD>32 & \SHORTER THEN CALL CALPUT
RETURN
/*─────────────────────────────CELLDRAW SUBROUTINE──────────────────────*/
CELLDRAW: PARSE ARG ZZ,CDDOY;ZZ=RIGHT(ZZ,2);CALCELLS=CALCELLS+1
IF CALCELLS>7 THEN DO
CALLINE=CALLINE+1
CELLX=SUBSTR(CELLX,2)
CELLJ=SUBSTR(CELLJ,2)
CELLM=SUBSTR(CELLM,2)
CELLB=TRANSLATE(CELLX,,")(─-"#)
IF CALLINE==1 THEN CALL CX
CALL CALCSM; CALL CALPUTL CELLX; CALL CALCSJ; CALL CX
CELLX=; CELLJ=; CELLM=; CALCELLS=1
END
CDDOY=RIGHT(CDDOY,CW); CELLM=CELLM'│'CENTER('',CW)
CELLX=CELLX'│'CENTRE(ZZ,CW); CELLJ=CELLJ'│'CENTER('',CW)
RETURN
/*═════════════════════════════GENERAL 1-LINE SUBS══════════════════════*/
ABB:ARG ABBU;PARSE ARG ABB;RETURN ABBREV(ABBU,_,ABBL(ABB))
ABBL:RETURN VERIFY(ARG(1)LEFT(@ABC,1),@ABC,'M')-1
ABBN:PARSE ARG ABBN;RETURN ABB(ABBN)|ABB('NO'ABBN)
CALCSJ:IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;IF SD>24&\SHORT THEN CALL CALPUTL CELLJ; RETURN
CALCSM:IF SD>24&\SHORT THEN CALL CALPUTL CELLM;IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;RETURN
CALHD:IF SD>24&\SHORTER THEN CALL CALPUTL;IF SD>32&\SHORTEST THEN CALL CALPUTL;RETURN
CALPB:IF \GRID&SHORTEST THEN CALL PUT CHK;RETURN
CALPUT:CALPUTS=CALPUTS+1;MAXKALPUTS=MAX(MAXKALPUTS,CALPUTS);IF SYMBOL('CT.'CALPUTS)\=='VAR' THEN CT.CALPUTS=;CT.CALPUTS=OVERLAY(ARG(1),CT.CALPUTS,CV);RETURN
CALPUTL:CALL CALPUT COPIES(' ',CINDENT)LEFT(ARG(2)"│",1)CENTER(ARG(1),CALWIDTH)||RIGHT('│'ARG(2),1);RETURN
CX:CX_='├┤';CX=COPIES(COPIES('─',CW)'┼',7);IF CALFT THEN DO;CX=TRANSLATE(CX,'┬',"┼");CALFT=0;END;IF CALFB THEN DO;CX=TRANSLATE(CX,'┴',"┼");CX_='└┘';CALFB=0;END;CALL CALPUTL CX,CX_;RETURN
DOW:PROCEDURE;ARG M,D,Y;IF M<3 THEN DO;M=M+12;Y=Y-1;END;YL=LEFT(Y,2);YR=RIGHT(Y,2);W=(D+(M+1)*26%10+YR+YR%4+YL%4+5*YL)//7;IF W==0 THEN W=7;RETURN W
ER:PARSE ARG _1,_2;CALL '$ERR' "14"P(_1) P(WORD(_1,2) !FID(1)) _2;IF _1<0 THEN RETURN _1;EXIT RESULT
ERR:CALL ER '-'ARG(1),ARG(2);RETURN ''
ERX:CALL ER '-'ARG(1),ARG(2);EXIT ''
FCALPUTS: DO J=1 FOR MAXKALPUTS;CALL PUT CT.J;END;CT.=;MAXKALPUTS=0;CALPUTS=0;RETURN
INT:INT=NUMX(ARG(1),ARG(2));IF \ISINT(INT) THEN CALL ERX 92,ARG(1) ARG(2);RETURN INT/1
IS#:RETURN VERIFY(ARG(1),#)==0
ISINT:RETURN DATATYPE(ARG(1),'W')
LOWER:RETURN TRANSLATE(ARG(1),@ABC,@ABCU)
LY:ARG _;IF LENGTH(_)==2 THEN _=HYY||_;LY=_//4==0;IF LY==0 THEN RETURN 0;LY=((_//100\==0)|_//400==0);RETURN LY
NA:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);PARSE VAR OPS NA OPS;IF NA=='' THEN CALL ERX 35,_O;RETURN NA
NAI:RETURN INT(NA(),_O)
NAN:RETURN NUMX(NA(),_O)
NO:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);RETURN LEFT(_,2)\=='NO'
NUM:PROCEDURE;PARSE ARG X .,F,Q;IF X=='' THEN RETURN X;IF DATATYPE(X,'N') THEN RETURN X/1;X=SPACE(TRANSLATE(X,,','),0);IF DATATYPE(X,'N') THEN RETURN X/1;RETURN NUMNOT()
NUMNOT:IF Q==1 THEN RETURN X;IF Q=='' THEN CALL ER 53,X F;CALL ERX 53,X F
NUMX:RETURN NUM(ARG(1),ARG(2),1)
P:RETURN WORD(ARG(1),1)
PUT:_=ARG(1);_=TRANSLATE(_,,'_'CHK);IF \GRID THEN _=UNGRID(_);IF LOWERCASE THEN _=LOWER(_);IF UPPERCASE THEN UPPER _;IF SHORTEST&_=' ' THEN RETURN;CALL TELL _;RETURN
TELL:SAY ARG(1);RETURN
UNGRID:RETURN TRANSLATE(ARG(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣") |
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
| #Rust | Rust | extern crate libc;
//c function that returns the sum of two integers
extern {
fn add_input(in1: libc::c_int, in2: libc::c_int) -> libc::c_int;
}
fn main() {
let (in1, in2) = (5, 4);
let output = unsafe {
add_input(in1, in2) };
assert!( (output == (in1 + in2) ),"Error in sum calculation") ;
} |
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
| #Scala | Scala | object JNIDemo {
try System.loadLibrary("JNIDemo")
private def callStrdup(s: String)
println(callStrdup("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.
| #F.23 | F# | // No arguments
noArgs()
// Fixed number of arguments
oneArg x
// Optional arguments
// In a normal function:
optionalArgs <| Some(5) <| None
// In a function taking a tuple:
optionalArgsInTuple(Some(5), None)
// In a function in a type:
foo.optionalArgs 5;;
// However, if you want to pass more than one paramter, the arguments must be
// passed in a tuple:
foo.optionalArgs(5, 6)
// Function with a variable number of arguments
variableArgs 5 6 7 // etc...
// Named arguments can only be used in type methods taking a tuple. The
// arguments can appear in any order.
foo.namedArgs(x = 5, y = 6)
// Using a function in a statement
for i = 0 to someFunc() do
printfn "Something"
// Using a function in a first-class context
funcArgs someFunc
// Obtaining a return value
let x = someFunc()
// Built-in functions: do functions like (+) or (-) count?
// Parameters are normally passed by value (as shown in the previous examples),
// but they can be passed by reference.
// Passing by reference:
refArgs &mutableVal
// Partial application example
let add2 = (+) 2 |
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
| #Standard_ML | Standard ML | - val nums = [1,2,3,4,5,6,7,8,9,10];
val nums = [1,2,3,4,5,6,7,8,9,10] : int list
- val sum = foldl op+ 0 nums;
val sum = 55 : int
- val product = foldl op* 1 nums;
val product = 3628800 : int |
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}
| #UNIX_Shell | UNIX Shell | $ printf '%s' "("{1,2},{3,4}")"; printf '\n'
(1,3)(1,4)(2,3)(2,4)
$ printf '%s' "("{3,4},{1,2}")"; printf '\n'
(3,1)(3,2)(4,1)(4,2)
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Julia | Julia | catalannum(n::Integer) = binomial(2n, n) ÷ (n + 1)
@show catalannum.(1:15)
@show catalannum(big(100)) |
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
| #Nim | Nim | proc expandBraces(str: string) =
var
escaped = false
depth = 0
bracePoints: seq[int]
bracesToParse: seq[int]
for idx, ch in str:
case ch
of '\\':
escaped = not escaped
of '{':
inc depth
if not escaped and depth == 1:
bracePoints = @[idx]
of ',':
if not escaped and depth == 1:
bracePoints &= idx
of '}':
if not escaped and depth == 1 and bracePoints.len >= 2:
bracesToParse = bracePoints & idx
dec depth
else:
discard
if ch != '\\':
escaped = false
if bracesToParse.len > 0:
let prefix = str[0..<bracesToParse[0]]
let suffix = str[(bracesToParse[^1] + 1)..^1]
for idx in 1..bracesToParse.high:
let option = str[(bracesToParse[idx - 1] + 1)..(bracesToParse[idx] - 1)]
expandBraces(prefix & option & suffix)
else:
echo " ", str
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
for str in ["It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"]:
echo "\nExpansions of \"", str, "\":"
expandBraces(str) |
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
| #FreeBASIC | FreeBASIC | Function sameDigits(Byval n As Integer, Byval b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b
While n > 0
If n Mod b <> f Then Return False Else n \= b
Wend
Return True
End Function
Function isBrazilian(Byval n As Integer) As Boolean
If n < 7 Then Return False
If n Mod 2 = 0 Then Return True
For b As Integer = 2 To n - 2
If sameDigits(n, b) Then Return True
Next b
Return False
End Function
Function isPrime(Byval n As Integer) As Boolean
If n < 2 Then Return False
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False Else d += 2
If n Mod d = 0 Then Return False Else d += 4
Wend
Return True
End Function
Dim kind(2) As String ={"", "odd", "prime"}
For i As Integer = 0 To 2
Print Using "First 20 & Brazilian numbers: "; kind(i)
Dim Limit As Integer = 20, n As Integer = 7
Do
If isBrazilian(n) Then Print Using "& "; n; : Limit -= 1
Select Case kind(i)
Case "" : n += 1
Case "odd" : n += 2
Case "prime" : Do : n += 2 : Loop Until isPrime(n)
End Select
Loop While Limit > 0
Next i
Sleep |
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
| #Factor | Factor | USING: arrays calendar.format grouping io.streams.string kernel
math.ranges prettyprint sequences sequences.interleaved ;
IN: rosetta-code.calendar
: calendar ( year -- )
12 [1,b] [ 2array [ month. ] with-string-writer ] with map
3 <groups> [ " " <interleaved> ] map 5 " " <repetition>
<interleaved> simple-table. ;
: calendar-demo ( -- ) 1969 calendar ;
MAIN: calendar-demo |
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.
| #Icon_and_Unicon | Icon and Unicon | link graphics,printf
procedure main() # brownian tree
Density := .08 # % particles to area
SeedArea := .5 # central area to confine seed
ParticleArea := .7 # central area to exclude particles appearing
Height := Width := 400 # canvas
Particles := Height * Width * Density
Field := list(Height)
every !Field := list(Width)
Size := sprintf("size=%d,%d",Width,Height)
Fg := sprintf("fg=%s",?["green","red","blue"])
Label := sprintf("label=Brownian Tree %dx%d PA=%d%% SA=%d%% D=%d%%",
Width,Height,ParticleArea*100,SeedArea*100,Density*100)
WOpen(Label,Size,Fg,"bg=black") | stop("Unable to open Window")
sx := Height * SetInside(SeedArea)
sy := Width * SetInside(SeedArea)
Field[sx,sy] := 1
DrawPoint(sx,sy) # Seed the field
Lost := 0
every 1 to Particles do {
repeat {
px := Height * SetOutside(ParticleArea)
py := Width * SetOutside(ParticleArea)
if /Field[px,py] then
break # don't materialize in the tree
}
repeat {
dx := delta()
dy := delta()
if not ( xy := Field[px+dx,py+dy] ) then {
Lost +:= 1
next # lost try again
}
if \xy then
break # collision
px +:= dx # move to clear spot
py +:= dy
}
Field[px,py] := 1
DrawPoint(px,py) # Stick the particle
}
printf("Brownian Tree Complete: Particles=%d Lost=%d.\n",Particles,Lost)
WDone()
end
procedure delta() #: return a random 1 pixel perturbation
return integer(?0 * 3) - 1
end
procedure SetInside(core) #: set coord inside area
return core * ?0 + (1-core)/2
end
procedure SetOutside(core) #: set coord outside area
pt := ?0 * (1 - core)
pt +:= ( pt > (1-core)/2, core)
return pt
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
| #Crystal | Crystal | size = 4
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char
i = 0
loop do
i += 1
loop do
print "Guess #{i}: "
guess = gets.not_nil!.chomp.chars
exit if guess.empty?
break if guess.size == size &&
guess.all? { |x| ('1'..'9').includes? x } &&
guess.uniq.size == size
puts "Problem, try again. You need to enter #{size} unique digits from 1 to 9"
end
if guess == secret
puts "Congratulations you guessed correctly in #{i} attempts"
break
end
bulls = cows = 0
size.times do |j|
if guess[j] == secret[j]
bulls += 1
elsif secret.includes? guess[j]
cows += 1
end
end
puts "Bulls: #{bulls}; Cows: #{cows}"
end |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #C.23 | C# | using System;
using System.Linq;
namespace CaesarCypher
{
class Program
{
static char Encrypt(char ch, int code)
{
if (!char.IsLetter(ch)) return ch;
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)((ch + code - offset) % 26 + offset);
}
static string Encrypt(string input, int code)
{
return new string(input.Select(ch => Encrypt(ch, code)).ToArray());
}
static string Decrypt(string input, int code)
{
return Encrypt(input, 26 - code);
}
const string TestCase = "Pack my box with five dozen liquor jugs.";
static void Main()
{
string str = TestCase;
Console.WriteLine(str);
str = Encrypt(str, 5);
Console.WriteLine("Encrypted: " + str);
str = Decrypt(str, 5);
Console.WriteLine("Decrypted: " + str);
Console.ReadKey();
}
}
} |
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
| #M2000_Interpreter | M2000 Interpreter |
Module FindE {
Function comp_e (n){
\\ max 28 for decimal (in one line with less spaces)
n/=28:For i=27to 1:n=1+n/i:Next i:=n
}
Clipboard Str$(comp_e(1@),"")+" Decimal"+{
}+Str$(comp_e(1),"")+" Double"+{
}+Str$(comp_e(1~),"")+" Float"+{
}+Str$(comp_e(1#),"")+" Currency"+{
}
Report Str$(comp_e(1@),"")+" Decimal"+{
}+Str$(comp_e(1),"")+" Double"+{
}+Str$(comp_e(1~),"")+" Float"+{
}+Str$(comp_e(1#),"")+" Currency"+{
}
}
FindE
|
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
| #Maple | Maple | evalf[50](add(1/n!,n=0..100));
# 2.7182818284590452353602874713526624977572470937000
evalf[50](exp(1));
# 2.7182818284590452353602874713526624977572470937000 |
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)
| #Python | Python | from itertools import permutations
from random import shuffle
try:
raw_input
except:
raw_input = input
try:
from itertools import izip
except:
izip = zip
digits = '123456789'
size = 4
def parse_score(score):
score = score.strip().split(',')
return tuple(int(s.strip()) for s in score)
def scorecalc(guess, chosen):
bulls = cows = 0
for g,c in izip(guess, chosen):
if g == c:
bulls += 1
elif g in chosen:
cows += 1
return bulls, cows
choices = list(permutations(digits, size))
shuffle(choices)
answers = []
scores = []
print ("Playing Bulls & Cows with %i unique digits\n" % size)
while True:
ans = choices[0]
answers.append(ans)
#print ("(Narrowed to %i possibilities)" % len(choices))
score = raw_input("Guess %2i is %*s. Answer (Bulls, cows)? "
% (len(answers), size, ''.join(ans)))
score = parse_score(score)
scores.append(score)
#print("Bulls: %i, Cows: %i" % score)
found = score == (size, 0)
if found:
print ("Ye-haw!")
break
choices = [c for c in choices if scorecalc(c, ans) == score]
if not choices:
print ("Bad scoring? nothing fits those scores you gave:")
print (' ' +
'\n '.join("%s -> %s" % (''.join(an),sc)
for an,sc in izip(answers, scores)))
break |
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.
| #Ring | Ring |
# PROJECT : CALENDAR - FOR "REAL" PROGRAMMERS
# DATE : 2018/06/28
# AUTHOR : GAL ZSOLT (~ CALMOSOFT ~)
# EMAIL : <[email protected]>
LOAD "GUILIB.RING"
LOAD "STDLIB.RING"
NEW QAPP
{
WIN1 = NEW QWIDGET() {
DAY = LIST(12)
POS = NEWLIST(12,37)
MONTH = LIST(12)
WEEK = LIST(7)
WEEKDAY = LIST(7)
BUTTON = NEWLIST(7,6)
MONTHSNAMES = LIST(12)
WEEK = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"]
MONTHS = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
"AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]
DAYSNEW = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]]
MO = [4,0,0,3,5,1,3,6,2,4,0,2]
MON = [31,28,31,30,31,30,31,31,30,31,30,31]
M2 = (((1969-1900)%7) + FLOOR((1969 - 1900)/4) % 7) % 7
FOR N = 1 TO 12
MONTH[N] = (MO[N] + M2) % 7
X = (MONTH[N] + 1) % 7 + 1
FOR M = 1 TO LEN(DAYSNEW)
IF DAYSNEW[M][1] = X
NR = M
OK
NEXT
DAY[N] = DAYSNEW[NR][2]
NEXT
FOR M = 1 TO 12
FOR N = 1 TO DAY[M] - 1
POS[M][N] = " "
NEXT
NEXT
FOR M = 1 TO 12
FOR N = DAY[M] TO 37
IF N < (MON[M] + DAY[M])
POS[M][N] = N - DAY[M] + 1
ELSE
POS[M][N] = " "
OK
NEXT
NEXT
SETWINDOWTITLE("CALENDAR")
SETGEOMETRY(100,100,650,800)
LABEL1 = NEW QLABEL(WIN1) {
SETGEOMETRY(10,10,800,600)
SETTEXT("")
}
YEAR = NEW QPUSHBUTTON(WIN1)
{
SETGEOMETRY(280,20,63,20)
YEAR.SETTEXT("1969")
}
FOR N = 1 TO 4
NR = (N-1)*3+1
SHOWMONTHS(NR)
NEXT
FOR N = 1 TO 12
SHOWWEEKS(N)
NEXT
FOR N = 1 TO 12
SHOWDAYS(N)
NEXT
SHOW()
}
EXEC()
}
FUNC SHOWMONTHS(M)
FOR N = M TO M + 2
MONTHSNAMES[N] = NEW QPUSHBUTTON(WIN1)
{
IF N%3 = 1
COL = 120
ROWNR = FLOOR(N/3)
IF ROWNR = 0
ROWNR = N/3
OK
IF N = 1
ROW = 40
ELSE
ROW = 40+ROWNR*180
OK
ELSE
COLNR = N%3
IF COLNR = 0
COLNR = 3
OK
ROWNR = FLOOR(N/3)
IF N%3 = 0
ROWNR = FLOOR(N/3)-1
OK
COL = 120 + (COLNR-1)*160
ROW = 40 + ROWNR*180
OK
SETGEOMETRY(COL,ROW,63,20)
MONTHSNAMES[N].SETTEXT(MONTHS[N])
}
NEXT
FUNC SHOWWEEKS(N)
FOR M = 1 TO 7
COL = M%7
IF COL = 0 COL = 7 OK
WEEKDAY[M] = NEW QPUSHBUTTON(WIN1)
{
COLNR = N % 3
IF COLNR = 0
COLNR = 3
OK
ROWNR = FLOOR(N/3)
IF N%3 = 0
ROWNR = FLOOR(N/3)-1
OK
COLBEGIN = 60 + (COLNR-1)*160
ROWBEGIN = 60 + (ROWNR)*180
SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN,25,20)
WEEKDAY[M].SETTEXT(WEEK[M])
}
NEXT
FUNC SHOWDAYS(IND)
ROWNR = FLOOR(IND/3)
IF IND%3 = 0
ROWNR = FLOOR(IND/3)-1
OK
ROWBEGIN = 60+ROWNR*180
FOR M = 1 TO 6
FOR N = 1 TO 7
COL = N%7
IF COL = 0 COL = 7 OK
ROW = M
BUTTON[N][M] = NEW QPUSHBUTTON(WIN1)
{
IF IND%3 = 1
COLBEGIN = 60
ELSEIF IND%3 = 2
COLBEGIN = 220
ELSE
COLBEGIN = 380
OK
SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN+ROW*20,25,20)
NR = (M-1)*7+N
IF NR <= 37
IF POS[IND][NR] != " "
BUTTON[N][M].SETTEXT(STRING(POS[IND][NR]))
OK
OK
}
NEXT
NEXT
|
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
| #Smalltalk | Smalltalk | Object subclass:'CallDemo'!
!CallDemo class methods!
strdup:arg
<cdecl: mustFree char* 'strdup' (char*) module:'libc'>
! !
Transcript showCR:( CallDemo strdup:'Hello' ) |
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
| #Stata | Stata | #include <stdlib.h>
#include "stplugin.h"
STDLL stata_call(int argc, char *argv[]) {
int i, j, n = strtol(argv[1], NULL, 0);
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
// Don't forget array indices are 1-based in Stata.
SF_mat_store(argv[0], i, j, 1.0/(double)(i+j-1));
}
}
return 0;
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Factor | Factor | foo |
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
| #Swift | Swift | let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums.reduce(0, +))
print(nums.reduce(1, *))
print(nums.reduce("", { $0 + String($1) })) |
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
| #Tailspin | Tailspin |
[1..5] -> \(@: $(1); $(2..last)... -> @: $@ + $; $@!\) -> '$;
' -> !OUT::write
[1..5] -> \(@: $(1); $(2..last)... -> @: $@ - $; $@!\) -> '$;
' -> !OUT::write
[1..5] -> \(@: $(1); $(2..last)... -> @: $@ * $; $@!\) -> '$;
' -> !OUT::write
|
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}
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))
Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}
Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))
End Function
Sub Main()
Dim empty(-1) As Integer
Dim list1 = {1, 2}
Dim list2 = {3, 4}
Dim list3 = {1776, 1789}
Dim list4 = {7, 12}
Dim list5 = {4, 14, 23}
Dim list6 = {0, 1}
Dim list7 = {1, 2, 3}
Dim list8 = {30}
Dim list9 = {500, 100}
For Each sequnceList As Integer()() In {
({list1, list2}),
({list2, list1}),
({list1, empty}),
({empty, list1}),
({list3, list4, list5, list6}),
({list7, list8, list9}),
({list7, empty, list9})
}
Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})")
Console.WriteLine($"{{{String.Join(", ", cart)}}}")
Next
End Sub
End Module |
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
| #K | K | catalan: {_{*/(x-i)%1+i:!y-1}[2*x;x+1]%x+1}
catalan'!:15
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
| #Perl | Perl | sub brace_expand {
my $input = shift;
my @stack = ([my $current = ['']]);
while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) {
if ($1 eq '{') {
push @stack, [$current = ['']];
}
elsif ($1 eq ',' && @stack > 1) {
push @{$stack[-1]}, ($current = ['']);
}
elsif ($1 eq '}' && @stack > 1) {
my $group = pop @stack;
$current = $stack[-1][-1];
# handle the case of brace pairs without commas:
@{$group->[0]} = map { "{$_}" } @{$group->[0]} if @$group == 1;
@$current = map {
my $c = $_;
map { map { $c . $_ } @$_ } @$group;
} @$current;
}
else { $_ .= $1 for @$current; }
}
# handle the case of missing closing braces:
while (@stack > 1) {
my $right = pop @{$stack[-1]};
my $sep;
if (@{$stack[-1]}) { $sep = ',' }
else { $sep = '{'; pop @stack }
$current = $stack[-1][-1];
@$current = map {
my $c = $_;
map { $c . $sep . $_ } @$right;
} @$current;
}
return @$current;
} |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #Go | Go | package main
import "fmt"
func sameDigits(n, b int) bool {
f := n % b
n /= b
for n > 0 {
if n%b != f {
return false
}
n /= b
}
return true
}
func isBrazilian(n int) bool {
if n < 7 {
return false
}
if n%2 == 0 && n >= 8 {
return true
}
for b := 2; b < n-1; b++ {
if sameDigits(n, b) {
return true
}
}
return false
}
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
kinds := []string{" ", " odd ", " prime "}
for _, kind := range kinds {
fmt.Printf("First 20%sBrazilian numbers:\n", kind)
c := 0
n := 7
for {
if isBrazilian(n) {
fmt.Printf("%d ", n)
c++
if c == 20 {
fmt.Println("\n")
break
}
}
switch kind {
case " ":
n++
case " odd ":
n += 2
case " prime ":
for {
n += 2
if isPrime(n) {
break
}
}
}
}
}
n := 7
for c := 0; c < 100000; n++ {
if isBrazilian(n) {
c++
}
}
fmt.Println("The 100,000th Brazilian number:", n-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
| #Fortran | Fortran |
MODULE DATEGNASH !Assorted vexations. Time and calendar games, with local flavourings added.
TYPE DateBag !Pack three parts into one.
INTEGER DAY,MONTH,YEAR !The usual suspects.
END TYPE DateBag !Simple enough.
CHARACTER*9 MONTHNAME(12),DAYNAME(0:6) !Re-interpretations.
PARAMETER (MONTHNAME = (/"January","February","March","April",
1 "May","June","July","August","September","October","November",
2 "December"/))
PARAMETER (DAYNAME = (/"Sunday","Monday","Tuesday","Wednesday",
1 "Thursday","Friday","Saturday"/)) !Index this array with DayNum mod 7.
CHARACTER*3 MTHNAME(12) !The standard abbreviations.
PARAMETER (MTHNAME = (/"JAN","FEB","MAR","APR","MAY","JUN",
1 "JUL","AUG","SEP","OCT","NOV","DEC"/))
INTEGER*4 JDAYSHIFT !INTEGER*2 just isn't enough.
PARAMETER (JDAYSHIFT = 2415020) !Thus shall 31/12/1899 give 0, a Sunday, via DAYNUM.
CONTAINS
INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank.
Concocted yet again by R.N.McLean (whom God preserve) December MM.
Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!
Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces.
Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.
Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.
Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone.
Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only.
Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!
Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.
CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back.
INTEGER L !The length of the bumf.
L = LEN(TEXT) !So, what is it?
1 IF (L.LE.0) GO TO 2 !Are we there yet?
IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also.
L = L - 1 !Step back one.
GO TO 1 !And try again.
2 LSTNB = L !The last non-blank, possibly zero.
RETURN !Unsafe to use LSTNB as a variable.
END FUNCTION LSTNB !Compilers can bungle it.
CHARACTER*2 FUNCTION I2FMT(N) !These are all the same.
INTEGER*4 N !But, the compiler doesn't offer generalisations.
IF (N.LT.0) THEN !Negative numbers cop a sign.
IF (N.LT.-9) THEN !But there's not much room left.
I2FMT = "-!" !So this means 'overflow'.
ELSE !Otherwise, room for one negative digit.
I2FMT = "-"//CHAR(ICHAR("0") - N) !Thus. Presume adjacent character codes, etc.
END IF !So much for negative numbers.
ELSE IF (N.LT.10) THEN !Single digit positive?
I2FMT = " " //CHAR(ICHAR("0") + N) !Yes. This.
ELSE IF (N.LT.100) THEN !Two digit positive?
I2FMT = CHAR(N/10 + ICHAR("0")) !Yes.
1 //CHAR(MOD(N,10) + ICHAR("0")) !These.
ELSE !Otherwise,
I2FMT = "+!" !Positive overflow.
END IF !So much for that.
END FUNCTION I2FMT !No WRITE and FORMAT unlimbering.
CHARACTER*8 FUNCTION I8FMT(N) !Oh for proper strings.
INTEGER*4 N
CHARACTER*8 HIC
WRITE (HIC,1) N
1 FORMAT (I8)
I8FMT = HIC
END FUNCTION I8FMT
SUBROUTINE SAY(OUT,TEXT) !Gutted version that maintains no file logging output, etc.
INTEGER OUT
CHARACTER*(*) TEXT
WRITE (6,1) TEXT(1:LSTNB(TEXT))
1 FORMAT (A)
END SUBROUTINE SAY
INTEGER*4 FUNCTION DAYNUM(YY,M,D) !Computes (JDayN - JDayShift), not JDayN.
C Conversion from a Gregorian calendar date to a Julian day number, JDayN.
C Valid for any Gregorian calendar date producing a Julian day number
C greater than zero, though remember that the Gregorian calendar
C was not used before y1582m10d15 and often, not after that either.
C thus in England (et al) when Wednesday 2'nd September 1752 (Julian style)
C was followed by Thursday the 14'th, occasioning the Eleven Day riots
C because creditors demanded a full month's payment instead of 19/30'ths.
C The zero of the Julian day number corresponds to the first of January
C 4713BC on the *Julian* calendar's naming scheme, as extended backwards
C with current usage into epochs when it did not exist: the proleptic Julian calendar.
c This function employs the naming scheme of the *Gregorian* calendar,
c and if extended backwards into epochs when it did not exist (thus the
c proleptic Gregorian calendar) it would compute a zero for y-4713m11d24 *if*
c it is supposed there was a year zero between 1BC and 1AD (as is convenient
c for modern mathematics and astronomers and their simple calculations), *but*
c 1BC immediately preceeds 1AD without any year zero in between (and is a leap year)
c thus the adjustment below so that the date is y-4714m11d24 or 4714BCm11d24,
c not that this name was in use at the time...
c Although the Julian calendar (introduced by himself in what we would call 45BC,
c which was what the Romans occasionally called 709AUC) was provoked by the
c "years of confusion" resulting from arbitrary application of the rules
c for the existing Roman calendar, other confusions remain unresolved,
c so precise dating remains uncertain despite apparently precise specifications
c (and much later, Dennis the Short chose wrongly for the birth of Christ)
c and the Roman practice of inclusive reckoning meant that every four years
c was interpreted as every third (by our exclusive reckoning) so that the
c leap years were not as we now interpret them. This was resolved by Augustus
c but exactly when (and what date name is assigned) and whose writings used
c which system at the time of writing is a matter of more confusion,
c and this has continued for centuries.
C Accordingly, although an algorithm may give a regular sequence of date names,
c that does not mean that those date names were used at the time even if the
c calendar existed then, because the interpretation of the algorithm varied.
c This in turn means that a date given as being on the Julian calendar
c prior to about 10AD is not as definite as it may appear and its alignment
c with the astronomical day number is uncertain even though the calculation
c is quite definite.
c
C Computationally, year 1 is preceded by year 0, in a smooth progression.
C But there was never a year zero despite what astronomers like to say,
C so the formula's year 0 corresponds to 1BC, year -1 to 2BC, and so on back.
C Thus y-4713 in this counting would be 4714BC on the Gregorian calendar,
C were it to have existed then which it didn't.
C To conform to the civil usage, the incoming YY, presumed a proper BC (negative)
C and AD (positive) year is converted into the computational counting sequence, Y,
C and used in the formula. If a YY = 0 is (improperly) offered, it will manifest
C as 1AD. Thus YY = -4714 will lead to calculations with Y = -4713.
C Thus, 1BC is a leap year on the proleptic Gregorian calendar.
C For their convenience, astronomers decreed that a day starts at noon, so that
C in Europe, observations through the night all have the same day number.
C The current Western civil calendar however has the day starting just after midnight
C and that day's number lasts until the following midnight.
C
C There is no constraint on the values of D, which is just added as it stands.
C This means that if D = 0, the daynumber will be that of the last day of the
C previous month. Likewise, M = 0 or M = 13 will wrap around so that Y,M + 1,0
C will give the last day of month M (whatever its length) as one day before
C the first day of the next month.
C
C Example: Y = 1970, M = 1, D = 1; JDAYN = 2440588, a Thursday but MOD(2440588,7) = 3.
C and with the adjustment JDAYSHIFT, DAYNUM = 25568; mod 7 = 4 and DAYNAME(4) = "Thursday".
C The Julian Day number 2440588.0 is for NOON that Thursday, 2440588.5 is twelve hours later.
C And Julian Day number 2440587.625 is for three a.m. Thursday.
C
C DAYNUM and MUNYAD are the infamous routines of H. F. Fliegel and T.C. van Flandern,
C presented in Communications of the ACM, Vol. 11, No. 10 (October, 1968).
Carefully typed in again by R.N.McLean (whom God preserve) December XXMMIIX.
C Though I remain puzzled as to why they used I,J,K for Y,M,D,
C given that the variables were named in the INTEGER statement anyway.
INTEGER*4 JDAYN !Without rebasing, this won't fit in INTEGER*2.
INTEGER YY,Y,M,MM,D !NB! Full year number, so 1970, not 70.
Caution: integer division in Fortran does not produce fractional results.
C The fractional part is discarded so that 4/3 gives 1 and -4/3 gives -1.
C Thus 4/3 might be Trunc(4/3) or 4 div 3 in other languages. Beware of negative numbers!
Y = YY !I can fiddle this copy without damaging the original's value.
IF (Y.LT.1) Y = Y + 1 !Thus YY = -2=2BC, -1=1BC, +1=1AD, ... becomes Y = -1, 0, 1, ...
MM = (M - 14)/12 !Calculate once. Note that this is integer division, truncating.
JDAYN = D - 32075 !This is the proper astronomer's Julian Day Number.
a + 1461*(Y + 4800 + MM)/4
b + 367*(M - 2 - MM*12)/12
c - 3*((Y + 4900 + MM)/100)/4
DAYNUM = JDAYN - JDAYSHIFT !Thus, *NOT* the actual *Julian* Day Number.
END FUNCTION DAYNUM !But one such that Mod(n,7) gives day names.
Could compute the day of the year somewhat as follows...
c DN:=D + (61*Month + (Month div 8)) div 2 - 30
c + if Month > 2 then FebLength - 30 else 0;
TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM) !Oh for palindromic programming!
Conversion from a Julian day number to a Gregorian calendar date. See JDAYN/DAYNUM.
INTEGER*4 DAYNUM,JDAYN !Without rebasing, this won't fit in INTEGER*2.
INTEGER Y,M,D,L,N !Y will be a full year number: 1950 not 50.
JDAYN = DAYNUM + JDAYSHIFT !Revert to a proper Julian day number.
L = JDAYN + 68569 !Further machinations of H. F. Fliegel and T.C. van Flandern.
N = 4*L/146097
L = L - (146097*N + 3)/4
Y = 4000*(L + 1)/1461001
L = L - 1461*Y/4 + 31
M = 80*L/2447
D = L - 2447*M/80
L = M/11
M = M + 2 - 12*L
Y = 100*(N - 49) + Y + L
IF (Y.LT.1) Y = Y - 1 !The other side of conformity to BC/AD, as in DAYNUM.
MUNYAD%YEAR = Y !Now place for the world to see.
MUNYAD%MONTH = M
MUNYAD%DAY = D
END FUNCTION MUNYAD !A year has 365.2421988 days...
INTEGER FUNCTION PMOD(N,M) !Remainder, mod M; always positive even if N is negative.
c For date calculations, the MOD function is expected to yield positive remainders,
c in line with the idea that MOD(a,b) = MOD(a ± b,b) as is involved in shifting the zero
c of the daynumber count by a multiple of seven when considering the day of the week.
c For this reason, the zero day was chosen to be 31/12/1899, a Sunday, so that all
c day numbers would be positive. But, there was generation at Reefton in 1886.
c For some computers, the positive interpretation is implemented, for others, not.
c In the case MOD(N,M) = N - Truncate(N/M)*M, MOD(-6,7) = -6 even though MOD(1,7) = 1.
INTEGER N,M !The numbers. M presumed positive.
PMOD = MOD(MOD(N,M) + M,M) !Double do does de deed.
END FUNCTION PMOD !Simple enough.
SUBROUTINE CALENDAR(Y1,Y2,COLUMNS) !Print a calendar, with holiday annotations.
Careful with the MOD function. MOD(-6,7) may be negative on some systems, positive on others. Thus, PMOD.
INTEGER Y1,Y2,YEAR !Ah yes. Year stuff.
INTEGER M,M1,M2,MONTH !And within each year are the months.
INTEGER*4 DN1,DN2,DN,D !But days are handled via day numbers.
INTEGER W,G !Layout: width and gap.
INTEGER L,LINE !Vertical layout.
INTEGER COL,COLUMNS,COLWIDTH !Horizontal layout.
INTEGER CODE !Days are not all alike.
CHARACTER*200 STRIPE(6),SPECIAL(6),MLINE,DLINE !Scratchpads.
IF (Y1.LE.0) CALL SAY(MSG,"Despite the insinuations of "
1 //"astronomers seduced by the ease of their arithmetic, "
2 //"there is no year zero. 1AD is preceded by 1BC, "
3 //"corresponding to year -1, 2BC to year -2, etc.")
IF (Y1.LT.1582) CALL SAY(MSG,"This Gregorian calendar"
1 //" scheme did not exist prior to 1582.")
c COLUMNS = 4 !Number of months across the page.
c W = 4 !Width of a day's field.
c G = 3 !Added gap between month columns.
W = 3 !Abandon the annotation of the day's class, so just a space and two digits.
G = 1 !Set the gap to one.
COLWIDTH = 7*W + G !Seven days to a week, plus a gap.
Y:DO YEAR = Y1,Y2 !Step through the years.
CALL SAY(MSG,"") !Space out between each year's schedule.
IF (YEAR.EQ.0) THEN !This year number is improper.
CALL SAY(MSG,"There is no year zero.") !Declare correctness.
CYCLE Y !Skip this year.
END IF !Otherwise, no evasions.
MLINE = "" !Prepare a field..
L = (COLUMNS*COLWIDTH - G - 8)/2 !Find the centre.
IF (YEAR.GT.0) THEN !Ordinary Anno Domine years?
MLINE(L:) = I8FMT(YEAR) !Yes. Place the year number.
ELSE !Otherwise, we're in BC.
MLINE(L - 1:) = I8FMT(-YEAR)//"BC" !There is no year zero.
END IF !So much for year games.
CALL SAY(MSG,MLINE) !Splot the year.
DO MONTH = 1,12,COLUMNS !Step through the months of this YEAR.
M1 = MONTH !The first of this lot.
M2 = MIN(12,M1 + COLUMNS - 1) !The last.
MLINE = "" !Scrub the month names.
DLINE = "" !Wipe the day names in case COLUMNS does not divide 12.
STRIPE = "" !Scrub the day table.
SPECIAL = "" !And the associated special day remarks.
c L0 = W - 1 !Locate the first day number's first column.
L0 = 1 !Cram: no space in front of the Sunday day-of-the-month.
DO M = M1,M2 !Work through the months.
L = (COLWIDTH - G - LSTNB(MONTHNAME(M)))/2 - 1 !Centre the month name.
MLINE(L0 + L:) = MONTHNAME(M) !Splot.
DO D = 0,6 !Prepare this month's day name heading.
L = L0 + (3 - W) + D*W !Locate its first column.
DLINE(L:L + 2) = DAYNAME(D)(1:W - 1) !Squish.
END DO !On to the next day.
DN1 = DAYNUM(YEAR,M,1) !Day number of the first day of the month.
DN2 = DAYNUM(YEAR,M + 1,0)!Thus the last, without annoyance.
COL = MOD(PMOD(DN1,7) + 7,7) !What day of the week is the first day?
LINE = 1 !Whichever it is, it is on the first line.
D = 1 !Day of the month, not number of the day.
DO DN = DN1,DN2 !Step through the day numbers of this month.
L = L0 + COL*W !Finger the starting column.
STRIPE(LINE)(L:L + 1) = I2FMT(D) !Place the two-digit day number.
D = D + 1 !Advance to the next day of the current month
COL = COL + 1 !So, one more day along in the week.
IF (COL.GT.6) THEN !A fresh week is needed?
LINE = LINE + 1 !Yes.
COL = 0 !Start the new week.
END IF !So much for the end of a week.
END DO !On to the next day of this month.
L0 = L0 + 7*W + G !Locate the start column of the next month's column.
END DO !On to the next month in this layer.
CALL SAY(MSG,MLINE) !Name the months.
C CALL SAY(MSG,"") !Set off.
CALL SAY(MSG,DLINE) !Give the day name headings.
DO LINE = 1,6 !Now roll the day number table.
IF (STRIPE(LINE).NE."") THEN !Perhaps there was no use of the sixth line.
CALL SAY(MSG,STRIPE(LINE)) !Ah well. Show the day numbers.
END IF !So much for that week line.
END DO !On to the next week line.
END DO !On to the next batch of months of the YEAR.
END DO Y !On to the next YEAR.
CALL SAY(MSG,"") !Take a breath.
END SUBROUTINE CALENDAR !Enough of this.
END MODULE DATEGNASH !An ad-hoc assemblage.
PROGRAM SHOW1968 !Put it to the test.
USE DATEGNASH
INTEGER NCOL
DO NCOL = 1,6
CALL CALENDAR(1969,1969,NCOL)
END DO
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.
| #J | J | brtr=:4 :0
seed=. ?x
clip=. 0 >. (<:x) <."1 ]
near=. [: clip +"1/&(,"0/~i:1)
p=.i.0 2
mask=. 1 (<"1 near seed)} x$0
field=.1 (<seed)} x$0
for.i.y do.
p=. clip (p +"1 <:?3$~$p),?x
b=.(<"1 p) { mask
fix=. b#p
if.#fix do. NB. if. works around j602 bug: 0(0#a:)}i.0 0
p=. (-.b)# p
mask=. 1 (<"1 near fix)} mask
field=. 1 (<"1 fix)} field
end.
end.
field
) |
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
| #D | D | void main() {
import std.stdio, std.random, std.string, std.algorithm,
std.range, std.ascii;
immutable hidden = "123456789"d.randomCover.take(4).array;
while (true) {
"Next guess: ".write;
const d = readln.strip.array.sort().release;
if (d.count == 4 && d.all!isDigit && d.uniq.count == 4) {
immutable bulls = d.zip(hidden).count!q{ a[0] == a[1] },
cows = d.count!(g => hidden.canFind(g)) - bulls;
if (bulls == 4)
return " You guessed it!".writeln;
writefln("bulls %d, cows %d", bulls, cows);
}
" Bad guess! (4 unique digits, 1-9)".writeln;
}
} |
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
| #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
class MyTransform {
private :
int shift ;
public :
MyTransform( int s ) : shift( s ) { }
char operator( )( char c ) {
if ( isspace( c ) )
return ' ' ;
else {
static std::string letters( "abcdefghijklmnopqrstuvwxyz" ) ;
std::string::size_type found = letters.find(tolower( c )) ;
int shiftedpos = ( static_cast<int>( found ) + shift ) % 26 ;
if ( shiftedpos < 0 ) //in case of decryption possibly
shiftedpos = 26 + shiftedpos ;
char shifted = letters[shiftedpos] ;
return shifted ;
}
}
} ;
int main( ) {
std::string input ;
std::cout << "Which text is to be encrypted ?\n" ;
getline( std::cin , input ) ;
std::cout << "shift ?\n" ;
int myshift = 0 ;
std::cin >> myshift ;
std::cout << "Before encryption:\n" << input << std::endl ;
std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
MyTransform( myshift ) ) ;
std::cout << "encrypted:\n" ;
std::cout << input << std::endl ;
myshift *= -1 ; //decrypting again
std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
MyTransform( myshift ) ) ;
std::cout << "Decrypted again:\n" ;
std::cout << input << std::endl ;
return 0 ;
} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 1+Fold[1.+#1/#2&,1,Range[10,2,-1]] |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #min | min | (:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota
(iota 'succ '* map-reduce) :factorial
20 iota (factorial 1 swap /) '+ map-reduce print |
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)
| #R | R | bullsAndCowsPlayer <- function()
{
guesses <- 1234:9876
#The next line is terrible code, but it's the most R way to convert a set of 4-digit numbers to their 4 digits.
guessDigits <- t(sapply(strsplit(as.character(guesses), ""), as.integer))
validGuesses <- guessDigits[apply(guessDigits, 1, function(x) length(unique(x)) == 4 && all(x != 0)), ]
repeat
{
remainingCasesCount <- nrow(validGuesses)
cat("Possibilities remaining:", remainingCasesCount)#Not required, but excellent when debugging.
guess <- validGuesses[sample(remainingCasesCount, 1), ]
guessAsOneNumber <- as.integer(paste(guess, collapse = ""))
bulls <- as.integer(readline(paste0("My guess is ", guessAsOneNumber, ". Bull score? [0-4] ")))
if(bulls == 4) return(paste0("Your number is ", guessAsOneNumber, ". I win!"))
cows <- as.integer(readline("Cow score? [0-4] "))
#If our guess scores y bulls, then only numbers containing exactly y digits with the same value and position (y "pseudoBulls") as in our guess can be correct.
#Accounting for the positions of cows not being fixed, the same argument also applies for them.
#The following lines make us only keep the numbers that have the right pseudoBulls and "pseudoCows" scores, albeit without the need for a pseudoCows function.
#We also use pseudoBulls != 4 to remove our most recent guess, because we know that it cannot be correct.
#Finally, the drop=FALSE flag is needed to stop R converting validGuesses to a vector when there is only one guess left.
pseudoBulls <- function(x) sum(x == guess)
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE]
if(nrow(validGuesses) == 0) return("Error: Scoring problem?")
}
}
bullsAndCowsPlayer() |
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.
| #Ruby | Ruby | # loadup.rb - run UPPERCASE RUBY program
class Object
alias lowercase_method_missing method_missing
# Allow UPPERCASE method calls.
def method_missing(sym, *args, &block)
str = sym.to_s
if str == (down = str.downcase)
lowercase_method_missing sym, *args, &block
else
send down, *args, &block
end
end
# RESCUE an exception without the 'rescue' keyword.
def RESCUE(_BEGIN, _CLASS, _RESCUE)
begin _BEGIN.CALL
rescue _CLASS
_RESCUE.CALL; end
end
end
_PROGRAM = ARGV.SHIFT
_PROGRAM || ABORT("USAGE: #{$0} PROGRAM.RB ARGS...")
LOAD($0 = _PROGRAM) |
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
| #Swift | Swift | import Foundation
let hello = "Hello, World!"
let fromC = strdup(hello)
let backToSwiftString = String.fromCString(fromC) |
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
| #Tcl | Tcl | package require critcl
critcl::code {
#include <math.h>
}
critcl::cproc tcl::mathfunc::ilogb {double value} int {
return ilogb(value);
}
package provide ilogb 1.0 |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Forth | Forth | a-function \ requiring no arguments
a-function \ with a fixed number of arguents
a-function \ having optional arguments
a-function \ having a variable number of arguments
a-function \ having such named arguments as we have in Forth
' a-function var ! \ using a function in a first-class context (here: storing it in a variable)
a-function \ in which we obtain a function's return value
\ forth lacks 'statement contenxt'
\ forth doesn't distinguish between built-in and user-defined functions
\ forth doesn't distinguish between functions and subroutines
\ forth doesn't care about by-value or by-reference
\ partial application is achieved by creating functions and manipulating stacks
: curried 0 a-function ;
: only-want-third-argument 1 2 rot a-function ;
\ Realistic example:
: move ( delta-x delta-y -- )
y +! x +! ;
: down ( n -- ) 0 swap move ;
: up ( n -- ) negate down ;
: right ( n -- ) 0 move ;
: left ( n -- ) negate right ; |
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
| #Tcl | Tcl | proc fold {lambda zero list} {
set accumulator $zero
foreach item $list {
set accumulator [apply $lambda $accumulator $item]
}
return $accumulator
} |
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
| #uBasic.2F4tH | uBasic/4tH | Push 5, 4, 3, 2, 1: s = Used() - 1
For x = 0 To s: @(x) = Pop(): Next
Print "Sum is : "; FUNC(_reduce(0, s, _add))
Print "Difference is : "; FUNC(_reduce(0, s, _subtract))
Print "Product is : "; FUNC(_reduce(0, s, _multiply))
Print "Maximum is : "; FUNC(_reduce(0, s, _max))
Print "Minimum is : "; FUNC(_reduce(0, s, _min))
Print "No op is : "; FUNC(_reduce(0, s, _noop))
End
_reduce
Param (3)
Local (2)
If (Line(c@) = 0) + ((b@ - a@) < 1) Then Return (0)
d@ = @(a@)
For e@ = a@ + 1 To b@
d@ = FUNC(c@ (d@, @(e@)))
Next
Return (d@)
_add Param (2) : Return (a@ + b@)
_subtract Param (2) : Return (a@ - b@)
_multiply Param (2) : Return (a@ * b@)
_max Param (2) : Return (Max(a@, b@))
_min Param (2) : Return (Min(a@, b@)) |
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}
| #Wren | Wren | import "/seq" for Lst
var prod2 = Fn.new { |l1, l2|
var res = []
for (e1 in l1) {
for (e2 in l2) res.add([e1, e2])
}
return res
}
var prodN = Fn.new { |ll|
if (ll.count < 2) Fiber.abort("There must be at least two lists.")
var p2 = prod2.call(ll[0], ll[1])
return ll.skip(2).reduce(p2) { |acc, l| prod2.call(acc, l) }.map { |l| Lst.flatten(l) }.toList
}
var printProdN = Fn.new { |ll|
System.print("%(ll.join(" x ")) = ")
System.write("[\n ")
System.print(prodN.call(ll).join("\n "))
System.print("]\n")
}
System.print("[1, 2] x [3, 4] = %(prodN.call([ [1, 2], [3, 4] ]))")
System.print("[3, 4] x [1, 2] = %(prodN.call([ [3, 4], [1, 2] ]))")
System.print("[1, 2] x [] = %(prodN.call([ [1, 2], [] ]))")
System.print("[] x [1, 2] = %(prodN.call([ [], [1, 2] ]))")
System.print("[1, a] x [2, b] = %(prodN.call([ [1, "a"], [2, "b"] ]))")
System.print()
printProdN.call([ [1776, 1789], [7, 12], [4, 14, 23], [0, 1] ])
printProdN.call([ [1, 2, 3], [30], [500, 100] ])
printProdN.call([ [1, 2, 3], [], [500, 100] ])
printProdN.call([ [1, 2, 3], [30], ["a", "b"] ]) |
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
| #Kotlin | Kotlin | abstract class Catalan {
abstract operator fun invoke(n: Int) : Double
protected val m = mutableMapOf(0 to 1.0)
}
object CatalanI : Catalan() {
override fun invoke(n: Int): Double {
if (n !in m)
m[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
return m[n]!!
}
private fun fact(n: Int): Double {
if (n in facts)
return facts[n]!!
val f = n * fact(n -1)
facts[n] = f
return f
}
private val facts = mutableMapOf(0 to 1.0, 1 to 1.0, 2 to 2.0)
}
object CatalanR1 : Catalan() {
override fun invoke(n: Int): Double {
if (n in m)
return m[n]!!
var sum = 0.0
for (i in 0..n - 1)
sum += invoke(i) * invoke(n - 1 - i)
sum = Math.round(sum).toDouble()
m[n] = sum
return sum
}
}
object CatalanR2 : Catalan() {
override fun invoke(n: Int): Double {
if (n !in m)
m[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * invoke(n - 1)).toDouble()
return m[n]!!
}
}
fun main(args: Array<String>) {
val c = arrayOf(CatalanI, CatalanR1, CatalanR2)
for(i in 0..15) {
c.forEach { print("%9d".format(it(i).toLong())) }
println()
}
} |
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
| #Phix | Phix | -- demo\rosetta\Brace_expansion.exw
with javascript_semantics
function pair(sequence stems, sequence brest)
sequence res = {}
for i=1 to length(stems) do
for j=1 to length(brest) do
res = append(res,stems[i]&brest[j])
end for
end for
return res
end function
function brarse(string s)
integer idx = 1
while idx<=length(s) do
integer ch = s[idx]
if ch='{' then
sequence alts = {idx}
idx += 1
integer l0 = idx
bool nest = false, bl0 = false
integer level = 1
while idx<=length(s) do
switch s[idx] do
case '{': level += 1
nest = true
case '}': level -= 1
bl0 = (level=0)
case ',': if level=1 then
alts = append(alts,idx)
end if
case '\\': idx += 1
end switch
if bl0 then exit end if
idx += 1
end while
if length(alts)>1 and level=0 then
alts &= idx
sequence stems = {}
string stem = s[1..alts[1]-1]
for i=2 to length(alts) do
string rest = s[alts[i-1]+1..alts[i]-1]
if nest then
sequence inners = brarse(rest)
for j=1 to length(inners) do
stems = append(stems,stem&inners[j])
end for
else
stems = append(stems,stem&rest)
end if
end for
return pair(stems,brarse(s[idx+1..$]))
elsif nest then
return pair({s[1..l0-1]},brarse(s[l0..$]))
end if
end if
idx += 1
end while
return {s}
end function
-- (since ? and pp() add their own backslash escapes:)
procedure edump(sequence x)
for i=1 to length(x) do
printf(1,"%s\n",{x[i]})
end for
end procedure
edump(brarse("~/{Downloads,Pictures}/*.{jpg,gif,png}"))
edump(brarse("It{{em,alic}iz,erat}e{d,}, please."))
edump(brarse(`{,{,gotta have{ ,\, again\, }}more }cowbell!`))
edump(brarse(`{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}`))
|
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #Groovy | Groovy | import org.codehaus.groovy.GroovyBugError
class Brazilian {
private static final List<Integer> primeList = new ArrayList<>(Arrays.asList(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
))
static boolean isPrime(int n) {
if (n < 2) {
return false
}
for (Integer prime : primeList) {
if (n == prime) {
return true
}
if (n % prime == 0) {
return false
}
if (prime * prime > n) {
return true
}
}
BigInteger bi = BigInteger.valueOf(n)
return bi.isProbablePrime(10)
}
private static boolean sameDigits(int n, int b) {
int f = n % b
n = n.intdiv(b)
while (n > 0) {
if (n % b != f) {
return false
}
n = n.intdiv(b)
}
return true
}
private static boolean isBrazilian(int n) {
if (n < 7) return false
if (n % 2 == 0) return true
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true
}
}
return false
}
static void main(String[] args) {
for (String kind : Arrays.asList("", "odd ", "prime ")) {
boolean quiet = false
int bigLim = 99_999
int limit = 20
System.out.printf("First %d %sBrazilian numbers:\n", limit, kind)
int c = 0
int n = 7
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) System.out.printf("%d ", n)
if (++c == limit) {
System.out.println("\n")
quiet = true
}
}
if (quiet && "" != kind) continue
switch (kind) {
case "":
n++
break
case "odd ":
n += 2
break
case "prime ":
while (true) {
n += 2
if (isPrime(n)) break
}
break
default:
throw new GroovyBugError("Oops")
}
}
if ("" == kind) {
System.out.printf("The %dth Brazilian number is: %d\n\n", bigLim + 1, n)
}
}
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #FreeBASIC | FreeBASIC | ' version 17-02-2016
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' For older versions they have to be defined.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function WD(m As Integer, d As Integer, y As Integer) As Integer
' Zellerish
' 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday
' 4 = Thursday, 5 = Friday, 6 = Saturday
If m < 3 Then ' if m = 1 or m = 2 then
m += 12
y -= 1
End If
Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7
End Function
Function LEAPYEAR(y As Integer) As Integer
If (y Mod 4) <> 0 Then Return FALSE
If (y Mod 100) = 0 AndAlso (y Mod 400) <> 0 Then Return FALSE
Return TRUE
End Function
' ------=< main >=------
Dim As String wdn = "Mo Tu We Th Fr Sa Su" ' weekday names
Dim As String mo(1 To 12) => {"January", "February", "March", "April", _
"May", "June", "July", "August", "September", _
"October", "November", "December"}
Dim As String tmp1, tmp2, d(1 To 12)
Dim As UInteger ml(1 To 12) => {31,28,31,30,31,30,31,31,30,31,30,31}
Dim As UInteger i, i1, j, k, y = 1969
Dim As UInteger m_row = 6
Do
While InKey <> "" : Wend ' clear keyboard buffer
Print : Print " For wich year do want a calendar"
Print " Year must be greater then 1752"
Input " Input year (enter = 1969)";tmp1
If tmp1 = "" Then Exit Do
i = Val(tmp1)
If i < 1752 Then
Print
Print " Can only make a calendar for a year after 1752"
Beep : Sleep 5000, 1 : Print
Else
y = i : Exit Do
End If
Loop
Cls
Do
While InKey <> "" : Wend ' clear keyboard buffer
Print : Print " Make device choice"
Print " 132 characters Line printer, 6x2 months (Enter or 1)"
Print " 80x43 display, 3x4 months (2)"
Do
tmp1 = InKey
If tmp1 = Chr(13) Or tmp1 = "1" Then Exit Do, Do
If tmp1 = "2" Then
m_row = 3
Exit Do, Do
End If
Loop Until tmp1 <> ""
Print : Print " Enter, 1 or 2 only"
Beep : Sleep 5000, 1 : Print
Loop
Cls
Dim As UInteger char_line = m_row * 22 - 1
If LEAPYEAR(y) = TRUE Then ml(2) = 29
tmp1 = ""
For i = 1 To 31
tmp1 = tmp1 + Right((" " + Str(i)), 3)
Next
For i = 1 To 12
tmp2 = ""
j = WD(i,1, y)
If j = 0 Then j = 7
j = j - 1
tmp2 = Space(j * 3) + Left(tmp1, ml(i) * 3) + Space(21)
d(i) = tmp2
Next
Print
tmp1 = Str(y)
Print Space((char_line + (char_line And 1) - Len(tmp1)) \ 2); tmp1
Print
tmp2 = " " ' make the weekday names line
For i = 1 To m_row
tmp2 = tmp2 + wdn
If i < m_row Then tmp2 = tmp2 + " "
Next
For i = 1 To 12 Step m_row
tmp1 = ""
For j = i To i + m_row -2 ' make the month names line
tmp1 = tmp1 + Left(Space((22 - Len(mo(j))) \ 2) + mo(j) + Space(21), 22)
Next
tmp1 = tmp1 + Space((22 - Len(mo(i + m_row -1))) \ 2) + mo(i + m_row -1)
Print tmp1
Print tmp2
For j = 1 To 85 Step 21
For k = i To i + m_row -2
Print Mid(d(k), j ,21); " ";
Next
Print Mid(d(i + m_row -1), j ,21)
Next
Print
Next
' empty keyboard buffer
While InKey <> "" : Wend
'Print : Print "hit any key to end program
Sleep
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.
| #Java | Java | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.JFrame;
public class BrownianTree extends JFrame implements Runnable {
BufferedImage I;
private List<Particle> particles;
static Random rand = new Random();
public BrownianTree() {
super("Brownian Tree");
setBounds(100, 100, 400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
I.setRGB(I.getWidth() / 2, I.getHeight() / 2, 0xff00);
particles = new LinkedList<Particle>();
}
@Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
public void run() {
for (int i = 0; i < 20000; i++) {
particles.add(new Particle());
}
while (!particles.isEmpty()) {
for (Iterator<Particle> it = particles.iterator(); it.hasNext();) {
if (it.next().move()) {
it.remove();
}
}
repaint();
}
}
public static void main(String[] args) {
BrownianTree b = new BrownianTree();
b.setVisible(true);
new Thread(b).start();
}
private class Particle {
private int x, y;
private Particle() {
x = rand.nextInt(I.getWidth());
y = rand.nextInt(I.getHeight());
}
/* returns true if either out of bounds or collided with tree */
private boolean move() {
int dx = rand.nextInt(3) - 1;
int dy = rand.nextInt(3) - 1;
if ((x + dx < 0) || (y + dy < 0)
|| (y + dy >= I.getHeight()) || (x + dx >= I.getWidth())) {
return true;
}
x += dx;
y += dy;
if ((I.getRGB(x, y) & 0xff00) == 0xff00) {
I.setRGB(x - dx, y - dy, 0xff00);
return true;
}
return false;
}
}
} |
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
| #Delphi | Delphi | def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]
/** Choose a random number to be guessed. */
def pick4(entropy) {
def digits := [1,2,3,4,5,6,7,8,9].diverge()
# Partial Fisher-Yates shuffle
for i in 0..!4 {
def other := entropy.nextInt(digits.size() - i) + i
def t := digits[other]
digits[other] := digits[i]
digits[i] := t
}
return digits(0, 4)
}
/** Compute the score of a guess. */
def scoreGuess(actual :Number, guess :Number) {
var bulls := 0
var cows := 0
for i => digit in guess {
if (digit == actual[i]) {
bulls += 1
} else if (actual.indexOf1(digit) != -1) {
cows += 1
}
}
return [bulls, cows]
}
/** Parse a guess string into a list of digits (Number). */
def parseGuess(guessString, fail) :Number {
if (guessString.size() != 4) {
return fail(`I need four digits, not ${guessString.size()} digits.`)
} else {
var digits := []
for c in guessString {
if (('1'..'9')(c)) {
digits with= c - '0'
} else {
return fail(`I need a digit from 1 to 9, not "$c".`)
}
}
return digits
}
}
/** The game loop: asking for guesses and reporting scores and win conditions.
The return value is null or a broken reference if there was a problem. */
def bullsAndCows(askUserForGuess, tellUser, entropy) {
def actual := pick4(entropy)
def gameTurn() {
return when (def guessString := askUserForGuess <- ()) -> {
escape tellAndContinue {
def guess := parseGuess(guessString, tellAndContinue)
def [bulls, cows] := scoreGuess(actual, guess)
if (bulls == 4) {
tellUser <- (`You got it! The number is $actual!`)
null
} else {
tellAndContinue(`Your score for $guessString is $bulls bulls and $cows cows.`)
}
} catch message {
# The parser or scorer has something to say, and the game continues afterward
when (tellUser <- (message)) -> {
gameTurn()
}
}
} catch p {
# Unexpected problem of some sort
tellUser <- ("Sorry, game crashed.")
throw(p)
}
}
return gameTurn()
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Clojure | Clojure | (defn encrypt-character [offset c]
(if (Character/isLetter c)
(let [v (int c)
base (if (>= v (int \a))
(int \a)
(int \A))
offset (mod offset 26)] ;works with negative offsets too!
(char (+ (mod (+ (- v base) offset) 26)
base)))
c))
(defn encrypt [offset text]
(apply str (map #(encrypt-character offset %) text)))
(defn decrypt [offset text]
(encrypt (- 26 offset) text))
(let [text "The Quick Brown Fox Jumps Over The Lazy Dog."
enc (encrypt -1 text)]
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 П1 0 П2 1 П2 1 П3
ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3
ИП0 x#0 25 L0 08 ИП3 С/П |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Modula-2 | Modula-2 | MODULE CalculateE;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
CONST EPSILON = 1.0E-15;
PROCEDURE abs(n : REAL) : REAL;
BEGIN
IF n < 0.0 THEN
RETURN -n
END;
RETURN n
END abs;
VAR
buf : ARRAY[0..31] OF CHAR;
fact,n : LONGCARD;
e,e0 : LONGREAL;
BEGIN
fact := 1;
e := 2.0;
n := 2;
REPEAT
e0 := e;
fact := fact * n;
INC(n);
e := e + 1.0 / LFLOAT(fact)
UNTIL abs(e - e0) < EPSILON;
WriteString("e = ");
RealToStr(e, buf);
WriteString(buf);
WriteLn;
ReadChar
END CalculateE. |
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)
| #Racket | Racket | #lang racket/base
(require racket/string
racket/list)
(define (permutations-getall items size)
(if (zero? size)
'(())
(for/list ([tail (in-list (permutations-getall items (- size 1)))]
#:when #t
[i (in-list items)]
#:unless (member i tail))
(cons i tail))))
(define digits (list 1 2 3 4 5 6 7 8 9))
(define size 4)
(define all-choices (shuffle (permutations-getall digits size)))
(define (listnum->string list)
(apply string-append (map number->string list))) |
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.
| #Seed7 | Seed7 | $ INCLUDE "SEED7_05.S7I";
INCLUDE "TIME.S7I";
CONST FUNC STRING: CENTER (IN STRING: STRI, IN INTEGER: LENGTH) IS
RETURN ("" LPAD (LENGTH - LENGTH(STRI)) DIV 2 <& STRI) RPAD LENGTH;
CONST PROC: PRINTCALENDAR (IN INTEGER: YEAR, IN INTEGER: COLS) IS FUNC
LOCAL
VAR TIME: DATE IS TIME.VALUE;
VAR INTEGER: DAYOFWEEK IS 0;
CONST ARRAY STRING: MONTHNAMES IS [] ("JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER");
VAR ARRAY ARRAY STRING: MONTHTABLE IS 12 TIMES 9 TIMES "";
VAR STRING: STR IS "";
VAR INTEGER: MONTH IS 0;
VAR INTEGER: POSITION IS 0;
VAR INTEGER: ROW IS 0;
VAR INTEGER: COLUMN IS 0;
VAR INTEGER: LINE IS 0;
BEGIN
FOR MONTH RANGE 1 TO 12 DO
MONTHTABLE[MONTH][1] := " " & CENTER(UPPER(MONTHNAMES[MONTH]), 20);
MONTHTABLE[MONTH][2] := UPPER(" MO TU WE TH FR SA SU");
DATE := DATE(YEAR, MONTH, 1);
DAYOFWEEK := DAYOFWEEK(DATE);
FOR POSITION RANGE 1 TO 43 DO
IF POSITION >= DAYOFWEEK AND POSITION - DAYOFWEEK < DAYSINMONTH(DATE.YEAR, DATE.MONTH) THEN
STR := SUCC(POSITION - DAYOFWEEK) LPAD 3;
ELSE
STR := "" LPAD 3;
END IF;
MONTHTABLE[MONTH][3 + PRED(POSITION) DIV 7] &:= STR;
END FOR;
END FOR;
WRITELN(CENTER(UPPER("[SNOOPY PICTURE]"), COLS * 24 + 4));
WRITELN(CENTER(STR(YEAR),COLS * 24 + 4));
WRITELN;
FOR ROW RANGE 1 TO SUCC(11 DIV COLS) DO
FOR LINE RANGE 1 TO 9 DO
FOR COLUMN RANGE 1 TO COLS DO
IF PRED(ROW) * COLS + COLUMN <= 12 THEN
WRITE(" " & MONTHTABLE[PRED(ROW) * COLS + COLUMN][LINE]);
END IF;
END FOR;
WRITELN;
END FOR;
END FOR;
END FUNC;
CONST PROC: MAIN IS FUNC
BEGIN
PRINTCALENDAR(1969, 3);
END FUNC; |
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
| #TXR | TXR | This is the TXR Lisp interactive listener of TXR 176.
Use the :quit command or type Ctrl-D on empty line to exit.
1> (with-dyn-lib nil
(deffi strdup "strdup" str-d (str)))
#:lib-0177
2> (strdup "hello, world!")
"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
| #Wren | Wren | /* call_foreign_language_function.wren */
class C {
foreign static strdup(s)
}
var s = "Hello World!"
System.print(C.strdup(s)) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.