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/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
| #Forth | Forth | : catalan ( n -- ) 1 swap 1+ 1 do dup cr . i 2* 1- 2* i 1+ */ loop drop ; |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #VBA | VBA |
Option Explicit
Sub Method_1(Optional myStr As String)
Dim strTemp As String
If myStr <> "" Then strTemp = myStr
Debug.Print strTemp
End Sub
Static Sub Method_2(Optional myStr As String)
Dim strTemp As String
If myStr <> "" Then strTemp = myStr
Debug.Print strTemp
End Sub |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Wren | Wren | class MyClass {
construct new() {}
method() { System.print("instance method called") }
static method() { System.print("static method called") }
}
var mc = MyClass.new()
mc.method()
MyClass.method() |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Ursala | Ursala | #import std
#import flo
my_replacement = fleq/0.?/~& negative
abs = math.|fabs my_replacement |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #VBA | VBA | function ffun(x, y)
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun
double precision :: x, y, ffun
ffun = x + y * y
end function |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Python | Python | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n*(n + 1)//2
continue
i = np.searchsorted(blk, root, 'left')
i += blk[i]*blk[i] < lb
if not i:
return blk[0]*blk[0], pos
p = blk[:i + 1]
q = (lb - 1)//p
idx = np.searchsorted(blk, q, 'right')
sel = idx < n
p, idx = p[sel], idx[sel]
q = blk[idx]
sel = q >= p
p, q, idx = p[sel], q[sel], idx[sel]
pos += np.sum(idx - np.arange(len(idx)))
return np.min(p*q), pos
res = []
p = 0
for i in range(100):
p, _ = smallest_brilliant(p + 1)
res.append(p)
print(f'first 100 are {res}')
for i in range(max_order*2):
thresh = 10**i
p, pos = smallest_brilliant(thresh)
print(f'Above 10^{i:2d}: {p:20d} at #{pos}') |
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
| #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
on braceExpansion(textForExpansion)
-- Massage the text to pass to a shell script: -
-- Single-quote it to render everything in it initially immune from brace and file-system expansion.
-- Include a return at the end to get a new line at the end of each eventual expansion.
set textForExpansion to quoted form of (textForExpansion & return)
-- Switch to ASObjC text for a couple of regex substitutions.
set textForExpansion to current application's class "NSMutableString"'s stringWithString:(textForExpansion)
-- Increase the escape level of every instance of /two/ backslashes (represented by eight in the
-- AppleScript string for the search regex) and isolate each result inside its own quote marks.
tell textForExpansion to replaceOccurrencesOfString:("\\\\\\\\") withString:("''$0$0''") ¬
options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})
-- UNquote every run of braces and/or commas not now immediately preceded by a backslash.
tell textForExpansion to replaceOccurrencesOfString:("(?<!\\\\)[{,}]++") withString:("'$0'") ¬
options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})
-- Pass the massaged text to a shell script to be 'echo'-ed. Since a space will still be inserted
-- between each expansion, also delete the space after each return in the result.
-- Return a list of the individual expansions.
return (do shell script ("echo " & textForExpansion & " | sed -E 's/([[:cntrl:]]) /\\1/g'"))'s paragraphs
end braceExpansion
-- Test:
set output to braceExpansion("~/{Downloads,Pictures}/*.{jpg,gif,png}") & ¬
braceExpansion("It{{em,alic}iz,erat}e{d,}, please.") & ¬
braceExpansion("{,{,gotta have{ ,\\, again\\, }}more }cowbell!") & ¬
braceExpansion("{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}")
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
log output -- To see the result without the backslash-escaping. |
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
| #11l | 11l | F isPrime(n)
I n % 2 == 0
R n == 2
I n % 3 == 0
R n == 3
V d = 5
L d * d <= n
I n % d == 0
R 0B
I n % (d + 2) == 0
R 0B
d += 6
R 1B
F sameDigits(=n, b)
V d = n % b
n I/= b
I d == 0
R 0B
L n > 0
I n % b != d
R 0B
n I/= b
R 1B
F isBrazilian(n)
I n < 7
R 0B
I (n [&] 1) == 0
R 1B
L(b) 2 .. n - 2
I sameDigits(n, b)
R 1B
R 0B
F printList(title, check)
print(title)
V n = 7
[Int] l
L
I check(n) & isBrazilian(n)
l.append(n)
I l.len == 20 {L.break}
n++
print(l.join(‘, ’))
print()
printList(‘First 20 Brazilian numbers:’, n -> 1B)
printList(‘First 20 odd Brazilian numbers:’, n -> (n [&] 1) != 0)
printList(‘First 20 prime Brazilian numbers:’, n -> isPrime(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
| #AutoHotkey | AutoHotkey | Calendar(Yr){
LastDay := [], Day := []
Titles =
(ltrim
______January_________________February_________________March_______
_______April____________________May____________________June________
________July___________________August_________________September_____
______October_________________November________________December______
)
StringSplit, title, titles, `n
Res := "________________________________" Yr "`r`n"
loop 4 { ; 4 Vertical Sections
Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01
Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01
Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01
Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa"
loop , 6 { ; 6 Weeks max per month
Week := A_Index, Res .= "`r`n"
loop, 21 { ; 3 weeks times 7 days
Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1
FormatTime, WD, % Day[Mon], WDay
FormatTime, dd, % Day[Mon], dd
if (WD>ThisWD) {
Res .= "__ "
continue
}
dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days
Res .= ((wd=7) && A_Index < 21) ? "___" : ""
FormatTime, dd, % Day[Mon], dd
}
}
Res .= "`r`n"
}
StringReplace, Res, Res,_,%A_Space%, all
Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ")
return res
} |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #E | E | open System
open System.Reflection
type MyClass() =
let answer = 42
member this.GetAnswer
with get() = answer
[<EntryPoint>]
let main argv =
let myInstance = MyClass()
let fieldInfo = myInstance.GetType().GetField("answer", BindingFlags.NonPublic ||| BindingFlags.Instance)
let answer = fieldInfo.GetValue(myInstance)
printfn "%s = %A" (answer.GetType().ToString()) answer
0 |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #F.23 | F# | open System
open System.Reflection
type MyClass() =
let answer = 42
member this.GetAnswer
with get() = answer
[<EntryPoint>]
let main argv =
let myInstance = MyClass()
let fieldInfo = myInstance.GetType().GetField("answer", BindingFlags.NonPublic ||| BindingFlags.Instance)
let answer = fieldInfo.GetValue(myInstance)
printfn "%s = %A" (answer.GetType().ToString()) answer
0 |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #AutoHotkey | AutoHotkey | SetBatchLines -1
Process, Priority,, high
size := 400
D := .08
num := size * size * d
field:= Object()
field[size//2, size//2] := true ; set the seed
lost := 0
Loop % num
{
x := Rnd(1, size), y := Rnd(1, size)
Loop
{
oldX := X, oldY := Y
x += Rnd(-1, 1), y += Rnd(1, -1)
If ( field[x, y] )
{
field[oldX, oldY] := true
break
}
If ( X > Size ) or ( Y > Size) or ( X < 1 ) or ( Y < 1 )
{
lost++
break
}
}
}
pToken := Gdip_startup()
pBitmap := Gdip_CreateBitmap(size, size)
loop %size%
{
x := A_index
Loop %size%
{
If ( field[x, A_Index] )
{
Gdip_SetPixel(pBitmap, x, A_Index, 0xFF0000FF)
}
}
}
Gdip_SaveBitmapToFile(pBitmap, "brownian.png")
Gdip_DisposeImage(pBitmap)
Gdip_Shutdown(pToken)
Run brownian.png
MsgBox lost %lost%
Rnd(min, max){
Random, r, min, max
return r
} |
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
| #Arturo | Arturo | rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0
while [bulls <> 4][
bulls: new 0
cows: new 0
got: strip input "make a guess: "
if? or? not? numeric? got
4 <> size got -> print "Malformed answer. Try again!"
else [
loop.with:'i split got 'digit [
if? (to :integer digit) = rand\[i] -> inc 'bulls
else [
if contains? rand to :integer digit -> inc 'cows
]
]
print ["Bulls:" bulls "Cows:" cows "\n"]
]
]
print color #green "** Well done! You made the right guess!!" |
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
| #Ksh | Ksh |
#!/bin/ksh
# Burrows–Wheeler transform
# # Variables:
#
export LC_COLLATE=POSIX
STX=\^ # start marker
ETX=\| # end marker
typeset -a str
str[0]='BANANA'
str[1]='appellee'
str[2]='dogwood'
str[3]='TO BE OR NOT TO BE OR WANT TO BE OR NOT?'
str[4]='SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES'
str[5]='|ABC^'
# # Functions:
#
# # Function _bwt(str, arr, lc) - sort all circular shifts of arr, return last col
#
function _bwt {
typeset _str ; _str="$1"
typeset _arr ; nameref _arr="$2"
typeset _lastcol ; nameref _lastcol="$3"
typeset _i _j _newstr ; integer _i _j
[[ ${_str} == *+("$STX"|"$ETX")* ]] && return 1
_str="$STX${_str}$ETX"
for ((_i=0; _i<${#_str}; _i++)); do
_newstr=${_str:${#_str}-1:1}
for ((_j=0; _j<${#_str}-1; _j++)); do
_newstr+=${_str:${_j}:1}
done
_arr+=( "${_newstr}" )
_str="${_newstr}"
done
set -sA arr # Sort arr
for ((_i=0; _i<${#_arr[*]}; _i++)); do
_lastcol+=${_arr[_i]:${#_arr[_i]}-1:1}
done
}
# # Function _ibwt(str) - inverse bwt
#
function _ibwt {
typeset _str ; _str="$1"
typeset _arr _vec _ret _i ; typeset -a _arr _vec ; integer _i
_intovec "${_str}" _vec
for ((_i=1; _i<${#_str}; _i++)); do
_intoarr _vec _arr
set -sA _arr
done
for ((_i=0; _i<${#arr[*]}; _i++)); do
[[ "${arr[_i]}" == ${STX}*${ETX} ]] && echo "${arr[_i]}" && return
done
}
# # Function _intovec(str, vec) - trans str into vec[]
#
function _intovec {
typeset _str ; _str="$1"
typeset _vec ; nameref _vec="$2"
typeset _i ; integer _i
for ((_i=0; _i<${#_str}; _i++)); do
_vec+=( "${_str:${_i}:1}" )
done
}
# # Function _intoarr(i, vec, arr) - insert vec into arr
#
function _intoarr {
typeset _vec ; nameref _vec="$1"
typeset _arr ; nameref _arr="$2"
typeset _j ; integer _j
for ((_j=0; _j<${#_vec[*]}; _j++)); do
_arr="${_vec[_j]}${_arr[_j]}"
done
}
######
# main #
######
for ((i=0; i<${#str[*]}; i++)); do
unset arr lastcol result ; typeset -a arr
print -- "${str[i]}"
_bwt "${str[i]}" arr lastcol
(( $? )) && print "ERROR: string cannot contain $STX or $ETX" && continue
print -- "${lastcol}"
result=$(_ibwt "${lastcol}")
print -- "${result}"
echo
done
|
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
| #Lua | Lua | STX = string.char(tonumber(2,16))
ETX = string.char(tonumber(3,16))
function bwt(s)
if s:find(STX, 1, true) then
error("String cannot contain STX")
end
if s:find(ETX, 1, true) then
error("String cannot contain ETX")
end
local ss = STX .. s .. ETX
local tbl = {}
for i=1,#ss do
local before = ss:sub(i + 1)
local after = ss:sub(1, i)
table.insert(tbl, before .. after)
end
table.sort(tbl)
local sb = ""
for _,v in pairs(tbl) do
sb = sb .. string.sub(v, #v, #v)
end
return sb
end
function ibwt(r)
local le = #r
local tbl = {}
for i=1,le do
table.insert(tbl, "")
end
for j=1,le do
for i=1,le do
tbl[i] = r:sub(i,i) .. tbl[i]
end
table.sort(tbl)
end
for _,row in pairs(tbl) do
if row:sub(le,le) == ETX then
return row:sub(2, le - 1)
end
end
return ""
end
function makePrintable(s)
local a = s:gsub(STX, '^')
local b = a:gsub(ETX, '|')
return b
end
function main()
local tests = {
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
STX .. "ABC" .. ETX
}
for _,test in pairs(tests) do
print(makePrintable(test))
io.write(" --> ")
local t = ""
if xpcall(
function () t = bwt(test) end,
function (err) print("ERROR: " .. err) end
) then
print(makePrintable(t))
end
local r = ibwt(t)
print(" --> " .. r)
print()
end
end
main() |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ STRINGSIZE, 500
/* Initialized data */
.data
szMessString: .asciz "String :\n"
szMessEncrip: .asciz "\nEncrypted :\n"
szMessDecrip: .asciz "\nDecrypted :\n"
szString1: .asciz "Why study medicine because there is internet ?"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
szString2: .skip STRINGSIZE
szString3: .skip STRINGSIZE
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszString1 @ display string
bl affichageMess
ldr r0,iAdrszString1
ldr r1,iAdrszString2
mov r2,#20 @ key
bl encrypt
ldr r0,iAdrszMessEncrip
bl affichageMess
ldr r0,iAdrszString2 @ display string
bl affichageMess
ldr r0,iAdrszString2
ldr r1,iAdrszString3
mov r2,#20 @ key
bl decrypt
ldr r0,iAdrszMessDecrip
bl affichageMess
ldr r0,iAdrszString3 @ display string
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszMessDecrip: .int szMessDecrip
iAdrszMessEncrip: .int szMessEncrip
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString2
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* encrypt strings */
/******************************************************************/
/* r0 contains the address of the string1 */
/* r1 contains the address of the encrypted string */
/* r2 contains the key (1-25) */
encrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
add r4,r2 @ add key
cmp r4,#90 @ > Z
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @> z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
add r4,r2
cmp r4,#122
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* decrypt strings */
/******************************************************************/
/* r0 contains the address of the encrypted string1 */
/* r1 contains the address of the decrypted string */
/* r2 contains the key (1-25) */
decrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
sub r4,r2 @ substract key
cmp r4,#65 @ < A
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @ > z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
sub r4,r2 @ substract key
cmp r4,#97 @ < a
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Emacs_Lisp | Emacs Lisp | (defun factorial (i)
"Compute factorial of i."
(apply #'* (number-sequence 1 i)))
(defun compute-e (iter)
"Compute e."
(apply #'+ 1 (mapcar (lambda (x) (/ 1.0 x))
(mapcar #'factorial (number-sequence 1 iter)))))
(compute-e 20) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Epoxy | Epoxy | fn CalculateE(P)
var E:1,F:1
loop I:1;I<=P;I+:1 do
F*:I
E+:1/F
cls
return E
cls
log(CalculateE(100))
log(math.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)
| #Fortran | Fortran | module Player
implicit none
contains
subroutine Init(candidates)
integer, intent(in out) :: candidates(:)
integer :: a, b, c, d, n
n = 0
thousands: do a = 1, 9
hundreds: do b = 1, 9
tens: do c = 1, 9
units: do d = 1, 9
if (b == a) cycle hundreds
if (c == b .or. c == a) cycle tens
if (d == c .or. d == b .or. d == a) cycle units
n = n + 1
candidates(n) = a*1000 + b*100 + c*10 + d
end do units
end do tens
end do hundreds
end do thousands
end subroutine init
subroutine Evaluate(bulls, cows, guess, candidates)
integer, intent(in) :: bulls, cows, guess
integer, intent(in out) :: candidates(:)
integer :: b, c, s, i, j
character(4) :: n1, n2
write(n1, "(i4)") guess
do i = 1, size(candidates)
if (candidates(i) == 0) cycle
b = 0
c = 0
write(n2, "(i4)") candidates(i)
do j = 1, 4
s = index(n1, n2(j:j))
if(s /= 0) then
if(s == j) then
b = b + 1
else
c = c + 1
end if
end if
end do
if(.not.(b == bulls .and. c == cows)) candidates(i) = 0
end do
end subroutine Evaluate
function Nextguess(candidates)
integer :: Nextguess
integer, intent(in out) :: candidates(:)
integer :: i
nextguess = 0
do i = 1, size(candidates)
if(candidates(i) /= 0) then
nextguess = candidates(i)
candidates(i) = 0
return
end if
end do
end function
end module Player
program Bulls_Cows
use Player
implicit none
integer :: bulls, cows, initial, guess
integer :: candidates(3024) = 0
real :: rnum
! Fill candidates array with all possible number combinations
call Init(candidates)
! Random initial guess
call random_seed
call random_number(rnum)
initial = 3024 * rnum + 1
guess = candidates(initial)
candidates(initial) = 0
do
write(*, "(a, i4)") "My guess is ", guess
write(*, "(a)", advance = "no") "Please score number of Bulls and Cows: "
read*, bulls, cows
write(*,*)
if (bulls == 4) then
write(*, "(a)") "Solved!"
exit
end if
! We haven't found the solution yet so evaluate the remaining candidates
! and eliminate those that do not match the previous score given
call Evaluate(bulls, cows, guess, candidates)
! Get the next guess from the candidates that are left
guess = Nextguess(candidates)
if(guess == 0) then
! If we get here then no solution is achievable from the scores given or the program is bugged
write(*, "(a)") "Sorry! I can't find a solution. Possible mistake in the scoring"
exit
end if
end do
end program |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to all UPPERCASE)
This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
Moreover this task is further inspired by the long lost corollary article titled:
"Real programmers think in UPPERCASE"!
Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all
4-bit,
5-bit,
6-bit &
7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer.
Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING,
and suffer from chronic Presbyopia, hence programming in UPPERCASE
is less to do with computer architecture and more to do with practically. :-)
For economy of size, do not actually include Snoopy generation
in either the code or the output, instead just output a place-holder.
FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.
Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
| #GUISS | GUISS | RIGHTCLICK:CLOCK,ADJUST DATE AND TIME,BUTTON:CANCEL |
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
| #Luck | Luck | import "stdio.h";;
import "string.h";;
let s1:string = "Hello World!";;
let s2:char* = strdup(cstring(s1));;
puts(s2);;
free(s2 as void*) |
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckCCall {
mybuf$=string$(chr$(0), 1000)
a$="Hello There 12345"+Chr$(0)
Print Len(a$)
Buffer Clear Mem as Byte*Len(a$)
\\ copy to Mem the converted a$ (from Utf-16Le to ANSI)
Return Mem, 0:=str$(a$)
Declare MyStrDup Lib C "msvcrt._strdup" { Long Ptr}
Declare MyFree Lib C "msvcrt.free" { Long Ptr}
\\ see & means by reference
\\ ... means any number of arguments
Declare MyPrintStr Lib C "msvcrt.swprintf" { &sBuf$, sFmt$, long Z }
\\ Now we use address Mem(0) as pointer (passing by value)
Long Z=MyStrDup(Mem(0))
a=MyPrintStr(&myBuf$, "%s", Z)
Print MyFree(Z), a
Print LeftPart$(chr$(mybuf$), chr$(0))
}
CheckCCall
|
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.
| #C.2B.2B | C++ |
/* function with no arguments */
foo();
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Python | Python | WIDTH = 81
HEIGHT = 5
lines=[]
def cantor(start, len, index):
seg = len / 3
if seg == 0:
return None
for it in xrange(HEIGHT-index):
i = index + it
for jt in xrange(seg):
j = start + seg + jt
pos = i * WIDTH + j
lines[pos] = ' '
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
return None
lines = ['*'] * (WIDTH*HEIGHT)
cantor(0, WIDTH, 1)
for i in xrange(HEIGHT):
beg = WIDTH * i
print ''.join(lines[beg : beg+WIDTH]) |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR p=2 TO 61
20 LET n=p: GO SUB 1000
30 IF NOT n THEN GO TO 200
40 FOR h=1 TO p-1
50 FOR d=1 TO h-1+p
60 IF NOT (FN m((h+p)*(p-1),d)=0 AND FN w(-p*p,h)=FN m(d,h)) THEN GO TO 180
70 LET q=INT (1+((p-1)*(h+p)/d))
80 LET n=q: GO SUB 1000
90 IF NOT n THEN GO TO 180
100 LET r=INT (1+(p*q/h))
110 LET n=r: GO SUB 1000
120 IF (NOT n) OR ((FN m((q*r),(p-1))<>1)) THEN GO TO 180
130 PRINT p;" ";q;" ";r
180 NEXT d
190 NEXT h
200 NEXT p
210 STOP
1000 IF n<4 THEN LET n=(n>1): RETURN
1010 IF (NOT FN m(n,2)) OR (NOT FN m(n,3)) THEN LET n=0: RETURN
1020 LET i=5
1030 IF NOT ((i*i)<=n) THEN LET n=1: RETURN
1040 IF (NOT FN m(n,i)) OR NOT FN m(n,(i+2)) THEN LET n=0: RETURN
1050 LET i=i+6
1060 GO TO 1030
2000 DEF FN m(a,b)=a-(INT (a/b)*b): REM Mod function
2010 DEF FN w(a,b)=FN m(FN m(a,b)+b,b): REM Mod function modified
|
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
| #PARI.2FGP | PARI/GP | reduce(f, v)={
my(t=v[1]);
for(i=2,#v,t=f(t,v[i]));
t
};
reduce((a,b)->a+b, [1,2,3,4,5,6,7,8,9,10]) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #XLISP | XLISP | (SETQ DOG 'BENJAMIN)
(SETQ Dog 'SAMBA)
(SETQ dog 'BERNIE)
(DISPLAY `(THERE IS JUST ONE DOG NAMED ,DOG)) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #XPL0 | XPL0 |
dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
print "The three dogs are named ", dog$, ", ", Dog$, " and ", DOG$
end |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Yabasic | Yabasic |
dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
print "The three dogs are named ", dog$, ", ", Dog$, " and ", DOG$
end |
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}
| #Racket | Racket | #lang racket/base
(require rackunit
;; usually, included in "racket", but we're using racket/base so we
;; show where this comes from
(only-in racket/list cartesian-product))
;; these tests will pass silently
(check-equal? (cartesian-product '(1 2) '(3 4))
'((1 3) (1 4) (2 3) (2 4)))
(check-equal? (cartesian-product '(3 4) '(1 2))
'((3 1) (3 2) (4 1) (4 2)))
(check-equal? (cartesian-product '(1 2) '()) '())
(check-equal? (cartesian-product '() '(1 2)) '())
;; these will print
(cartesian-product '(1776 1789) '(7 12) '(4 14 23) '(0 1))
(cartesian-product '(1 2 3) '(30) '(500 100))
(cartesian-product '(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
| #Fortran | Fortran | program main
!=======================================================================================
implicit none
!=== Local data
integer :: n
!=== External procedures
double precision, external :: catalan_numbers
!=== Execution =========================================================================
write(*,'(1x,a)')'==============='
write(*,'(5x,a,6x,a)')'n','c(n)'
write(*,'(1x,a)')'---------------'
do n = 0, 14
write(*,'(1x,i5,i10)') n, int(catalan_numbers(n))
enddo
write(*,'(1x,a)')'==============='
!=======================================================================================
end program main
!BL
!BL
!BL
double precision recursive function catalan_numbers(n) result(value)
!=======================================================================================
implicit none
!=== Input, ouput data
integer, intent(in) :: n
!=== Execution =========================================================================
if ( n .eq. 0 ) then
value = 1
else
value = ( 2.0d0 * dfloat(2 * n - 1) / dfloat( n + 1 ) ) * catalan_numbers(n-1)
endif
!=======================================================================================
end function catalan_numbers |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #XBS | XBS | class MyClass {
construct=func(self,Props){
self:Props=Props;
}{Props={}}
GetProp=func(self,Name){
send self.Props[Name];
}
}
set Class = new MyClass with [{Name="MyClass Name"}];
log(Class::GetProp("Name")); |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #XLISP | XLISP | (DEFINE-CLASS MY-CLASS)
(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
(DISPLAY "I am the class -- ")
(DISPLAY SELF)
(NEWLINE)
(DISPLAY "You sent me the parameter ")
(DISPLAY SOME-PARAMETER)
(NEWLINE))
(DEFINE-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
(DISPLAY "I am an instance of the class -- ")
(DISPLAY SELF)
(NEWLINE)
(DISPLAY "You sent me the parameter ")
(DISPLAY SOME-PARAMETER)
(NEWLINE))
(MY-CLASS 'DO-SOMETHING-WITH 'FOO)
(DEFINE MY-INSTANCE (MY-CLASS 'NEW))
(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR) |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Zig | Zig | const assert = @import("std").debug.assert;
pub const ID = struct {
name: []const u8,
age: u7,
const Self = @This();
pub fn init(name: []const u8, age: u7) Self {
return Self{
.name = name,
.age = age,
};
}
pub fn getAge(self: Self) u7 {
return self.age;
}
};
test "call an object method" {
// Declare an instance of a struct by using a struct method.
const person1 = ID.init("Alice", 18);
// Or by declaring it manually.
const person2 = ID{
.name = "Bob",
.age = 20,
};
assert(person1.getAge() == 18);
assert(ID.getAge(person2) == 20);
} |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #zkl | zkl | class C{var v; fcn f{v}}
C.f() // call function f in class C
C.v=5; c2:=C(); // create new instance of C
println(C.f()," ",c2.f()) //-->5 Void
C.f.isStatic //--> False
class [static] D{var v=123; fcn f{v}}
D.f(); D().f(); // both return 123
D.f.isStatic //-->False
class E{var v; fcn f{}} E.f.isStatic //-->True |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Wren | Wren | /* call_shared_library_function.wren */
var RTLD_LAZY = 1
foreign class DL {
construct open(file, mode) {}
foreign call(symbol, arg)
foreign close()
}
class My {
static openimage(s) {
System.print("internal openimage opens %(s)...")
if (!__handle) __handle = 0
__handle = __handle + 1
return __handle - 1
}
}
var file = "fake.img"
var imglib = DL.open("./fakeimglib.so", RTLD_LAZY)
var imghandle = (imglib != null) ? imglib.call("openimage", file) : My.openimage(file)
System.print("opened with handle %(imghandle)")
if (imglib != null) imglib.close() |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #X86-64_Assembly | X86-64 Assembly |
option casemap:none
windows64 equ 1
linux64 equ 3
ifndef __LIB_CLASS__
__LIB_CLASS__ equ 1
if @Platform eq windows64
option dllimport:<kernel32>
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
GetProcessHeap proto
LoadLibraryA proto :qword
FreeLibrary proto :qword
GetProcAddress proto :qword, :qword
option dllimport:none
exit equ ExitProcess
dlsym equ GetProcAddress
dlclose equ FreeLibrary
elseif @Platform eq linux64
malloc proto :qword
free proto :qword
exit proto :dword
dlclose proto :qword
dlopen proto :qword, :dword
dlsym proto :qword, :qword
endif
printf proto :qword, :vararg
CLASS libldr
CMETHOD getproc
ENDMETHODS
libname db 100 dup (0)
plib dq ?
ENDCLASS
METHOD libldr, Init, <VOIDARG>, <>, library:qword, namelen:qword
mov rbx, thisPtr
assume rbx:ptr libldr
.if library != 0
mov rcx, namelen
mov rsi, library
lea rdi, [rbx].libname
rep movsb
if @Platform eq windows64
invoke LoadLibraryA, addr [rbx].libname
.if rax == 0
invoke printf, CSTR("--> Failed to load library",10)
.else
mov [rbx].plib, rax
.endif
elseif @Platform eq linux64
invoke dlopen, addr [rbx].libname, 1
.if rax == 0
lea rax, [rbx].libname
invoke printf, CSTR("--> Failed to load library %s",10), rax
.else
mov [rbx].plib, rax
.endif
endif
.else
invoke printf, CSTR("--> Library name to load required..",10)
.endif
mov rax, rbx
assume rbx:nothing
ret
ENDMETHOD
METHOD libldr, getproc, <VOIDARG>, <>, func:qword
local tmp:qword
mov tmp, func
;; Just return RAX..
invoke dlsym, [thisPtr].libldr.plib, tmp
ret
ENDMETHOD
METHOD libldr, Destroy, <VOIDARG>, <>
mov rbx, thisPtr
assume rbx:ptr libldr
.if [rbx].plib != 0
invoke dlclose, [rbx].plib
.endif
assume rbx:nothing
ret
ENDMETHOD
endif
.data
LibName db "./somelib.l",0
.code
main proc
local ldr:ptr libldr
invoke printf, CSTR("--> Loading %s .. ",10), addr LibName
mov ldr, _NEW(libldr, addr LibName, sizeof(LibName))
ldr->getproc(CSTR("disappointment"))
.if rax == 0
lea rax, idisappointment
.endif
call rax
_DELETE(ldr)
invoke exit, 0
ret
main endp
idisappointment:
push rbp
mov rbp, rsp
invoke printf, CSTR("--> Well this is a internal disappointment..",10)
pop rbp
mov rax, 0
ret
end
|
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Raku | Raku | use Lingua::EN::Numbers;
# Find an abundance of primes to use to generate brilliants
my %primes = (2..100000).grep( &is-prime ).categorize: { .chars };
# Generate brilliant numbers
my @brilliant = lazy flat (1..*).map: -> $digits {
sort flat (^%primes{$digits}).race.map: { %primes{$digits}[$_] X× (flat %primes{$digits}[$_ .. *]) }
};
# The task
put "First 100 brilliant numbers:\n" ~ @brilliant[^100].batch(10)».fmt("%4d").join("\n") ~ "\n" ;
for 1 .. 7 -> $oom {
my $threshold = exp $oom, 10;
my $key = @brilliant.first: :k, * >= $threshold;
printf "First >= %13s is %9s in the series: %13s\n", comma($threshold), ordinal-digit(1 + $key, :u), comma @brilliant[$key];
} |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Rust | Rust | // [dependencies]
// primal = "0.3"
// indexing = "0.4.1"
fn get_primes_by_digits(limit: usize) -> Vec<Vec<usize>> {
let mut primes_by_digits = Vec::new();
let mut power = 10;
let mut primes = Vec::new();
for prime in primal::Primes::all().take_while(|p| *p < limit) {
if prime > power {
primes_by_digits.push(primes);
primes = Vec::new();
power *= 10;
}
primes.push(prime);
}
primes_by_digits.push(primes);
primes_by_digits
}
fn main() {
use indexing::algorithms::lower_bound;
use std::time::Instant;
let start = Instant::now();
let primes_by_digits = get_primes_by_digits(1000000000);
println!("First 100 brilliant numbers:");
let mut brilliant_numbers = Vec::new();
for primes in &primes_by_digits {
for i in 0..primes.len() {
let p1 = primes[i];
for j in i..primes.len() {
let p2 = primes[j];
brilliant_numbers.push(p1 * p2);
}
}
if brilliant_numbers.len() >= 100 {
break;
}
}
brilliant_numbers.sort();
for i in 0..100 {
let n = brilliant_numbers[i];
print!("{:4}{}", n, if (i + 1) % 10 == 0 { '\n' } else { ' ' });
}
println!();
let mut power = 10;
let mut count = 0;
for p in 1..2 * primes_by_digits.len() {
let primes = &primes_by_digits[p / 2];
let mut position = count + 1;
let mut min_product = 0;
for i in 0..primes.len() {
let p1 = primes[i];
let n = (power + p1 - 1) / p1;
let j = lower_bound(&primes[i..], &n);
let p2 = primes[i + j];
let product = p1 * p2;
if min_product == 0 || product < min_product {
min_product = product;
}
position += j;
if p1 >= p2 {
break;
}
}
println!("First brilliant number >= 10^{p} is {min_product} at position {position}");
power *= 10;
if p % 2 == 1 {
let size = primes.len();
count += size * (size + 1) / 2;
}
}
let time = start.elapsed();
println!("\nElapsed time: {} milliseconds", time.as_millis());
} |
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
| #AutoHotkey | AutoHotkey | ;This one is a lot more simpler than the rest
BraceExp(string, del:="`n") {
Loop, Parse, string
if (A_LoopField = "{")
break
else
substring .= A_LoopField
substr := SubStr(string, InStr(string, "{")+1, InStr(string, "}")-InStr(string, "{")-1)
Loop, Parse, substr, `,
toreturn .= substring . A_LoopField . del
return toreturn
}
Msgbox, % BraceExp("enable_{video,audio}")
Msgbox, % BraceExp("apple {bush,tree}")
Msgbox, % BraceExp("h{i,ello}")
Msgbox, % BraceExp("rosetta{code,stone}") |
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
| #Action.21 | Action! | INCLUDE "H6:SIEVE.ACT"
BYTE FUNC SameDigits(INT x,b)
INT d
d=x MOD b
x==/b
WHILE x>0
DO
IF x MOD b#d THEN
RETURN (0)
FI
x==/b
OD
RETURN (1)
BYTE FUNC IsBrazilian(INT x)
INT b
IF x<7 THEN RETURN (0) FI
IF x MOD 2=0 THEN RETURN (1) FI
FOR b=2 TO x-2
DO
IF SameDigits(x,b) THEN
RETURN (1)
FI
OD
RETURN (0)
PROC Main()
DEFINE COUNT="20"
DEFINE MAXNUM="3000"
BYTE ARRAY primes(MAXNUM+1)
INT i,x,c
CHAR ARRAY s
Put(125) PutE() ;clear the screen
Sieve(primes,MAXNUM+1)
FOR i=0 TO 2
DO
IF i=0 THEN
s=" "
ELSEIF i=1 THEN
s=" odd "
ELSE
s=" prime "
FI
PrintF("First %I%SBrazilian numbers:%E",COUNT,s)
c=0 x=7
DO
IF IsBrazilian(x) THEN
PrintI(x) Put(32)
c==+1
IF c=COUNT THEN EXIT FI
FI
IF i=0 THEN
x==+1
ELSEIF i=1 THEN
x==+2
ELSE
DO
x==+2
UNTIL primes(x)
OD
FI
OD
PutE() PutE()
OD
RETURN |
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
| #AutoIt | AutoIt |
#include <Date.au3>
; Set the count of characters in each line, minimum is 20 - one month.
Global $iPrintSize = 132
; Set the count of months, you want to print side by side. With "0" it calculates automatically.
; The number will corrected, if it not allowed to print in an rectangle.
; If your print size is to small for given count, it will set back to automatically calculation.
Global $iSideBySide = 3
; Set the count of spaces between months.
Global $iSpace = 4
_CreateCalendar( 1969 )
Func _CreateCalendar($_iYear)
Local $aMon[12] = [' January ', ' February ', ' March ', _
' April ', ' May ', ' June ', _
' July ', ' August ', ' September ', _
' October ', ' November ', ' December ']
Local $sHead = 'Mo Tu We Th Fr Sa Su'
Local $aDaysInMonth[12] = [31,28,31,30,31,30,31,31,30,31,30,31]
If _DateIsLeapYear($_iYear) Then $aDaysInMonth[1] = 29
; == assign date in weekday table for the whole year
Local $aAllDaysInMonth[6][7][12] ; [ lines ][ weekdays ][ months ]
Local $iDay = 1, $iShift
For $i = 1 To 12
$iShift = _DateToDayOfWeekISO($_iYear, $i, 1) -1
For $j = 0 To 5
For $k = $iShift To 6
$aAllDaysInMonth[$j][$k][$i-1] = $iDay
$iDay += 1
If $iDay > $aDaysInMonth[$i-1] Then ExitLoop(2)
Next
$iShift = 0
Next
$iDay = 1
Next
; == check given side by side count, calculate if needed
If $iSideBySide > 0 Then
If $iPrintSize < ($iSideBySide *(20 +$iSpace) -$iSpace) Then $iSideBySide = 0
EndIf
Switch $iSideBySide
Case 0
$iSideBySide = Int($iPrintSize /(20 +$iSpace))
If $iPrintSize < 20 Then Return _PrintLine('Escape: Size Error')
If $iPrintSize < (20 +$iSpace) Then $iSideBySide = 1
Case 5
$iSideBySide = 4
Case 7 To 11
$iSideBySide = 6
EndSwitch
; == create space string
Local $sSpace = ''
For $i = 1 To $iSpace
$sSpace &= ' '
Next
; == print header
_PrintLine(@LF)
_PrintLine('[ here is Snoopy ]', @LF)
_PrintLine(StringRegExpReplace($_iYear, '(\d)(\d)(\d)(\d)', '$1 $2 $3 $4'), @LF)
; == create data for each line, in dependence to count of months in one line
Local $sLine, $iRight, $sTmp1, $sTmp2
For $n = 0 To 12 /$iSideBySide -1
$sTmp1 = ''
$sTmp2 = ''
For $z = 0 To $iSideBySide -1
$sTmp1 &= $aMon[$iSideBySide *$n+$z] & $sSpace
$sTmp2 &= $sHead & $sSpace
Next
_PrintLine(StringTrimRight($sTmp1, $iSpace))
_PrintLine(StringTrimRight($sTmp2, $iSpace))
For $j = 0 To 5
$sLine = ''
For $i = 1 To $iSideBySide
For $k = 0 To 6
$iRight = 3
If $k = 0 Then $iRight = 2
$sLine &= StringRight(' ' & $aAllDaysInMonth[$j][$k][$iSideBySide*$n+$i-1], $iRight)
Next
If $i < $iSideBySide Then $sLine &= $sSpace
Next
_PrintLine($sLine)
Next
Next
EndFunc ;==>_CreateCalendar
Func _PrintLine($_sLine, $_sLF='')
Local $iLen = StringLen($_sLine)
Local $sSpace = '', $sLeft = ''
For $i = 1 To $iPrintSize-1
$sSpace &= ' '
Next
If $iLen < $iPrintSize Then $sLeft = StringLeft($sSpace, Int(($iPrintSize-$iLen)/2))
ConsoleWrite($sLeft & $_sLine & $_sLF & @LF)
EndFunc ;==>_PrintLine
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Factor | Factor | ( scratchpad ) USING: sets sets.private ;
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
2 |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Forth | Forth | include FMS-SI.f
99 value x \ create a global variable named x
:class foo
ivar x \ this x is private to the class foo
:m init: 10 x ! ;m \ constructor
:m print x ? ;m
;class
foo f1 \ instantiate a foo object
f1 print \ 10 access the private x with the print message
x . \ 99 x is a globally scoped name
50 .. f1.x ! \ use the dot parser to access the private x without a message
f1 print \ 50
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #FreeBASIC | FreeBASIC | 'FB 1.05.0 Win64
#Undef Private
#Undef Protected
#Define Private Public
#Define Protected Public
Type MyType
Public :
x As Integer = 1
Protected :
y As Integer = 2
Private :
z As Integer = 3
End Type
Dim mt As MyType
Print mt.x, mt.y, mt.z
Print
Print "Press any key to quit"
Sleep |
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.
| #BBC_BASIC | BBC BASIC | SYS "SetWindowText", @hwnd%, "Brownian Tree"
SIZE = 400
VDU 23,22,SIZE;SIZE;8,16,16,0
GCOL 10
REM set the seed:
PLOT SIZE, SIZE
OFF
REPEAT
REM set particle's initial position:
REPEAT
X% = RND(SIZE)-1
Y% = RND(SIZE)-1
UNTIL POINT(2*X%,2*Y%) = 0
REPEAT
oldX% = X%
oldY% = Y%
X% += RND(3) - 2
Y% += RND(3) - 2
UNTIL POINT(2*X%,2*Y%)
IF X%>=0 IF X%<SIZE IF Y%>=0 IF Y%<SIZE PLOT 2*oldX%,2*oldY%
UNTIL 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
| #AutoHotkey | AutoHotkey | length:=4, Code:="" ; settings
While StrLen(Code) < length {
Random, num, 1, 9
If !InStr(Code, num)
Code .= num
}
Gui, Add, Text, w83 vInfo, I'm thinking of a %length%-digit number with no duplicate digits.
Gui, Add, Edit, wp vGuess, Enter a guess...
Gui, Add, Button, wp Default vDefault, Submit
Gui, Add, Edit, ym w130 r8 vHistory ReadOnly
Gui, Show
Return
ButtonSubmit:
If Default = Restart
Reload
Gui, Submit, NoHide
If (StrLen(Guess) != length)
GuiControl, , Info, Enter a %length%-digit number.
Else If Guess is not digit
GuiControl, , Info, Enter a %length%-digit number.
Else
{
GuiControl, , Info
GuiControl, , Guess
If (Guess = Code)
{
GuiControl, , Info, Correct!
GuiControl, , Default, Restart
Default = Restart
}
response := Response(Guess, Code)
Bulls := SubStr(response, 1, InStr(response,",")-1)
Cows := SubStr(response, InStr(response,",")+1)
GuiControl, , History, % History . Guess ": " Bulls " Bulls " Cows " Cows`n"
}
Return
GuiEscape:
GuiClose:
ExitApp
Response(Guess,Code) {
Bulls := 0, Cows := 0
Loop, % StrLen(Code)
If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1))
Bulls++
Else If (InStr(Code, SubStr(Guess, A_Index, 1)))
Cows++
Return Bulls "," Cows
} |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[BurrowWheeler, InverseBurrowWheeler]
BurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s},
s = Characters[bdelim <> sin <> edelim];
s = RotateLeft[s, #] & /@ Range[Length[s]];
StringJoin[LexicographicSort[s][[All, -1]]]
]
InverseBurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s, chars},
chars = Characters[sin];
s = ConstantArray[{}, Length[chars]];
Do[
s = LexicographicSort[MapThread[Prepend, {s, chars}]];
,
{Length[chars]}
];
StringTake[StringJoin[SelectFirst[s, Last /* EqualTo[edelim]]], {2, -2}]
]
BurrowWheeler["BANANA", {"^", "|"}]
InverseBurrowWheeler[%, {"^", "|"}]
BurrowWheeler["appellee", {"^", "|"}]
InverseBurrowWheeler[%, {"^", "|"}]
BurrowWheeler["dogwood", {"^", "|"}]
InverseBurrowWheeler[%, {"^", "|"}] |
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
| #Nim | Nim | import algorithm
from sequtils import repeat
import strutils except repeat
const
Stx = '\2'
Etx = '\3'
#---------------------------------------------------------------------------------------------------
func bwTransform*(s: string): string =
## Apply Burrows–Wheeler transform to input string.
doAssert(Stx notin s and Etx notin s, "Input string cannot contain STX and ETX characters")
let s = Stx & s & Etx # Add start and end of text marker.
# Build the table of rotated strings and sort it.
var table = newSeqOfCap[string](s.len)
for i in 0..s.high:
table.add(s[i + 1..^1] & s[0..i])
table.sort()
# Extract last column of the table.
for item in table:
result.add(item[^1])
#---------------------------------------------------------------------------------------------------
func invBwTransform*(r: string): string =
## Apply inverse Burrows–Wheeler transform.
# Build table.
var table = repeat("", r.len)
for _ in 1..r.len:
for i in 0..<r.len:
table[i] = r[i] & table[i]
table.sort()
# Find the correct row (ending in ETX).
var idx = 0
while not table[idx].endsWith(Etx):
inc idx
result = table[idx][1..^2]
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
proc displaybleString(s: string): string =
## Build a displayable string from a string containing STX and ETX characters.
s.multiReplace(("\2", "¹"), ("\3", "²"))
for text in ["banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES"]:
let transformed = text.bwTransform()
let invTransformed = transformed.invBwTransform()
echo ""
echo "Original text: ", text
echo "After transformation: ", transformed.displaybleString()
echo "After inverse transformation: ", invTransformed |
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
| #Arturo | Arturo | ia: to :integer `a`
iA: to :integer `A`
lowAZ: `a`..`z`
uppAZ: `A`..`Z`
caesar: function [s, xx][
k: (not? null? attr 'decode)? -> 26-xx -> xx
result: new ""
loop s 'i [
(in? i lowAZ)? -> 'result ++ to :char ia + (k + (to :integer i) - ia) % 26
[
(in? i uppAZ)? -> 'result ++ to :char iA + (k + (to :integer i) - iA) % 26
-> 'result ++ i
]
]
return result
]
msg: "The quick brown fox jumped over the lazy dogs"
print ["Original :" msg]
enc: caesar msg 11
print [" Encoded :" enc]
print [" Decoded :" caesar.decode enc 11] |
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
| #Excel | Excel | eApprox
=LAMBDA(n,
INDEX(
FOLDROW(
LAMBDA(efl,
LAMBDA(x,
LET(
flx, INDEX(efl, 2) * x,
e, INDEX(efl, 1),
CHOOSE(
{1;2},
e + (1 / flx),
flx
)
)
)
)
)({1;1})(
SEQUENCE(1, n)
),
1
)
) |
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)
| #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Println(`Cows and bulls/player
You think of four digit number of unique digits in the range 1 to 9.
I guess. You score my guess:
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.
You give my score as two numbers separated with a space.`)
// generate possible patterns, store in map
m := make(map[string]int)
var g func([]byte, int)
g = func(digits []byte, fixed int) {
if fixed == 4 {
m[string(digits[:4])] = 0
return
}
for i := fixed; i < len(digits); i++ {
digits[fixed], digits[i] = digits[i], digits[fixed]
g(digits, fixed+1)
digits[fixed], digits[i] = digits[i], digits[fixed]
}
}
g([]byte("123456789"), 0)
// guess/score/eliminate loop
for in := bufio.NewReader(os.Stdin);; {
// pick a value, ie, guess
var guess string
for guess = range m {
delete(m, guess)
break
}
// get and parse score
var c, b uint
for ;; fmt.Println("Score guess as two numbers: cows bulls") {
fmt.Printf("My guess: %s. Score? (c b) ", guess)
score, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
s2 := strings.Fields(score)
if len(s2) == 2 {
c2, err := strconv.ParseUint(s2[0], 10, 0)
if err == nil && c2 <= 4 {
b2, err := strconv.ParseUint(s2[1], 10, 0)
if err == nil && c2+b2 <= 4 {
c = uint(c2)
b = uint(b2)
break
}
}
}
}
// check for win
if b == 4 {
fmt.Println("I did it. :)")
return
}
// eliminate patterns with non-matching scores
for pat := range m {
var cows, bulls uint
for ig, cg := range guess {
switch strings.IndexRune(pat, cg) {
case -1:
default: // I just think cows should go first
cows++
case ig:
bulls++
}
}
if cows != c || bulls != b {
delete(m, pat)
}
}
// check for inconsistency
if len(m) == 0 {
fmt.Println("Oops, check scoring.")
return
}
}
} |
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.
| #Icon_and_Unicon | Icon and Unicon | $include "REALIZE.ICN"
LINK DATETIME
$define ISLEAPYEAR IsLeapYear
$define JULIAN julian
PROCEDURE MAIN(A)
PRINTCALENDAR(\A$<1$>|1969)
END
PROCEDURE PRINTCALENDAR(YEAR)
COLS := 3
MONS := $<$>
"JANUARY FEBRUARY MARCH APRIL MAY JUNE " ||
"JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER " ?
WHILE PUT(MONS, TAB(FIND(" "))) DO MOVE(1)
WRITE(CENTER("$<SNOOPY PICTURE$>",COLS * 24 + 4))
WRITE(CENTER(YEAR,COLS * 24 + 4), CHAR(10))
M := LIST(COLS)
EVERY MON := 0 TO 9 BY COLS DO $(
WRITES(" ")
EVERY I := 1 TO COLS DO {
WRITES(CENTER(MONS$<MON+I$>,24))
M$<I$> := CREATE CALENDARFORMATWEEK(YEAR,MON + I)
$)
WRITE()
EVERY 1 TO 7 DO $(
EVERY C := 1 TO COLS DO $(
WRITES(" ")
EVERY 1 TO 7 DO WRITES(RIGHT(@M$<C$>,3))
$)
WRITE()
$)
$)
RETURN
END
PROCEDURE CALENDARFORMATWEEK(YEAR,M)
STATIC D
INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$>
EVERY SUSPEND "SU"|"MO"|"TU"|"WE"|"TH"|"FR"|"SA"
EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND ""
EVERY SUSPEND 1 TO D$<M$> DO DAY +:= 1
IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29)
EVERY DAY TO (6*7) DO SUSPEND ""
END |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Notes
It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
C++ and C solutions can take some other language to communicate with.
It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.
See also
Use another language to call a function
| #Maple | Maple | > strdup := define_external( strdup, s::string, RETURN::string, LIB = "/lib/libc.so.6" ):
> strdup( "foo" );
"foo"
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["NETLink`"];
externalstrdup = DefineDLLFunction["_strdup", "msvcrt.dll", "string", {"string"}];
Print["Duplicate: ", externalstrdup["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.
| #COBOL | COBOL | CALL "No-Arguments"
*> Fixed number of arguments.
CALL "2-Arguments" USING Foo Bar
CALL "Optional-Arguments" USING Foo
CALL "Optional-Arguments" USING Foo Bar
*> If an optional argument is omitted and replaced with OMITTED, any following
*> arguments can still be specified.
CALL "Optional-Arguments" USING Foo OMITTED Bar
*> Interestingly, even arguments not marked as optional can be omitted without
*> a compiler warning. It is highly unlikely the function will still work,
*> however.
CALL "2-Arguments" USING Foo
*> COBOL does not support a variable number of arguments, or named arguments.
*> Values to return can be put in either one of the arguments or, in OpenCOBOL,
*> the RETURN-CODE register.
*> A standard function call cannot be done in another statement.
CALL "Some-Func" USING Foo
MOVE Return-Code TO Bar
*> Intrinsic functions can be used in any place a literal value may go (i.e. in
*> statements) and are optionally preceded by FUNCTION.
*> Intrinsic functions that do not take arguments may optionally have a pair of
*> empty parentheses.
*> Intrinsic functions cannot be defined by the user.
MOVE FUNCTION PI TO Bar
MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar
*> Built-in functions/subroutines typically have prefixes indicating which
*> compiler originally incorporated it:
*> - C$ - ACUCOBOL-GT
*> - CBL_ - Micro Focus
*> - CBL_OC_ - OpenCOBOL
*> Note: The user could name their functions similarly if they wanted to.
CALL "C$MAKEDIR" USING Foo
CALL "CBL_CREATE_DIR" USING Foo
CALL "CBL_OC_NANOSLEEP" USING Bar
*> Although some built-in functions identified by numbers.
CALL X"F4" USING Foo Bar
*> Parameters can be passed in 3 different ways:
*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may
*> be omitted. The address of the argument is passed to the function.
*> The function is allowed to modify the variable.
*> - BY CONTENT - a copy is made and the function is passed the address
*> of the copy, which it can then modify. This is recomended when
*> passing a literal to a function.
*> - BY VALUE - the function is passed the address of the argument (like a
*> pointer). This is mostly used to provide compatibility with other
*> languages, such as C.
CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified.
CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged.
CALL "C-Func" USING BY VALUE Bar
*> Partial application is impossible as COBOL does not support first-class
*> functions.
*> However, as functions are called using a string of their PROGRAM-ID,
*> you could pass a 'function' as an argument to another function, or store
*> it in a variable, or get it at runtime.
ACCEPT Foo *> Get a PROGRAM-ID from the user.
CALL "Use-Func" USING Foo
CALL Foo USING Bar |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #QB64 | QB64 | _Title "Cantor Set"
Dim Shared As Integer sw, sh, wide, high
sw = 800: sh = 200: wide = 729: high = 7
Dim Shared As Integer a(wide, high)
Screen _NewImage(sw, sh, 8)
Cls , 15: Color 0
Call calc(0, wide, 1)
Call CantorSet
Sleep
System
Sub calc (start As Integer, length As Integer, index As Integer)
Dim As Integer i, j, newLength
newLength = length \ 3
If newLength = 0 Then Exit Sub
For j = index To high - 1
For i = start + newLength To start + newLength * 2 - 1
a(i, j) = 1
Next
Next
Call calc(start, newLength, index + 1)
Call calc(start + newLength * 2, newLength, index + 1)
End Sub
Sub CantorSet
Dim As Integer i, j, x, y
For y = 0 To high - 1
j = y + 1
For x = 0 To wide - 1
i = x + 34
If a(x, y) = 0 Then Line (i, j * 24 - 5)-(i, j * 24 + 17)
Next
Next
End Sub |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Quackery | Quackery | [ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "ABA" ] is A ( $ --> $ )
[ $ "BBB" ] is B ( $ --> $ )
[ char A = iff
[ char q ] else space
swap of echo$ ] is draw ( n c --> $ )
81 $ "A"
5 times
[ dup witheach
[ dip over draw ]
cr
i if
[ expand
dip [ 3 / ] ] ]
2drop
|
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
| #Pascal | Pascal | program reduceApp;
type
// tmyArray = array of LongInt;
tmyArray = array[-5..5] of LongInt;
tmyFunc = function (a,b:LongInt):LongInt;
function add(x,y:LongInt):LongInt;
begin
add := x+y;
end;
function sub(k,l:LongInt):LongInt;
begin
sub := k-l;
end;
function mul(r,t:LongInt):LongInt;
begin
mul := r*t;
end;
function reduce(myFunc:tmyFunc;a:tmyArray):LongInt;
var
i,res : LongInt;
begin
res := a[low(a)];
For i := low(a)+1 to high(a) do
res := myFunc(res,a[i]);
reduce := res;
end;
procedure InitMyArray(var a:tmyArray);
var
i: LongInt;
begin
For i := low(a) to high(a) do
begin
//no a[i] = 0
a[i] := i + ord(i=0);
write(a[i],',');
end;
writeln(#8#32);
end;
var
ma : tmyArray;
BEGIN
InitMyArray(ma);
writeln(reduce(@add,ma));
writeln(reduce(@sub,ma));
writeln(reduce(@mul,ma));
END. |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #zkl | zkl | var dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET D$="Benjamin"
20 PRINT "There is just one dog named ";d$ |
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}
| #Raku | Raku | # cartesian product of two lists using the X cross meta-operator
say (1, 2) X (3, 4);
say (3, 4) X (1, 2);
say (1, 2) X ( );
say ( ) X ( 1, 2 );
# cartesian product of variable number of lists using
# the [X] reduce cross meta-operator
say [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);
say [X] (1, 2, 3), (30), (500, 100);
say [X] (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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function factorial(n As UInteger) As UInteger
If n = 0 Then Return 1
Return n * factorial(n - 1)
End Function
Function catalan1(n As UInteger) As UInteger
Dim prod As UInteger = 1
For i As UInteger = n + 2 To 2 * n
prod *= i
Next
Return prod / factorial(n)
End Function
Function catalan2(n As UInteger) As UInteger
If n = 0 Then Return 1
Dim sum As UInteger = 0
For i As UInteger = 0 To n - 1
sum += catalan2(i) * catalan2(n - 1 - i)
Next
Return sum
End Function
Function catalan3(n As UInteger) As UInteger
If n = 0 Then Return 1
Return catalan3(n - 1) * 2 * (2 * n - 1) \ (n + 1)
End Function
Print "n", "First", "Second", "Third"
Print "-", "-----", "------", "-----"
Print
For i As UInteger = 0 To 15
Print i, catalan1(i), catalan2(i), catalan3(i)
Next
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #zkl | zkl | var BN=Import("zklBigNum");
BN(1)+2 //--> BN(3) |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Sidef | Sidef | func is_briliant_number(n) {
n.is_semiprime && (n.factor.map{.len}.uniq.len == 1)
}
func brilliant_numbers_count(n) {
var count = 0
var len = n.isqrt.len
for k in (1 .. len-1) {
var pi = prime_count(10**(k-1), 10**k - 1)
count += binomial(pi, 2)+pi
}
var min = (10**(len - 1))
var max = (10**len - 1)
each_prime(min, max, {|p|
count += prime_count(p, max `min` idiv(n, p))
})
return count
}
say "First 100 brilliant numbers:"
100.by(is_briliant_number).each_slice(10, {|*a|
say a.map { '%4s' % _}.join(' ')
})
say ''
for n in (1 .. 12) {
var v = (10**n .. Inf -> first_by(is_briliant_number))
printf("First brilliant number >= 10^%d is %s", n, v)
printf(" at position %s\n", brilliant_numbers_count(v))
} |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Swift | Swift | // Refs:
// https://www.geeksforgeeks.org/sieve-of-eratosthenes/?ref=leftbar-rightbar
// https://developer.apple.com/documentation/swift/array/init(repeating:count:)-5zvh4
// https://www.geeksforgeeks.org/brilliant-numbers/#:~:text=Brilliant%20Number%20is%20a%20number,25%2C%2035%2C%2049%E2%80%A6.
// Using Sieve of Eratosthenes
func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false // setting zero to be not prime
primeArr[1] = false // setting one to be not prime
// finding all primes which are divisible by p and are greater than or equal to the square of it
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeArr[j] = false
}
}
p += 1
}
return primeArr
}
func digitsCount(n: Int) -> Int {
// count number of digits for a number
// increase the count if n divide by 10 is not equal to zero
var num = n
var count = 0;
while num != 0 {
num = num/10
count += 1
}
return count
}
func isBrilliant(n: Int) -> Bool {
// Set the prime array
var isPrime = [Bool]()
isPrime = primeArray(n: n)
// Check if the number is the product of two prime numbers
// Also check if the digit counts of those prime numbers are the same.
for i in stride(from: 2, through: n, by: 1) { // i=2, n=50
let x = n / i // i=2, n=50, x=25
if (isPrime[i] && isPrime[x] && x * i == n) { // i=2, x=50, false
if (digitsCount(n: i) == digitsCount(n: x)) {
return true
}
}
}
return false
}
func print100Brilliants() {
// Print the first 100 brilliant numbers
var brilNums = [Int]()
var count = 4
while brilNums.count != 100 {
if isBrilliant(n: count) {
brilNums.append(count)
}
count += 1
}
print("First 100 brilliant numbers:\n", brilNums)
}
func printBrilliantsOfMagnitude() {
// Print the brilliant numbers of base 10 up to magnitude of 6
// Including their positions in the array.
var basePower = 10.0
var brilNums: [Double] = [0.0]
var count = 1.0
while basePower != pow(basePower, 6) {
if isBrilliant(n: Int(count)) {
brilNums.append(count)
if count >= basePower {
print("First brilliant number >= \(Int(basePower)): \(Int(count)) at position \(brilNums.firstIndex(of: count)!)")
basePower *= 10
}
}
count += 1
}
}
print100Brilliants()
printBrilliantsOfMagnitude() |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
string str;
node *root;
} data;
node *next;
};
node *allocate_node(enum tag_t tag) {
node *n = malloc(sizeof(node));
if (n == NULL) {
fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
exit(1);
}
n->tag = tag;
n->next = NULL;
return n;
}
node *make_leaf(string str) {
node *n = allocate_node(NODE_LEAF);
n->data.str = str;
return n;
}
node *make_tree() {
node *n = allocate_node(NODE_TREE);
n->data.root = NULL;
return n;
}
node *make_seq() {
node *n = allocate_node(NODE_SEQ);
n->data.root = NULL;
return n;
}
void deallocate_node(node *n) {
if (n == NULL) {
return;
}
deallocate_node(n->next);
n->next = NULL;
if (n->tag == NODE_LEAF) {
free(n->data.str);
n->data.str = NULL;
} else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
deallocate_node(n->data.root);
n->data.root = NULL;
} else {
fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
exit(1);
}
free(n);
}
void append(node *root, node *elem) {
if (root == NULL) {
fprintf(stderr, "Cannot append to uninitialized node.");
exit(1);
}
if (elem == NULL) {
return;
}
if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
if (root->data.root == NULL) {
root->data.root = elem;
} else {
node *it = root->data.root;
while (it->next != NULL) {
it = it->next;
}
it->next = elem;
}
} else {
fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
exit(1);
}
}
size_t count(node *n) {
if (n == NULL) {
return 0;
}
if (n->tag == NODE_LEAF) {
return 1;
}
if (n->tag == NODE_TREE) {
size_t sum = 0;
node *it = n->data.root;
while (it != NULL) {
sum += count(it);
it = it->next;
}
return sum;
}
if (n->tag == NODE_SEQ) {
size_t prod = 1;
node *it = n->data.root;
while (it != NULL) {
prod *= count(it);
it = it->next;
}
return prod;
}
fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
exit(1);
}
void expand(node *n, size_t pos) {
if (n == NULL) {
return;
}
if (n->tag == NODE_LEAF) {
printf(n->data.str);
} else if (n->tag == NODE_TREE) {
node *it = n->data.root;
while (true) {
size_t cnt = count(it);
if (pos < cnt) {
expand(it, pos);
break;
}
pos -= cnt;
it = it->next;
}
} else if (n->tag == NODE_SEQ) {
size_t prod = pos;
node *it = n->data.root;
while (it != NULL) {
size_t cnt = count(it);
size_t rem = prod % cnt;
expand(it, rem);
it = it->next;
}
} else {
fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
exit(1);
}
}
string allocate_string(string src) {
size_t len = strlen(src);
string out = calloc(len + 1, sizeof(character));
if (out == NULL) {
fprintf(stderr, "Failed to allocate a copy of the string.");
exit(1);
}
strcpy(out, src);
return out;
}
node *parse_seq(string input, size_t *pos);
node *parse_tree(string input, size_t *pos) {
node *root = make_tree();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
size_t depth = 0;
bool asSeq = false;
bool allow = false;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = '\\';
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
asSeq = true;
depth++;
} else if (c == '}') {
if (depth-- > 0) {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
} else {
append(root, make_leaf(allocate_string(buffer)));
}
break;
}
} else if (c == ',') {
if (depth == 0) {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
bufpos = 0;
buffer[bufpos] = 0;
asSeq = false;
} else {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
return root;
}
node *parse_seq(string input, size_t *pos) {
node *root = make_seq();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
node *tree = parse_tree(input, pos);
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
append(root, tree);
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
return root;
}
void test(string input) {
size_t pos = 0;
node *n = parse_seq(input, &pos);
size_t cnt = count(n);
size_t i;
printf("Pattern: %s\n", input);
for (i = 0; i < cnt; i++) {
expand(n, i);
printf("\n");
}
printf("\n");
deallocate_node(n);
}
int main() {
test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
test("It{{em,alic}iz,erat}e{d,}, please.");
test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");
//not sure how to parse this one
//test("{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}");
return 0;
} |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #ALGOL_W | ALGOL W | begin % 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 %
procedure BrazilianSieve ( logical array b ( * ) ; integer value n ) ;
begin
logical isEven;
% start with even numbers flagged as Brazilian and odd numbers as %
% non-Brazilian %
isEven := false;
for i := 1 until n do begin
b( i ) := isEven;
isEven := not isEven
end for_i ;
% numbers below 7 are not Brazilian (see task notes) %
for i := 1 until 6 do b( i ) := false;
% flag all 33, 55, etc. numbers in each base as Brazilian %
% No Brazilian number can have a representation of 11 in any base B %
% as that would mean B + 1 = N, which contradicts B < N - 1 %
% also, no need to consider even digits as we know even numbers > 6 %
% are all Brazilian %
for base := 2 until n div 2 do begin
integer b11, bnn;
b11 := base + 1;
bnn := b11;
for digit := 3 step 2 until base - 1 do begin
bnn := bnn + b11 + b11;
if bnn <= n
then b( bnn ) := true
else goto end_for_digits
end for_digits ;
end_for_digits:
end for_base ;
% handle 111, 1111, 11111, ..., 333, 3333, ..., etc. %
for base := 2 until truncate( sqrt( n ) ) do begin
integer powerMax;
powerMax := MAXINTEGER div base; % avoid 32 bit %
if powerMax > n then powerMax := n; % integer overflow %
for digit := 1 step 2 until base - 1 do begin
integer bPower, bN;
bPower := base * base;
bN := digit * ( bPower + base + 1 ); % ddd %
while bN <= n and bPower <= powerMax do begin
if bN <= n then begin
b( bN ) := true
end if_bN_le_n ;
bPower := bPower * base;
bN := bN + ( digit * bPower )
end while_bStart_le_n
end for_digit
end for_base ;
end BrazilianSieve ;
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
begin
p( 1 ) := false; p( 2 ) := true;
for i := 3 step 2 until n do p( i ) := true;
for i := 4 step 2 until n do p( i ) := false;
for i := 2 until truncate( sqrt( n ) ) do begin
integer ii; ii := i + i;
if p( i ) then for pr := i * i step ii until n do p( pr ) := false
end for_i ;
end Eratosthenes ;
integer MAX_NUMBER;
MAX_NUMBER := 2000000;
begin
logical array b ( 1 :: MAX_NUMBER );
logical array p ( 1 :: MAX_NUMBER );
integer bCount;
BrazilianSieve( b, MAX_NUMBER );
write( "The first 20 Brazilian numbers:" );write();
bCount := 0;
for bPos := 1 until MAX_NUMBER do begin
if b( bPos ) then begin
bCount := bCount + 1;
writeon( i_w := 1, s_w := 0, " ", bPos );
if bCount >= 20 then goto end_first_20
end if_b_bPos
end for_bPos ;
end_first_20:
write();write( "The first 20 odd Brazilian numbers:" );write();
bCount := 0;
for bPos := 1 step 2 until MAX_NUMBER do begin
if b( bPos ) then begin
bCount := bCount + 1;
writeon( i_w := 1, s_w := 0, " ", bPos );
if bCount >= 20 then goto end_first_20_odd
end if_b_bPos
end for_bPos ;
end_first_20_odd:
write();write( "The first 20 prime Brazilian numbers:" );write();
Eratosthenes( p, MAX_NUMBER );
bCount := 0;
for bPos := 1 until MAX_NUMBER do begin
if b( bPos ) and p( bPos ) then begin
bCount := bCount + 1;
writeon( i_w := 1, s_w := 0, " ", bPos );
if bCount >= 20 then goto end_first_20_prime
end if_b_bPos
end for_bPos ;
end_first_20_prime:
write();write( "Various Brazilian numbers:" );
bCount := 0;
for bPos := 1 until MAX_NUMBER do begin
if b( bPos ) then begin
bCount := bCount + 1;
if bCount = 100
or bCount = 1000
or bCount = 10000
or bCount = 100000
or bCount = 1000000
then write( s_w := 0, bCount, "th Brazilian number: ", bPos );
if bCount >= 1000000 then goto end_1000000
end if_b_bPos
end for_bPos ;
end_1000000:
end
end. |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #AWK | AWK |
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk
To change the output width, change the value assigned to variable pagewide
#!/bin/gawk -f
BEGIN{
wkdays = "Su Mo Tu We Th Fr Sa"
pagewide = 80
blank=" "
for (i=1; i<pagewide; i++) blank = blank " "
# month name accessed as substr(month,num*10,10)
# where num is number of month, 1-12
month= " January February March April "
month= month " May June July August "
month= month " September October November December "
# table of days per month accessed as substr(days,2*month,2)
days =" 312831303130313130313031"
line1 = ""
line2 = ""
line3 = ""
line4 = ""
line5 = ""
line6 = ""
line7 = ""
line8 = ""
# print " year: " year " starts on: " dow(year)
}
function center(text, half) {
half = (pagewide - length(text))/2
return substr(blank,1,half) text substr(blank,1,half)
}
function min(a,b) {
if (a < b) return a
else return b
}
function makewk (fst,lst,day, i,wstring ){
wstring=""
for (i=1;i<day;i++) wstring=wstring " "
for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i)
return substr(wstring " ",1,20)
}
function dow (year, y){
y=year
y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7
# leap year adjustment
leap = 0
if (year % 4 == 0) leap = 1
if (year % 100 == 0) leap = 0
if (year % 400 == 0) leap = 1
y = y - leap
if (y==-1) y=6
if (y==0) y=7
return (y)
}
function prmonth (nmonth, newdow,monsize ){
line1 = line1 " " (substr(month,10*nmonth,10)) " "
line2 = line2 (wkdays) " "
line3 = line3 (makewk(1,8-newdow,newdow)) " "
line4 = line4 (makewk(9-newdow,15-newdow,1)) " "
line5 = line5 (makewk(16-newdow,22-newdow,1)) " "
line6 = line6 (makewk(23-newdow,29-newdow,1)) " "
line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " "
line8 = line8 (makewk(37-newdow,monsize,1)) " "
if (length(line3) + 22 > pagewide) {
print center(line1)
print center(line2)
print center(line3)
print center(line4)
print center(line5)
print center(line6)
print center(line7)
print center(line8)
line1 = ""
line2 = ""
line3 = ""
line4 = ""
line5 = ""
line6 = ""
line7 = ""
line8 = ""
}
}
/q/{
exit }
{
monsize=substr(days,2*1,2)
newdow=dow($1)
print center("[ picture of Snoopy goes here ]")
print center(sprintf("%d",$1) )
# January - December
for (i=1; i<13; i++) {
prmonth(i,newdow,monsize)
newdow=(monsize+newdow) %7
if (newdow == 0) newdow = 7
monsize=substr(days,2+2*i,2)
if (leap == 1 && monsize == 28) monsize = 29
}
}
|
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Go | Go | package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int // In Go identifiers that are capitalized are exported,
unexported int // while lowercase identifiers are not.
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
// For simplicity this skips several checks. It assumes the thing in the
// interface is a pointer without checking (v.Kind()==reflect.Ptr),
// it then assumes it is a structure type with two int fields
// (v.Kind()==reflect.Struct, f.Type()==reflect.TypeOf(int(0))).
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any) // get a reflect.Value
v = v.Elem() // dereference the pointer
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
// Loop through the struct fields
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i) // reflect.Value of the field
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
// "Exported", field 0, has CanSet==true so we can do:
v.Field(0).SetInt(16)
// "unexported", field 1, has CanSet==false so the following
// would fail at run-time with:
// panic: reflect: reflect.Value.SetInt using value obtained using unexported field
//v.Field(1).SetInt(43)
// However, we can bypass this restriction with the unsafe
// package once we know what type it is (so we can use the
// correct pointer type, here *int):
vp := v.Field(1).Addr() // Take the fields's address
up := unsafe.Pointer(vp.Pointer()) // … get an int value of the address and convert it "unsafely"
p := (*int)(up) // … and end up with what we want/need
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43 // effectively obj.unexported = 43
// or an incr all on one ulgy line:
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
// Note that as-per the package "unsafe" documentation,
// the return value from vp.Pointer *must* be converted to
// unsafe.Pointer in the same expression; the result is fragile.
//
// I.e. it is invalid to do:
// thisIsFragile := vp.Pointer()
// up := unsafe.Pointer(thisIsFragile)
}
// This time we'll use an external package to demonstrate that it's not
// restricted to things defined locally. We'll mess with bufio.Reader's
// interal workings by happening to know they have a non-exported
// "err error" field. Of course future versions of Go may not have this
// field or use it in the same way :).
func anotherExample() {
r := bufio.NewReader(os.Stdin)
// Do the dirty stuff in one ugly and unsafe statement:
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #C | C | #include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <FreeImage.h>
#define NUM_PARTICLES 1000
#define SIZE 800
void draw_brownian_tree(int world[SIZE][SIZE]){
int px, py; // particle values
int dx, dy; // offsets
int i;
// set the seed
world[rand() % SIZE][rand() % SIZE] = 1;
for (i = 0; i < NUM_PARTICLES; i++){
// set particle's initial position
px = rand() % SIZE;
py = rand() % SIZE;
while (1){
// randomly choose a direction
dx = rand() % 3 - 1;
dy = rand() % 3 - 1;
if (dx + px < 0 || dx + px >= SIZE || dy + py < 0 || dy + py >= SIZE){
// plop the particle into some other random location
px = rand() % SIZE;
py = rand() % SIZE;
}else if (world[py + dy][px + dx] != 0){
// bumped into something
world[py][px] = 1;
break;
}else{
py += dy;
px += dx;
}
}
}
}
int main(){
int world[SIZE][SIZE];
FIBITMAP * img;
RGBQUAD rgb;
int x, y;
memset(world, 0, sizeof world);
srand((unsigned)time(NULL));
draw_brownian_tree(world);
img = FreeImage_Allocate(SIZE, SIZE, 32, 0, 0, 0);
for (y = 0; y < SIZE; y++){
for (x = 0; x < SIZE; x++){
rgb.rgbRed = rgb.rgbGreen = rgb.rgbBlue = (world[y][x] ? 255 : 0);
FreeImage_SetPixelColor(img, x, y, &rgb);
}
}
FreeImage_Save(FIF_BMP, img, "brownian_tree.bmp", 0);
FreeImage_Unload(img);
} |
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
| #AWK | AWK | # Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
srand()
secret = ""
for (i = 1; i <= 4; ) {
digit = int(9 * rand()) + 1
if (index(secret, digit) == 0) {
secret = secret digit
i++
}
}
print "Welcome to 'Bulls and Cows'!"
print "I thought of a 4-digit number."
print "Please enter your guess."
}
iswellformed($0) {
if (calcscore($0, secret)) {
exit
}
}
function iswellformed(number, i, digit) {
if (number !~ /[1-9][1-9][1-9][1-9]/) {
print "Your guess should contain 4 digits, each from 1 to 9. Try again!"
return 0
}
for (i = 1; i <= 3; i++) {
digit = substr(number, 1, 1)
number = substr(number, 2)
if (index(number, digit) != 0) {
print "Your guess contains a digit twice. Try again!"
return 0
}
}
return 1
}
function calcscore(guess, secret, bulls, cows, i, idx) {
# Bulls = correct digits at the right position
# Cows = correct digits at the wrong position
for (i = 1; i <= 4; i++) {
idx = index(secret, substr(guess, i, 1))
if (idx == i) {
bulls++
} else if (idx > 0) {
cows++
}
}
printf("Your score for this guess: Bulls = %d, Cows = %d.", bulls, cows)
if (bulls < 4) {
printf(" Try again!\n")
} else {
printf("\nCongratulations, you win!\n")
}
return bulls == 4
} |
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
| #Pascal | Pascal |
program BurrowsWheeler;
{$mode objfpc}{$H+} // Lazarus default mode; long strings
uses SysUtils; // only for console output
const STR_BASE = 1; // first character in a Pascal string has index [1].
type TComparison = -1..1;
procedure Encode( const input : string;
out encoded : string;
out index : integer);
var
n : integer;
perm : array of integer;
i, j, k : integer;
incr, v : integer;
// Subroutine to compare rotations whose *last* letters have zero-based
// indices a, b. Returns 1, 0, -1 according as the rotation ending at a
// is >, =, < the rotation ending at b.
function CompareRotations( a, b : integer) : TComparison;
var
p, q, nrNotTested : integer;
begin
result := 0;
p := a;
q := b;
nrNotTested := n;
repeat
inc(p); if (p = n) then p := 0;
inc(q); if (q = n) then q := 0;
if (input[p + STR_BASE] = input[q + STR_BASE]) then dec( nrNotTested)
else if (input[p + STR_BASE] > input[q + STR_BASE]) then result := 1
else result := -1
until (result <> 0) or (nrNotTested = 0);
end;
begin
n := Length( input);
SetLength( perm, n);
for j := 0 to n - 1 do perm[j] := j;
// Sort string indices by comparing the associated rotations, as above.
// This is a Shell sort from Press et al., Numerical Recipes, 3rd edn, pp 422-3.
// Other sorting algorithms might be used.
incr := 1;
repeat
incr := 3*incr + 1
until (incr >= n);
repeat
incr := incr div 3;
for i := incr to n - 1 do begin
v := perm[i];
j := i;
while (j >= incr) and (CompareRotations( perm[j - incr], v) = 1) do begin
perm[j] := perm[j - incr];
dec( j, incr);
end;
perm[j] := v;
end; // for
until (incr = 1);
// Apply the sorted array to create the output.
SetLength( encoded, n);
for j := 0 to n - 1 do begin
k := perm[j];
encoded[j + STR_BASE] := input[k + STR_BASE];
if (k = n - 1) then index := j;
end;
end;
{------------------------------------------------------------------------------
Given an encoded string and the associated index, one way to rebuild
the original string is to do the following, or its equivalent:
Given Make an array Sort the array Rebuild the original string
'NNBAAA' [0] = ('N', 0) [0] = ('A', 3) Start with given index 3
index = 3 [1] = ('N', 1) [1] = ('A', 4) [3] gives 'B', next index = 2
[2] = ('B', 2) [2] = ('A', 5) [2] gives 'A', next index = 5
[3] = ('A', 3) [3] = ('B', 2) [5] gives 'N', next index = 1
[4] = ('A', 4) [4] = ('N', 0) [1] gives 'A', next index = 4
[5] = ('A', 5) [5] = ('N', 1) [4] gives 'N', next index = 0
[0] gives 'A', next index = 3
3 = start index, so stop
Result = 'BANANA'
If the original string consists of two or more repetitions of a substring,
the above method will stop when that substring has been built, e.g.
'CANCAN' will stop at 'CAN'.
We therefore need to test for the rebuilt string being too short, and if so
make enough copies of the decoded part to fill the required length.
It's possible to take the above description literally, and write a decoding
routine that uses a record type consisting of a character and an integer.
A more efficient way is to create an integer array containing only the indices,
in the above example (3, 4, 5, 2, 0, 1). A first pass counts the occurrences
of each character in the encoded string. If the character set is ['A'..'Z']
then the indices associated with 'A' are stored from [0]. If 'A' occurs a times,
the indices associated with 'B' are stored from [a]; if 'B' occurs b times,
the indices associated with 'C' are stored from [a + b]; and so on.
}
function Decode( encoded : string;
index : integer) : string;
var
charInfo : array [char] of integer;
perm : array of integer;
n, j, k : integer;
c : char;
total, prev : integer;
begin
n := Length( encoded);
// An empty encoded string will crash the code below, so trap it here.
if (n = 0) then begin
result := '';
exit;
end;
// Count the occurrences of each possible character.
for c := Low(char) to High(char) do charInfo[c] := 0;
for j := 0 to n - 1 do begin
c := encoded[j + STR_BASE];
inc( charInfo[c]);
end;
// Cumulate, i.e. charInfo[k] := sum of old charInfo from 0 to k - 1
total := 0;
prev := 0;
for c := Low(char) to High(char) do begin
inc( total, prev);
prev := CharInfo[c];
charInfo[c] := total;
end;
// Make the array "perm"
SetLength( perm, n);
for j := 0 to n - 1 do begin
c := encoded[j + STR_BASE];
k := charInfo[c];
perm[k] := j;
inc( charInfo[c]);
end;
// Apply the array "perm" to re-create the original string.
SetLength( result, n);
k := 0; // index into result
j := index;
repeat
j := perm[j];
result[k + STR_BASE] := encoded[j + STR_BASE];
inc(k);
until (j = index);
// If the original consisted of M repetitions of the same string, then
// at this point exactly 1/M of the result has been filled in.
// For M > 1 (shown by k < n), complete the result by copying the first part.
if (k < n) then begin
Assert( n mod k = 0); // we should have n = M*k
for j := k to n - 1 do result[j + STR_BASE] := result[j - k + STR_BASE];
end;
end;
procedure Test( const s : string);
var
encoded, decoded : string;
index : integer;
begin
WriteLn( '');
WriteLn( ' ' + s);
Encode( s, {out} encoded, index);
WriteLn( '---> ' + encoded);
WriteLn( ' index = ' + SysUtils.IntToStr( index));
decoded := Decode( encoded, index);
WriteLn( '---> ' + decoded);
end;
begin
Test( 'BANANA');
Test( 'CANAAN');
Test( 'CANCAN');
Test( 'appellee');
Test( 'dogwood');
Test( 'TO BE OR NOT TO BE OR WANT TO BE OR NOT?');
Test( 'SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES');
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
| #Astro | Astro | fun caesar(s, k, decode: false):
if decode:
k = 26 - k
result = ''
for i in s.uppercase() where 65 <= ord(i) <= 90:
result.push! char(ord(i) - 65 + k) mod 26 + 65
return result
let message = "The quick brown fox jumped over the lazy dogs"
let encrypted = caesar(msg, 11)
let decrypted = caesar(enc, 11, decode: true)
print(message, encrypted, decrypted, sep: '\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
| #F.23 | F# |
// A function to generate the sequence 1/n!). Nigel Galloway: May 9th., 2018
let e = Seq.unfold(fun (n,g)->Some(n,(n/g,g+1N))) (1N,1N)
|
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
| #Factor | Factor | USING: math math.factorials prettyprint sequences ;
IN: rosetta-code.calculate-e
CONSTANT: terms 20
terms <iota> [ n! recip ] map-sum >float . |
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)
| #Haskell | Haskell | import Data.List
import Control.Monad
import System.Random (randomRIO)
import Data.Char(digitToInt)
combinationsOf 0 _ = [[]]
combinationsOf _ [] = []
combinationsOf k (x:xs) = map (x:) (combinationsOf (k-1) xs) ++ combinationsOf k xs
player = do
let ps = concatMap permutations $ combinationsOf 4 ['1'..'9']
play ps where
play ps =
if null ps then
putStrLn "Unable to find a solution"
else do i <- randomRIO(0,length ps - 1)
let p = ps!!i :: String
putStrLn ("My guess is " ++ p) >> putStrLn "How many bulls and cows?"
input <- takeInput
let bc = input ::[Int]
ps' = filter((==sum bc).length. filter id. map (flip elem p))
$ filter((==head bc).length. filter id. zipWith (==) p) ps
if length ps' == 1 then putStrLn $ "The answer is " ++ head ps'
else play ps'
takeInput = do
inp <- getLine
let ui = map digitToInt $ take 2 $ filter(`elem` ['0'..'4']) inp
if sum ui > 4 || length ui /= 2 then
do putStrLn "Wrong input. Try again"
takeInput
else return ui |
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.
| #J | J | B=: + 4 100 400 -/@:<.@:%~ <:
M=: 28+ 3, (10$5$3 2),~ 0 ~:/@:= 4 100 400 | ]
R=: (7 -@| B+ 0, +/\@}:@M) |."0 1 (0,#\#~41) (]&:>: *"1 >/)~ M
H=. _3(_11&{.)\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
H=. 'SU MO TU WE TH FR SA',:"1~H
C=: H <@,"(2) 12 6 21 }."1@($,) (' ',3 ":,.#\#~31) {~ R
D=: 0 ": -@<.@%&21@+&1@[ ]\ C@]
L=: |."0 1~ +/ .(*./\@:=)"1&' '
E=: (|."0 1~ _2 <.@%~ +/ .(*./\.@:=)"1&' ')@:({."1) L
F=: 0 _1 }. 0 1 }. (2+[) E '[INSERT SNOOPY HERE]', ":@], D |
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
| #Maxima | Maxima | /* Maxima is written in Lisp and can call Lisp functions.
Use load("funcs.lisp"), or inside Maxima: */
to_lisp();
> (defun $f (a b) (+ a b))
> (to-maxima)
f(5, 6);
11 |
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
| #Mercury | Mercury | :- module test_ffi.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
% The actual FFI code begins here.
:- pragma foreign_decl("C", "#include <string.h>").
:- func strdup(string::in) = (string::out) is det.
:- pragma foreign_proc("C", strdup(S::in) = (SD::out),
[will_not_call_mercury, not_thread_safe, promise_pure],
"SD = strdup(S);").
% The actual FFI code ends here.
main(!IO) :-
io.write_string(strdup("Hello, worlds!\n"), !IO).
:- end_module test_ffi. |
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.
| #Clojure | Clojure |
(defn one []
"Function that takes no arguments and returns 1"
1)
(one); => 1
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #R | R |
cantorSet <- function() {
depth <- 6L
cs <- vector('list', depth)
cs[[1L]] <- c(0, 1)
for(k in seq_len(depth)) {
cs[[k + 1L]] <- unlist(sapply(seq_len(length(cs[[k]]) / 2L), function(j) {
p <- cs[[k]][2L] / 3
h <- 2L * (j - 1L)
c(
cs[[k]][h + 1L] + c(0, p),
cs[[k]][h + 2L] - c(p, 0)
)
}, simplify = FALSE))
}
cs
}
cantorSetGraph <- function() {
cs <- cantorSet()
u <- unlist(cs)
df <- data.frame(
x_start = u[seq_along(u) %% 2L == 1L],
x_end = u[seq_along(u) %% 2L == 0L],
depth = unlist(lapply(cs, function(e) {
l <- length(e)
n <- 0
while(l > 1) {
n <- n + 1L
l <- l / 2
}
rep(n, length(e) / 2)
}))
)
require(ggplot2)
g <- ggplot(df, aes_string(x = 'x_start', y = 'depth')) +
geom_segment(aes_string(xend = 'x_end', yend = 'depth', size = 3)) +
scale_y_continuous(trans = "reverse") +
theme(
axis.title = element_blank(),
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = 'none',
aspect.ratio = 1/5
)
list(graph = g, data = df, set = cs)
}
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Racket | Racket | #lang racket/base
;; {trans|Kotlin}}
(define current-width (make-parameter 81))
(define current-height (make-parameter 5))
(define (Cantor_set (w (current-width)) (h (current-height)))
(define lines (build-list h (λ (_) (make-bytes w (char->integer #\#)))))
(define (cantor start len index)
(let* ((seg (quotient len 3))
(seg-start (+ start seg))
(seg-end (+ seg-start seg)))
(unless (zero? seg)
(for* ((i (in-range index h))
(j (in-range seg-start seg-end)))
(bytes-set! (list-ref lines i) j (char->integer #\space)))
(cantor start seg (add1 index))
(cantor seg-end seg (add1 index)))))
(cantor 0 w 1)
lines)
(module+ main
(for-each displayln (Cantor_set)))
|
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
| #Perl | Perl | use List::Util 'reduce';
# note the use of the odd $a and $b globals
print +(reduce {$a + $b} 1 .. 10), "\n";
# first argument is really an anon function; you could also do this:
sub func { $b & 1 ? "$a $b" : "$b $a" }
print +(reduce \&func, 1 .. 10), "\n" |
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
| #Phix | Phix | with javascript_semantics
function add(integer a, b) return a + b end function
function sub(integer a, b) return a - b end function
function mul(integer a, b) return a * b end function
function reduce(integer rid, sequence s)
object res = s[1]
for i=2 to length(s) do
res = rid(res,s[i])
end for
return res
end function
?reduce(add,tagset(5))
?reduce(sub,tagset(5))
?reduce(mul,tagset(5))
|
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}
| #REXX | REXX | /*REXX program calculates the Cartesian product of two arbitrary-sized lists. */
@.= /*assign the default value to @. array*/
parse arg @.1 /*obtain the optional value of @.1 */
if @.1='' then do; @.1= "{1,2} {3,4}" /*Not specified? Then use the defaults*/
@.2= "{3,4} {1,2}" /* " " " " " " */
@.3= "{1,2} {}" /* " " " " " " */
@.4= "{} {3,4}" /* " " " " " " */
@.5= "{1,2} {3,4,5}" /* " " " " " " */
end
/* [↓] process each of the @.n values*/
do n=1 while @.n \= '' /*keep processing while there's a value*/
z= translate( space( @.n, 0), , ',') /*translate the commas to blanks. */
do #=1 until z=='' /*process each elements in first list. */
parse var z '{' x.# '}' z /*parse the list (contains elements). */
end /*#*/
$=
do i=1 for #-1 /*process the subsequent lists. */
do a=1 for words(x.i) /*obtain the elements of the first list*/
do j=i+1 for #-1 /* " " subsequent lists. */
do b=1 for words(x.j) /* " " elements of subsequent list*/
$=$',('word(x.i, a)","word(x.j, b)')' /*append partial Cartesian product ──►$*/
end /*b*/
end /*j*/
end /*a*/
end /*i*/
say 'Cartesian product of ' space(@.n) " is ───► {"substr($, 2)'}'
end /*n*/ /*stick a fork in it, we're all done. */ |
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
| #Frink | Frink | catalan[n] := binomial[2n,n]/(n+1)
for n = 0 to 15
println[catalan[n]] |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a brilliant number.
2 × 7 (14) is a brilliant number.
113 × 691 (78083) is a brilliant number.
2 × 31 (62) is semiprime, but is not a brilliant number (different number of digits in the two factors).
Task
Find and display the first 100 brilliant numbers.
For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
Stretch
Continue for larger orders of magnitude.
See also
Numbers Aplenty - Brilliant numbers
OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| #Wren | Wren | import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt
var primes = Int.primeSieve(1e7-1)
var getBrilliant = Fn.new { |digits, limit, countOnly|
var brilliant = []
var count = 0
var pow = 1
var next = Num.maxSafeInteger
for (k in 1..digits) {
var s = primes.where { |p| p > pow && p < pow * 10 }.toList
for (i in 0...s.count) {
for (j in i...s.count) {
var prod = s[i] * s[j]
if (prod < limit) {
if (countOnly) {
count = count + 1
} else {
brilliant.add(prod)
}
} else {
next = next.min(prod)
break
}
}
}
pow = pow * 10
}
return countOnly ? [count, next] : [brilliant, next]
}
System.print("First 100 brilliant numbers:")
var brilliant = getBrilliant.call(2, 10000, false)[0]
brilliant.sort()
brilliant = brilliant[0..99]
for (chunk in Lst.chunks(brilliant, 10)) Fmt.print("$4d", chunk)
System.print()
for (k in 1..12) {
var limit = 10.pow(k)
var res = getBrilliant.call(k, limit, true)
var total = res[0]
var next = res[1]
Fmt.print("First >= $,17d is $,15r in the series: $,17d", limit, total + 1, next)
} |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
Write a function that can perform brace expansion on any input string, according to the following specification.
Demonstrate how it would be used, and that it passes the four test cases given below.
Specification
In the input string, balanced pairs of braces containing comma-separated substrings (details below) represent alternations that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:
It{{em,alic}iz,erat}e{d,}
parse
―――――▶
It
⎧
⎨
⎩
⎧
⎨
⎩
em
⎫
⎬
⎭
alic
iz
⎫
⎬
⎭
erat
e
⎧
⎨
⎩
d
⎫
⎬
⎭
expand
―――――▶
Itemized
Itemize
Italicized
Italicize
Iterated
Iterate
input string
alternation tree
output (list of strings)
This tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into one branch of each alternation one comes across (see the right part of the diagram). When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.
Expansion of alternations can be more rigorously described by these rules:
a
⎧
⎨
⎩
2
⎫
⎬
⎭
1
b
⎧
⎨
⎩
X
⎫
⎬
⎭
Y
X
c
⟶
a2bXc
a2bYc
a2bXc
a1bXc
a1bYc
a1bXc
An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.
This means that multiple alternations inside the same branch are cumulative (i.e. the complete list of alternatives produced by a branch is the string-concatenating "Cartesian product" of its parts).
All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate (i.e. "lexicographically" with regard to the alternations).
The alternatives produced by the root branch constitute the final output.
Parsing the input string involves some additional complexity to deal with escaped characters and "incomplete" brace pairs:
a\\{\\\{b,c\,d}
⟶
a\\
⎧
⎨
⎩
\\\{b
⎫
⎬
⎭
c\,d
{a,b{c{,{d}}e}f
⟶
{a,b{c
⎧
⎨
⎩
⎫
⎬
⎭
{d}
e}f
An unescaped backslash which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.
Balanced brace pairs are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped comma is associated with the innermost brace pair that contains it (if any). With that in mind:
Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.
Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.
For every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for how to implement it. Try to come up with a solution that is idiomatic in your programming language. (See #Perl for a reference implementation.)
Test Cases
Input
(single string)
Ouput
(list/array of strings)
~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Brace_expansion_using_ranges
| #C.2B.2B | C++ | #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
} // namespace detail
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the representation of N in base B has all equal digits.
E.G.
1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1.
4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same.
5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same.
6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same.
7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same.
8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same.
and so on...
All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4.
More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2
Task
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
the first 20 Brazilian numbers;
the first 20 odd Brazilian numbers;
the first 20 prime Brazilian numbers;
See also
OEIS:A125134 - Brazilian numbers
OEIS:A257521 - Odd Brazilian numbers
OEIS:A085104 - Prime Brazilian numbers
| #AppleScript | AppleScript | on isBrazilian(n)
repeat with b from 2 to n - 2
set d to n mod b
set temp to n div b
repeat while (temp mod b = d) -- ((temp > 0) and (temp mod b = d))
set temp to temp div b
end repeat
if (temp = 0) then return true
end repeat
return false
end isBrazilian
on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
-- Task code:
on runTask()
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set collector to {}
set n to 1
repeat until ((count collector) is 20)
if (isBrazilian(n)) then set end of collector to n
set n to n + 1
end repeat
set end of output to "First 20 Brazilian numbers: " & linefeed & collector
set collector to {}
set n to 1
repeat until ((count collector) is 20)
if (isBrazilian(n)) then set end of collector to n
set n to n + 2
end repeat
set end of output to "First 20 odd Brazilian numbers: " & linefeed & collector
set collector to {}
if (isBrazilian(2)) then set end of collector to 2
set n to 3
repeat until ((count collector) is 20)
if (isPrime(n)) and (isBrazilian(n)) then set end of collector to n
set n to n + 2
end repeat
set end of output to "First 20 prime Brazilian numbers: " & linefeed & collector
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end runTask
return runTask() |
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
| #BaCon | BaCon | DECLARE month$[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }
DECLARE month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
year$ = "1969"
' Leap year
INCR month[1], IIF(MOD(VAL(year$), 4) = 0 OR MOD(VAL(year$), 100) = 0 AND MOD(VAL(year$), 400) <> 0, 1, 0)
PRINT ALIGN$("[SNOOPY HERE]", 132, 2)
PRINT ALIGN$(year$, 132, 2)
FOR nr = 0 TO 11
row = 3
GOTOXY 1+(nr %6)*22, row+(nr/6)*9
PRINT ALIGN$(month$[nr], 21, 2);
INCR row
GOTOXY 1+(nr %6)*22, row+(nr/6)*9
PRINT ALIGN$("Mo Tu We Th Fr Sa Su", 21, 2);
INCR row
' Each day
FOR day = 1 TO month[nr]
' Zeller
J = VAL(LEFT$(year$, 2))
K = VAL(MID$(year$, 3, 2))
m = nr+1
IF nr < 2 THEN
INCR m, 12
DECR K
END IF
h = (day + ((m+1)*26)/10 + K + (K/4) + (J/4) + 5*J)
daynr = MOD(h, 7) - 2
IF daynr < 0 THEN INCR daynr, 7
IF daynr = 0 AND day > 1 THEN INCR row
GOTOXY 1+(nr %6)*22+daynr*3, row+(nr/6)*9
PRINT day;
NEXT
NEXT |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
(x := foo(1,2,3)).print() # create and show a foo
printf("Fieldnames of foo x : ") # show fieldnames
every printf(" %i",fieldnames(x)) # __s (self), __m (methods), vars
printf("\n")
printf("var 1 of foo x = %i\n", x.var1) # read var1 from outside x
x.var1 := -1 # change var1 from outside x
x.print() # show we changed it
end
class foo(var1,var2,var3) # class with no set/read methods
method print()
printf("foo var1=%i, var2=%i, var3=%i\n",var1,var2,var3)
end
end |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| #J | J | import java.lang.reflect.*;
class Example {
private String _name;
public Example(String name) { _name = name; }
public String toString() { return "Hello, I am " + _name; }
}
public class BreakPrivacy {
public static final void main(String[] args) throws Exception {
Example foo = new Example("Eric");
for (Field f : Example.class.getDeclaredFields()) {
if (f.getName().equals("_name")) {
// make it accessible
f.setAccessible(true);
// get private field
System.out.println(f.get(foo));
// set private field
f.set(foo, "Edith");
System.out.println(foo);
break;
}
}
}
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #C.23 | C# | using System;
using System.Drawing;
namespace BrownianTree
{
class Program
{
static Bitmap BrownianTree(int size, int numparticles)
{
Bitmap bmp = new Bitmap(size, size);
Rectangle bounds = new Rectangle { X = 0, Y = 0, Size = bmp.Size };
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Black);
}
Random rnd = new Random();
bmp.SetPixel(rnd.Next(size), rnd.Next(size), Color.White);
Point pt = new Point(), newpt = new Point();
for (int i = 0; i < numparticles; i++)
{
pt.X = rnd.Next(size);
pt.Y = rnd.Next(size);
do
{
newpt.X = pt.X + rnd.Next(-1, 2);
newpt.Y = pt.Y + rnd.Next(-1, 2);
if (!bounds.Contains(newpt))
{
pt.X = rnd.Next(size);
pt.Y = rnd.Next(size);
}
else if (bmp.GetPixel(newpt.X, newpt.Y).R > 0)
{
bmp.SetPixel(pt.X, pt.Y, Color.White);
break;
}
else
{
pt = newpt;
}
} while (true);
}
return bmp;
}
static void Main(string[] args)
{
BrownianTree(300, 3000).Save("browniantree.png");
}
}
} |
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
| #BASIC | BASIC | DEFINT A-Z
DIM secret AS STRING
DIM guess AS STRING
DIM c AS STRING
DIM bulls, cows, guesses, i
RANDOMIZE TIMER
DO WHILE LEN(secret) < 4
c = CHR$(INT(RND * 10) + 48)
IF INSTR(secret, c) = 0 THEN secret = secret + c
LOOP
guesses = 0
DO
INPUT "Guess a 4-digit number with no duplicate digits: "; guess
guess = LTRIM$(RTRIM$(guess))
IF LEN(guess) = 0 THEN EXIT DO
IF LEN(guess) <> 4 OR VAL(guess) = 0 THEN
PRINT "** You should enter 4 numeric digits!"
GOTO looper
END IF
bulls = 0: cows = 0: guesses = guesses + 1
FOR i = 1 TO 4
c = MID$(secret, i, 1)
IF MID$(guess, i, 1) = c THEN
bulls = bulls + 1
ELSEIF INSTR(guess, c) THEN
cows = cows + 1
END IF
NEXT i
PRINT bulls; " bulls, "; cows; " cows"
IF guess = secret THEN
PRINT "You won after "; guesses; " guesses!"
EXIT DO
END IF
looper:
LOOP |
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
| #Perl | Perl | use utf8;
binmode STDOUT, ":utf8";
use constant STX => '👍 ';
sub transform {
my($s) = @_;
my($t);
warn "String can't contain STX character." and exit if $s =~ /STX/;
$s = STX . $s;
$t .= substr($_,-1,1) for sort map { rotate($s,$_) } 1..length($s);
return $t;
}
sub rotate { my($s,$n) = @_; join '', (split '', $s)[$n..length($s)-1, 0..$n-1] }
sub ɯɹoɟsuɐɹʇ {
my($s) = @_;
my @s = split '', $s;
my @t = sort @s;
map { @t = sort map { $s[$_] . $t[$_] } 0..length($s)-1 } 1..length($s)-1;
for (@t) {
next unless /${\(STX)}$/; # interpolate the constant
chop $_ and return $_
}
}
for $phrase (qw<BANANA dogwood SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES>,
'TO BE OR NOT TO BE OR WANT TO BE OR NOT?') {
push @res, 'Original: '. $phrase;
push @res, 'Transformed: '. transform $phrase;
push @res, 'Inverse transformed: '. ɯɹoɟsuɐɹʇ transform $phrase;
push @res, '';
}
print join "\n", @res; |
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
| #AutoHotkey | AutoHotkey | n=2
s=HI
t:=&s
While *t
o.=Chr(Mod(*t-65+n,26)+65),t+=2
MsgBox % o |
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
| #FOCAL | FOCAL | 1.1 S K=1; S E=0
1.2 F X=1,10; D 2
1.3 Q
2.1 S E=E+1/K
2.2 S K=K*X
2.3 T %2,X,%6.5,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
| #Forth | Forth | 100 constant #digits
: int-array create cells allot does> swap cells + ;
#digits 1+ int-array e-digits[]
: init-e ( -- )
[ #digits 1+ ] literal 0 DO
1 i e-digits[] !
LOOP
." = 2." ;
: .e ( -- )
init-e
[ #digits 1- ] literal 0 DO
0 \ carry
0 #digits DO
i e-digits[] dup @ 10 * rot + i 2 + /mod -rot swap !
-1 +LOOP
0 .r
LOOP ;
|
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)
| #J | J | require'misc'
poss=:1+~.4{."1 (i.!9)A.i.9
fmt=: ' ' -.~ ":
play=:3 :0
while.1<#poss=.poss do.
smoutput'guessing ',fmt guess=.({~ ?@#)poss
bc=.+/\_".prompt 'how many bull and cows? '
poss=.poss #~({.bc)=guess+/@:="1 poss
poss=.poss #~({:bc)=guess+/@e."1 poss
end.
if.#poss do.
'the answer is ',fmt,poss
else.
'no valid possibilities'
end.
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.