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/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Tcl | Tcl | package require Tcl 8.5
# Generate random point at specified distance from the centre
proc getPoint {range from to} {
set r2 [expr {$range / 2}]
set f2 [expr {$from ** 2}]
set t2 [expr {$to ** 2}]
while 1 {
set x [expr {int($range * rand())}]
set y [expr {int($range * rand())}]
set d2 [expr {($x-$r2)**2 + ($y-$r2)**2}]
if {$d2 >= $f2 && $d2 <= $t2} {
return [list $y $x]
}
}
}
# Make somewhere to store the counters
set ary [lrepeat 31 [lrepeat 31 0]]
# Generate 100 random points
for {set i 0} {$i < 100} {incr i} {
set location [getPoint 31 10 15]
# Increment the counter for the point
lset ary $location [expr {1 + [lindex $ary $location]}]
}
# Simple renderer
foreach line $ary {
foreach c $line {
puts -nonewline [expr {$c == 0 ? " " : $c > 9 ? "X" : $c}]
}
puts ""
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Avail | Avail | If year = 1999 then [Print: "Party!";];
If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];
If breed = "Abyssinian" then [score := 150;]
else if breed = "Birman" then [score := 70;]
else [score := 45;];
Unless char = ¢X then [Print: "character was not an x";]; |
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #Go | Go | package main
import (
"fmt"
"regexp"
"strings"
)
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:]) // this can only contain ASCII characters
if m == "" {
return s
}
splits := strings.Split(m, ".")
ip := splits[0]
if len(ip) > period {
pi := reverse(ip)
for i := (len(ip) - 1) / period * period; i >= period; i -= period {
pi = pi[:i] + sep + pi[i:]
}
ip = reverse(pi)
}
if strings.Contains(m, ".") {
dp := splits[1]
if len(dp) > period {
for i := (len(dp) - 1) / period * period; i >= period; i -= period {
dp = dp[:i] + sep + dp[i:]
}
}
ip += "." + dp
}
return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)
}
func main() {
tests := [...]string{
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-in Aus$+1411.8millions",
"===US$0017440 millions=== (in 2000 dollars)",
"123.e8000 is pretty big.",
"The land area of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000±100 millions.",
"6/9/1946 was a good year for some.",
}
fmt.Println(commatize(tests[0], 0, 2, "*"))
fmt.Println(commatize(tests[1], 0, 3, "-"))
fmt.Println(commatize(tests[2], 0, 4, "__"))
fmt.Println(commatize(tests[3], 0, 5, " "))
fmt.Println(commatize(tests[4], 0, 3, "."))
for _, test := range tests[5:] {
fmt.Println(commatize(test, 0, 3, ","))
}
} |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #Arturo | Arturo | allEqual?: function [lst] -> 1 = size unique lst
ascending?: function [lst] -> lst = sort lst
lists: [
["abc" "abc" "abc"]
["abc" "abd" "abc"]
["abc" "abd" "abe"]
["abc" "abe" "abd"]
]
loop lists 'l [
print ["list:" l]
print ["allEqual?" allEqual? l]
print ["ascending?" ascending? l "\n"]
] |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #AWK | AWK |
# syntax: GAWK -f COMPARE_A_LIST_OF_STRINGS.AWK
BEGIN {
main("AA,BB,CC")
main("AA,AA,AA")
main("AA,CC,BB")
main("AA,ACB,BB,CC")
main("single_element")
exit(0)
}
function main(list, arr,i,n,test1,test2) {
test1 = 1 # elements are identical
test2 = 1 # elements are in ascending order
n = split(list,arr,",")
printf("\nlist:")
for (i=1; i<=n; i++) {
printf(" %s",arr[i])
if (i > 1) {
if (arr[i-1] != arr[i]) {
test1 = 0 # elements are not identical
}
if (arr[i-1] >= arr[i]) {
test2 = 0 # elements are not in ascending order
}
}
}
printf("\n%d\n%d\n",test1,test2)
}
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #11l | 11l | F quibble(words)
R S words.len
0
‘{}’
1
‘{’words[0]‘}’
E
‘{’words[0.<(len)-1].join(‘, ’)‘ and ’words.last‘}’
print(quibble([‘’] * 0))
print(quibble([‘ABC’]))
print(quibble([‘ABC’, ‘DEF’]))
print(quibble([‘ABC’, ‘DEF’, ‘G’, ‘H’])) |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S
{\displaystyle S}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:
Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,
S
{\displaystyle S}
is
{
i
c
e
d
,
j
a
m
,
p
l
a
i
n
}
{\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}
,
|
S
|
=
3
{\displaystyle |S|=3}
, and
k
=
2
{\displaystyle k=2}
.)
A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.
Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.
Also note that doughnut can also be spelled donut.
Task
Write a function/program/routine/.. to generate all the combinations with repetitions of
n
{\displaystyle n}
types of things taken
k
{\displaystyle k}
at a time and use it to show an answer to the doughnut example above.
For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.
References
k-combination with repetitions
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #11l | 11l | F combsReps(lst, k)
T Ty = T(lst[0])
I k == 0
R [[Ty]()]
I lst.empty
R [[Ty]]()
R combsReps(lst, k - 1).map(x -> @lst[0] [+] x) [+] combsReps(lst[1..], k)
print(combsReps([‘iced’, ‘jam’, ‘plain’], 2))
print(combsReps(Array(1..10), 3).len) |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #11l | 11l | F perm(=n, p)
BigInt r = 1
V k = n - p
L n > k
r *= n--
R r
F comb(n, =k)
V r = perm(n, k)
L k > 0
r I/= k--
R r
L(i) 1..11
print(‘P(12,’i‘) = ’perm(12, i))
L(i) (10.<60).step(10)
print(‘C(60,’i‘) = ’comb(60, i)) |
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer).
Task[edit]
Create a lexical analyzer for the simple programming language specified below. The
program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a lexer module/library/class, it would be great
if two versions of the solution are provided: One without the lexer module, and one with.
Input Specification
The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens:
Operators
Name
Common name
Character sequence
Op_multiply
multiply
*
Op_divide
divide
/
Op_mod
mod
%
Op_add
plus
+
Op_subtract
minus
-
Op_negate
unary minus
-
Op_less
less than
<
Op_lessequal
less than or equal
<=
Op_greater
greater than
>
Op_greaterequal
greater than or equal
>=
Op_equal
equal
==
Op_notequal
not equal
!=
Op_not
unary not
!
Op_assign
assignment
=
Op_and
logical and
&&
Op_or
logical or
¦¦
The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.
Symbols
Name
Common name
Character
LeftParen
left parenthesis
(
RightParen
right parenthesis
)
LeftBrace
left brace
{
RightBrace
right brace
}
Semicolon
semi-colon
;
Comma
comma
,
Keywords
Name
Character sequence
Keyword_if
if
Keyword_else
else
Keyword_while
while
Keyword_print
print
Keyword_putc
putc
Identifiers and literals
These differ from the the previous tokens, in that each occurrence of them has a value associated with it.
Name
Common name
Format description
Format regex
Value
Identifier
identifier
one or more letter/number/underscore characters, but not starting with a number
[_a-zA-Z][_a-zA-Z0-9]*
as is
Integer
integer literal
one or more digits
[0-9]+
as is, interpreted as a number
Integer
char literal
exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes
'([^'\n]|\\n|\\\\)'
the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n'
String
string literal
zero or more characters (anything except newline or double quote), enclosed by double quotes
"[^"\n]*"
the characters without the double quotes and with escape sequences converted
For char and string literals, the \n escape sequence is supported to represent a new-line character.
For char and string literals, to represent a backslash, use \\.
No other special sequences are supported. This means that:
Char literals cannot represent a single quote character (value 39).
String literals cannot represent strings containing double quote characters.
Zero-width tokens
Name
Location
End_of_input
when the end of the input stream is reached
White space
Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.
"Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =).
Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge.
This means: keywords, identifiers, and integer literals.
e.g. ifprint is recognized as an identifier, instead of the keywords if and print.
e.g. 42fred is invalid, and neither recognized as a number nor an identifier.
Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value).
e.g. & & is invalid, and not interpreted as the && operator.
For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:
if ( p /* meaning n is prime */ ) {
print ( n , " " ) ;
count = count + 1 ; /* number of primes found so far */
}
if(p){print(n," ");count=count+1;}
Complete list of token names
End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract
Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal
Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if
Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen
LeftBrace RightBrace Semicolon Comma Identifier Integer
String
Output Format
The program output should be a sequence of lines, each consisting of the following whitespace-separated fields:
the line number where the token starts
the column number where the token starts
the token name
the token value (only for Identifier, Integer, and String tokens)
the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.
This task is intended to be used as part of a pipeline, with the other compiler tasks - for example:
lex < hello.t | parse | gen | vm
Or possibly:
lex hello.t lex.out
parse lex.out parse.out
gen parse.out gen.out
vm gen.out
This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.
Diagnostics
The following error conditions should be caught:
Error
Example
Empty character constant
''
Unknown escape sequence.
\r
Multi-character constant.
'xx'
End-of-file in comment. Closing comment characters not found.
End-of-file while scanning string literal. Closing string character not found.
End-of-line while scanning string literal. Closing string character not found before end-of-line.
Unrecognized character.
|
Invalid number. Starts like a number, but ends in non-numeric characters.
123abc
Test Cases
Input
Output
Test Case 1:
/*
Hello world
*/
print("Hello, World!\n");
4 1 Keyword_print
4 6 LeftParen
4 7 String "Hello, World!\n"
4 24 RightParen
4 25 Semicolon
5 1 End_of_input
Test Case 2:
/*
Show Ident and Integers
*/
phoenix_number = 142857;
print(phoenix_number, "\n");
4 1 Identifier phoenix_number
4 16 Op_assign
4 18 Integer 142857
4 24 Semicolon
5 1 Keyword_print
5 6 LeftParen
5 7 Identifier phoenix_number
5 21 Comma
5 23 String "\n"
5 27 RightParen
5 28 Semicolon
6 1 End_of_input
Test Case 3:
/*
All lexical tokens - not syntactically correct, but that will
have to wait until syntax analysis
*/
/* Print */ print /* Sub */ -
/* Putc */ putc /* Lss */ <
/* If */ if /* Gtr */ >
/* Else */ else /* Leq */ <=
/* While */ while /* Geq */ >=
/* Lbrace */ { /* Eq */ ==
/* Rbrace */ } /* Neq */ !=
/* Lparen */ ( /* And */ &&
/* Rparen */ ) /* Or */ ||
/* Uminus */ - /* Semi */ ;
/* Not */ ! /* Comma */ ,
/* Mul */ * /* Assign */ =
/* Div */ / /* Integer */ 42
/* Mod */ % /* String */ "String literal"
/* Add */ + /* Ident */ variable_name
/* character literal */ '\n'
/* character literal */ '\\'
/* character literal */ ' '
5 16 Keyword_print
5 40 Op_subtract
6 16 Keyword_putc
6 40 Op_less
7 16 Keyword_if
7 40 Op_greater
8 16 Keyword_else
8 40 Op_lessequal
9 16 Keyword_while
9 40 Op_greaterequal
10 16 LeftBrace
10 40 Op_equal
11 16 RightBrace
11 40 Op_notequal
12 16 LeftParen
12 40 Op_and
13 16 RightParen
13 40 Op_or
14 16 Op_subtract
14 40 Semicolon
15 16 Op_not
15 40 Comma
16 16 Op_multiply
16 40 Op_assign
17 16 Op_divide
17 40 Integer 42
18 16 Op_mod
18 40 String "String literal"
19 16 Op_add
19 40 Identifier variable_name
20 26 Integer 10
21 26 Integer 92
22 26 Integer 32
23 1 End_of_input
Test Case 4:
/*** test printing, embedded \n and comments with lots of '*' ***/
print(42);
print("\nHello World\nGood Bye\nok\n");
print("Print a slash n - \\n.\n");
2 1 Keyword_print
2 6 LeftParen
2 7 Integer 42
2 9 RightParen
2 10 Semicolon
3 1 Keyword_print
3 6 LeftParen
3 7 String "\nHello World\nGood Bye\nok\n"
3 38 RightParen
3 39 Semicolon
4 1 Keyword_print
4 6 LeftParen
4 7 String "Print a slash n - \\n.\n"
4 33 RightParen
4 34 Semicolon
5 1 End_of_input
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #ALGOL_W | ALGOL W | begin
%lexical analyser %
% Algol W strings are limited to 256 characters in length so we limit source lines %
% and tokens to 256 characters %
integer lineNumber, columnNumber;
string(256) line;
string(256) tkValue;
integer tkType, tkLine, tkColumn, tkLength, tkIntegerValue;
logical tkTooLong;
string(1) currChar;
string(1) newlineChar;
integer LINE_WIDTH, MAX_TOKEN_LENGTH, MAXINTEGER_OVER_10, MAXINTEGER_MOD_10;
integer tOp_multiply , tOp_divide , tOp_mod , tOp_add
, tOp_subtract , tOp_negate , tOp_less , tOp_lessequal
, tOp_greater , tOp_greaterequal , tOp_equal , tOp_notequal
, tOp_not , tOp_assign , tOp_and , tOp_or
, tLeftParen , tRightParen , tLeftBrace , tRightBrace
, tSemicolon , tComma , tKeyword_if , tKeyword_else
, tKeyword_while , tKeyword_print , tKeyword_putc , tIdentifier
, tInteger , tString , tEnd_of_input , tComment
;
string(16) array tkName ( 1 :: 32 );
% reports an error %
procedure lexError( string(80) value message ); begin
integer errorPos;
write( i_w := 1, s_w := 0, "**** Error at(", lineNumber, ",", columnNumber, "): " );
errorPos := 0;
while errorPos < 80 and message( errorPos // 1 ) not = "." do begin
writeon( s_w := 0, message( errorPos // 1 ) );
errorPos := errorPos + 1
end while_not_at_end_of_message ;
writeon( s_w := 0, "." )
end lexError ;
% gets the next source character %
procedure nextChar ; begin
if columnNumber = LINE_WIDTH then begin
currChar := newlineChar;
columnNumber := columnNumber + 1
end
else if columnNumber > LINE_WIDTH then begin
readcard( line );
columnNumber := 1;
if not XCPNOTED(ENDFILE) then lineNumber := lineNumber + 1;
currChar := line( 0 // 1 )
end
else begin
currChar := line( columnNumber // 1 );
columnNumber := columnNumber + 1
end
end nextChar ;
% gets the next token, returns the token type %
integer procedure nextToken ; begin
% returns true if currChar is in the inclusive range lowerValue to upperValue %
% false otherwise %
logical procedure range( string(1) value lowerValue, upperValue ) ; begin
currChar >= lowerValue and currChar <= upperValue
end range ;
% returns true if the current character can start an identifier, false otherwise %
logical procedure identifierStartChar ; begin
currChar = "_" or range( "a", "z" ) or range( "A", "Z" )
end identifierStartChar ;
% add the current character to the token and get the next %
procedure addAndNextChar ; begin
if tkLength >= MAX_TOKEN_LENGTH then tkTooLong := true
else begin
tkValue( tkLength // 1 ) := currChar;
tkLength := tkLength + 1
end if_symbol_not_too_long ;
nextChar
end % addAndNextChar % ;
% handle a single character token %
procedure singleCharToken( integer value tokenType ) ; begin
tkType := tokenType;
nextChar
end singleCharToken ;
% handle a doubled character token: && or || %
procedure doubleCharToken( integer value tokenType ) ; begin
string(1) firstChar;
firstChar := currChar;
tkType := tokenType;
nextChar;
if currChar = firstChar then nextChar
else % the character wasn't doubled % lexError( "Unrecognised character." );
end singleCharToken ;
% handle an operator or operator= token %
procedure opOrOpEqual( integer value opToken, opEqualToken ) ; begin
tkType := opToken;
nextChar;
if currChar = "=" then begin
% have operator= %
tkType := opEqualToken;
nextChar
end if_currChar_is_equal ;
end opOrOpEqual ;
% handle a / operator or /* comment %
procedure divideOrComment ; begin
tkType := tOp_divide;
nextChar;
if currChar = "*" then begin
% have a comment %
logical moreComment;
tkType := tComment;
moreComment := true;
while moreComment do begin
nextChar;
while currChar not = "*" and not XCPNOTED(ENDFILE) do nextChar;
while currChar = "*" and not XCPNOTED(ENDFILE) do nextChar;
moreComment := ( currChar not = "/" and not XCPNOTED(ENDFILE) )
end while_more_comment ;
if not XCPNOTED(ENDFILE)
then nextChar
else lexError( "End-of-file in comment." )
end if_currChar_is_star ;
end divideOrComment ;
% handle an indentifier or keyword %
procedure identifierOrKeyword ; begin
tkType := tIdentifier;
while identifierStartChar or range( "0", "9" ) do addAndNextChar;
% there are only 5 keywords, so we just test each in turn here %
if tkValue = "if" then tkType := tKeyword_if
else if tkValue = "else" then tkType := tKeyword_else
else if tkValue = "while" then tkType := tKeyword_while
else if tkValue = "print" then tkType := tKeyword_print
else if tkValue = "putc" then tkType := tKeyword_putc;
if tkType not = tIdentifier then tkValue := "";
end identifierOrKeyword ;
% handle an integer literal %
procedure integerLiteral ; begin
logical overflowed;
integer digit;
overflowed := false;
tkType := tInteger;
while range( "0", "9" ) do begin
digit := ( decode( currChar ) - decode( "0" ) );
if tkIntegerValue > MAXINTEGER_OVER_10 then overflowed := true
else if tkIntegerValue = MAXINTEGER_OVER_10
and digit > MAXINTEGER_MOD_10 then overflowed := true
else begin
tkIntegerValue := tkIntegerValue * 10;
tkIntegerValue := tkIntegerValue + digit;
end;
nextChar
end while_have_a_digit ;
if overflowed then lexError( "Number too large." );
if identifierStartChar then lexError( "Number followed by letter or underscore." );
end integerLiteral ;
% handle a char literal %
procedure charLiteral ; begin
nextChar;
if currChar = "'" or currChar = newlineChar then lexError( "Invalid character constant." )
else if currChar = "\" then begin
% have an escape %
nextChar;
if currChar = "n" then currChar := newlineChar
else if currChar not = "\" then lexError( "Unknown escape sequence." )
end;
tkType := tInteger;
tkIntegerValue := decode( currChar );
% should have a closing quoute next %
nextChar;
if currChar not = "'"
then lexError( "Multi-character constant." )
else nextChar
end charLiteral ;
% handle a string literal %
procedure stringLiteral ; begin
tkType := tString;
tkValue( 0 // 1 ) := currChar;
tkLength := 1;
nextChar;
while currChar not = """" and currChar not = newlineChar and not XCPNOTED(ENDFILE) do addAndNextChar;
if currChar = newlineChar then lexError( "End-of-line while scanning string literal." )
else if XCPNOTED(ENDFILE) then lexError( "End-of-file while scanning string literal." )
else % currChar must be """" % addAndNextChar
end stringLiteral ;
while begin
% skip white space %
while ( currChar = " " or currChar = newlineChar ) and not XCPNOTED(ENDFILE) do nextChar;
% get the token %
tkLine := lineNumber;
tkColumn := columnNumber;
tkValue := "";
tkLength := 0;
tkIntegerValue := 0;
tkTooLong := false;
if XCPNOTED(ENDFILE) then tkType := tEnd_of_input
else if currChar = "*" then singleCharToken( tOp_multiply )
else if currChar = "/" then divideOrComment
else if currChar = "%" then singleCharToken( tOp_mod )
else if currChar = "+" then singleCharToken( tOp_add )
else if currChar = "-" then singleCharToken( tOp_subtract )
else if currChar = "<" then opOrOpEqual( tOp_less, tOp_lessequal )
else if currChar = ">" then opOrOpEqual( tOp_greater, tOp_greaterequal )
else if currChar = "=" then opOrOpEqual( tOp_assign, tOp_equal )
else if currChar = "!" then opOrOpEqual( tOp_not, tOp_notequal )
else if currChar = "&" then doubleCharToken( tOp_and )
else if currChar = "|" then doubleCharToken( tOp_or )
else if currChar = "(" then singleCharToken( tLeftParen )
else if currChar = ")" then singleCharToken( tRightParen )
else if currChar = "{" then singleCharToken( tLeftBrace )
else if currChar = "}" then singleCharToken( tRightBrace )
else if currChar = ";" then singleCharToken( tSemicolon )
else if currChar = "," then singleCharToken( tComma )
else if identifierStartChar then identifierOrKeyword
else if range( "0", "9" ) then integerLiteral
else if currChar = "'" then charLiteral
else if currChar = """" then stringLiteral
else begin
lexError( "Unrecognised character." );
singleCharToken( tComment )
end ;
% continue until we get something other than a comment %
tkType = tComment
end do begin end;
if tkTooLong then if tkType = tString
then lexError( "String literal too long." )
else lexError( "Identifier too long." );
tkType
end nextToken ;
% outputs the current token %
procedure writeToken ; begin
write( i_w := 5, s_w := 2, tkLine, tkColumn, tkName( tkType ) );
if tkType = tInteger then writeon( i_w := 11, tkIntegerValue )
else if tkLength > 0 then begin
writeon( " " );
for tkPos := 0 until tkLength - 1 do writeon( s_w := 0, tkValue( tkPos // 1 ) );
end
end writeToken ;
LINE_WIDTH := 256; MAXINTEGER_MOD_10 := MAXINTEGER rem 10;
MAX_TOKEN_LENGTH := 256; MAXINTEGER_OVER_10 := MAXINTEGER div 10;
newlineChar := code( 10 );
tOp_multiply := 1; tkName( tOp_multiply ) := "Op_multiply";
tOp_divide := 2; tkName( tOp_divide ) := "Op_divide";
tOp_mod := 3; tkName( tOp_mod ) := "Op_mod";
tOp_add := 4; tkName( tOp_add ) := "Op_add";
tOp_subtract := 5; tkName( tOp_subtract ) := "Op_subtract";
tOp_negate := 6; tkName( tOp_negate ) := "Op_negate";
tOp_less := 7; tkName( tOp_less ) := "Op_less";
tOp_lessequal := 8; tkName( tOp_lessequal ) := "Op_lessequal";
tOp_greater := 9; tkName( tOp_greater ) := "Op_greater";
tOp_greaterequal := 10; tkName( tOp_greaterequal ) := "Op_greaterequal";
tOp_equal := 11; tkName( tOp_equal ) := "Op_equal";
tOp_notequal := 12; tkName( tOp_notequal ) := "Op_notequal";
tOp_not := 13; tkName( tOp_not ) := "Op_not";
tOp_assign := 14; tkName( tOp_assign ) := "Op_assign";
tOp_and := 15; tkName( tOp_and ) := "Op_and";
tOp_or := 16; tkName( tOp_or ) := "Op_or";
tLeftParen := 17; tkName( tLeftParen ) := "LeftParen";
tRightParen := 18; tkName( tRightParen ) := "RightParen";
tLeftBrace := 19; tkName( tLeftBrace ) := "LeftBrace";
tRightBrace := 20; tkName( tRightBrace ) := "RightBrace";
tSemicolon := 21; tkName( tSemicolon ) := "Semicolon";
tComma := 22; tkName( tComma ) := "Comma";
tKeyword_if := 23; tkName( tKeyword_if ) := "Keyword_if";
tKeyword_else := 24; tkName( tKeyword_else ) := "Keyword_else";
tKeyword_while := 25; tkName( tKeyword_while ) := "Keyword_while";
tKeyword_print := 26; tkName( tKeyword_print ) := "Keyword_print";
tKeyword_putc := 27; tkName( tKeyword_putc ) := "Keyword_putc";
tIdentifier := 28; tkName( tIdentifier ) := "Identifier";
tInteger := 29; tkName( tInteger ) := "Integer";
tString := 30; tkName( tString ) := "String";
tEnd_of_input := 31; tkName( tEnd_of_input ) := "End_of_input";
tComment := 32; tkName( tComment ) := "Comment";
% allow the program to continue after reaching end-of-file %
ENDFILE := EXCEPTION( false, 1, 0, false, "EOF" );
% ensure the first call to nextToken reads the first line %
lineNumber := 0;
columnNumber := LINE_WIDTH + 1;
currChar := " ";
% get and print all tokens from standard input %
while nextToken not = tEnd_of_input do writeToken;
writeToken
end. |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Amazing_Hopper | Amazing Hopper |
#defn main(_V_,_N_) #RAND, main:, V#RNDV=1,_V_={#VOID}, \
_N_=0,totalarg,mov(_N_), \
LOOPGETARG_#RNDV:, {[ V#RNDV ]},push(_V_),++V#RNDV,\
{_N_,V#RNDV},jle(LOOPGETARG_#RNDV),clear(V#RNDV)
|
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #AppleScript | AppleScript |
#!/usr/bin/env osascript
-- Print first argument
on run argv
return (item 1 of argv)
end run
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #8086_Assembly | 8086 Assembly | MOV AX, 4C00h ; go back to DOS
INT 21h ; BIOS interrupt 21 base 16 |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* comments multi lines
end comments
*/
// comment end of ligne
|
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Input format:
Given the following program:
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
The output from the Code generator is a virtual assembly code program:
Output from gen, input to VM
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
The first line of the input specifies the datasize required and the number of constant
strings, in the order that they are reference via the code.
The data can be stored in a separate array, or the data can be stored at the beginning of
the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if
referenced at address 2.
If there are one or more constant strings, they come next. The code refers to these
strings by their index. The index starts at 0. So if there are 3 strings, and the code
wants to reference the 3rd string, 2 will be used.
Next comes the actual virtual assembly code. The first number is the code address of that
instruction. After that is the instruction mnemonic, followed by optional operands,
depending on the instruction.
Registers:
sp:
the stack pointer - points to the next top of stack. The stack is a 32-bit integer
array.
pc:
the program counter - points to the current instruction to be performed. The code is an
array of bytes.
Data:
data
string pool
Instructions:
Each instruction is one byte. The following instructions also have a 32-bit integer
operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
Print the word at stack top as a character.
prtc
Print the word at stack top as an integer.
prti
Stack top points to an index into the string pool. Print that entry.
prts
Unconditional stop.
halt
A simple example virtual machine
def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
AST Interpreter task
| #J | J | (opcodes)=: opcodes=: ;:{{)n
fetch store push add sub mul div mod lt gt le ge
eq ne and or neg not jmp jz prtc prts prti halt
}}-.LF
unpack=: {{
lines=. <;._2 y
'ds0 ds s0 s'=.;:0{::lines
assert.'Datasize:Strings:'-:ds0,s0
vars=: (".ds)#0
strings=: rplc&('\\';'\';'\n';LF)L:0 '"'-.L:0~(1+i.".s){lines
object=: ;xlate L:1 (;:'()[]') -.~L:1 ;:L:0 '-_' rplc~L:0 (1+".s)}.lines
outbuf=: stack=: i.0
}}
xlate=: {{
if.2<#y do.
(opcodes i. 1{y),(4#256)#:".2{::y
else.
opcodes i. 1{y
end.
}}
NB. ensure we maintain 32 bit signed int representation
signadj=: _2147483648+4294967296|2147483648+]
getint=: signadj@(256 #. ])
PUSH=: {{ stack=:stack,signadj y }}
POP=: {{ (stack=: _1 }. stack) ] _1 { stack }}
POP2=: {{ (stack=: _2 }. stack) ] _2 {. stack }}
emit=:{{
outbuf=: outbuf,y
if.LF e. outbuf do.
ndx=. outbuf i:LF
echo ndx{.outbuf
outbuf=: }.ndx}.outbuf
end.
}}
run_vm=: {{
unpack y
stack=: i.pc=:0
lim=. <:#object
while.do.
pc=: pc+1 [ op=: (pc { object){opcodes
i=. getint (lim<.pc+i.4) { object
k=. 0
select.op
case.fetch do. k=.4 [PUSH i{vars
case.store do. k=.4 [vars=: (POP'') i} vars
case.push do. k=.4 [PUSH i
case.add do. PUSH +/POP2''
case.sub do. PUSH -/POP2''
case.mul do. PUSH */POP2''
case.div do. PUSH<.%/POP2''
case.mod do. PUSH |~/POP2''
case.lt do. PUSH </POP2''
case.le do. PUSH <:/POP2''
case.eq do. PUSH =/POP2''
case.ne do. PUSH ~:/POP2''
case.ge do. PUSH >:/POP2''
case.gt do. PUSH >/POP2''
case.and do. PUSH */0~:POP2''
case.or do. PUSH +./0~:POP2''
case.neg do. PUSH -POP''
case.not do. PUSH 0=POP''
case.jmp do. k=. i
case.jz do. k=. (0=POP''){4,i
case.prtc do. emit u:POP''
case.prts do. emit (POP''){::strings
case.prti do. emit rplc&'_-'":POP''
case.halt do. if.#outbuf do.echo outbuf end.EMPTY return.
end.
pc=: pc+k
end.
}} |
http://rosettacode.org/wiki/Compiler/code_generator | Compiler/code generator | A code generator translates the output of the syntax analyzer and/or semantic analyzer
into lower level code, either assembly, object, or virtual.
Task[edit]
Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the
Virtual machine interpreter. The output is in text format, and represents virtual assembly code.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
while.ast can be input into the code generator.
The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code.
Run as: lex < while.t | parse | gen
Input to lex
Output from lex, input to parse
Output from parse
Output from gen, input to VM
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
Input format
As shown in the table, above, the output from the syntax analyzer is a flattened AST.
In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes.
Loading this data into an internal parse tree should be as simple as:
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";"
return None
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Output format - refer to the table above
The first line is the header: Size of data, and number of constant strings.
size of data is the number of 32-bit unique variables used. In this example, one variable, count
number of constant strings is just that - how many there are
After that, the constant strings
Finally, the assembly code
Registers
sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array.
pc: the program counter - points to the current instruction to be performed. The code is an array of bytes.
Data
32-bit integers and strings
Instructions
Each instruction is one byte. The following instructions also have a 32-bit integer operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
prtc
Print the word at stack top as a character.
prti
Print the word at stack top as an integer.
prts
Stack top points to an index into the string pool. Print that entry.
halt
Unconditional stop.
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Virtual Machine Interpreter task
AST Interpreter task
| #Go | Go | package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
// dependency: Ordered by NodeType, must remain in same order as NodeType enum
type atr struct {
enumText string
nodeType NodeType
opcode code
}
var atrs = []atr{
{"Identifier", ndIdent, 255},
{"String", ndString, 255},
{"Integer", ndInteger, 255},
{"Sequence", ndSequence, 255},
{"If", ndIf, 255},
{"Prtc", ndPrtc, 255},
{"Prts", ndPrts, 255},
{"Prti", ndPrti, 255},
{"While", ndWhile, 255},
{"Assign", ndAssign, 255},
{"Negate", ndNegate, neg},
{"Not", ndNot, not},
{"Multiply", ndMul, mul},
{"Divide", ndDiv, div},
{"Mod", ndMod, mod},
{"Add", ndAdd, add},
{"Subtract", ndSub, sub},
{"Less", ndLss, lt},
{"LessEqual", ndLeq, le},
{"Greater", ndGtr, gt},
{"GreaterEqual", ndGeq, ge},
{"Equal", ndEql, eq},
{"NotEqual", ndNeq, ne},
{"And", ndAnd, and},
{"Or", ndOr, or},
}
var (
stringPool []string
globals []string
object []code
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func nodeType2Op(nodeType NodeType) code {
return atrs[nodeType].opcode
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
/*** Code generator ***/
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func emitWordAt(at, n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for i := at; i < at+4; i++ {
object[i] = code(bs[i-at])
}
}
func hole() int {
t := len(object)
emitWord(0)
return t
}
func fetchVarOffset(id string) int {
for i := 0; i < len(globals); i++ {
if globals[i] == id {
return i
}
}
globals = append(globals, id)
return len(globals) - 1
}
func fetchStringOffset(st string) int {
for i := 0; i < len(stringPool); i++ {
if stringPool[i] == st {
return i
}
}
stringPool = append(stringPool, st)
return len(stringPool) - 1
}
func codeGen(x *Tree) {
if x == nil {
return
}
var n, p1, p2 int
switch x.nodeType {
case ndIdent:
emitByte(fetch)
n = fetchVarOffset(x.value)
emitWord(n)
case ndInteger:
emitByte(push)
n, err = strconv.Atoi(x.value)
check(err)
emitWord(n)
case ndString:
emitByte(push)
n = fetchStringOffset(x.value)
emitWord(n)
case ndAssign:
n = fetchVarOffset(x.left.value)
codeGen(x.right)
emitByte(store)
emitWord(n)
case ndIf:
codeGen(x.left) // if expr
emitByte(jz) // if false, jump
p1 = hole() // make room forjump dest
codeGen(x.right.left) // if true statements
if x.right.right != nil {
emitByte(jmp)
p2 = hole()
}
emitWordAt(p1, len(object)-p1)
if x.right.right != nil {
codeGen(x.right.right)
emitWordAt(p2, len(object)-p2)
}
case ndWhile:
p1 = len(object)
codeGen(x.left) // while expr
emitByte(jz) // if false, jump
p2 = hole() // make room for jump dest
codeGen(x.right) // statements
emitByte(jmp) // back to the top
emitWord(p1 - len(object)) // plug the top
emitWordAt(p2, len(object)-p2) // plug the 'if false, jump'
case ndSequence:
codeGen(x.left)
codeGen(x.right)
case ndPrtc:
codeGen(x.left)
emitByte(prtc)
case ndPrti:
codeGen(x.left)
emitByte(prti)
case ndPrts:
codeGen(x.left)
emitByte(prts)
case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,
ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:
codeGen(x.left)
codeGen(x.right)
emitByte(nodeType2Op(x.nodeType))
case ndNegate, ndNot:
codeGen(x.left)
emitByte(nodeType2Op(x.nodeType))
default:
msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType)
reportError(msg)
}
}
func codeFinish() {
emitByte(halt)
}
func listCode() {
fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool))
for _, s := range stringPool {
fmt.Println(s)
}
pc := 0
for pc < len(object) {
fmt.Printf("%5d ", pc)
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("fetch [%d]\n", x)
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("store [%d]\n", x)
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("push %d\n", x)
pc += 4
case add:
fmt.Println("add")
case sub:
fmt.Println("sub")
case mul:
fmt.Println("mul")
case div:
fmt.Println("div")
case mod:
fmt.Println("mod")
case lt:
fmt.Println("lt")
case gt:
fmt.Println("gt")
case le:
fmt.Println("le")
case ge:
fmt.Println("ge")
case eq:
fmt.Println("eq")
case ne:
fmt.Println("ne")
case and:
fmt.Println("and")
case or:
fmt.Println("or")
case neg:
fmt.Println("neg")
case not:
fmt.Println("not")
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x)
pc += 4
case jz:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jz (%d) %d\n", x, int32(pc)+x)
pc += 4
case prtc:
fmt.Println("prtc")
case prti:
fmt.Println("prti")
case prts:
fmt.Println("prts")
case halt:
fmt.Println("halt")
default:
reportError(fmt.Sprintf("listCode: Unknown opcode %d", op))
}
}
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
return makeLeaf(nodeType, s)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
codeGen(loadAst())
codeFinish()
listCode()
} |
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #JavaScript | JavaScript |
function swap(a, i, j){
var t = a[i]
a[i] = a[j]
a[j] = t
}
// Heap Sort
function heap_sort(a){
var n = a.length
function heapify(i){
var t = a[i]
while (true){
var l = 2 * i + 1, r = l + 1
var m = r < n ? (a[l] > a[r] ? l : r) : (l < n ? l : i)
if (m != i && a[m] > t){
a[i] = a[m]
i = m
}
else{
break
}
}
a[i] = t;
}
for (let i = Math.floor(n / 2) - 1; i >= 0; i--){
heapify(i)
}
for (let i = n - 1; i >= 1; i--){
swap(a, 0, i)
n--
heapify(0)
}
}
// Merge Sort
function merge_sort(a){
var b = new Array(a.length)
function rec(l, r){
if (l < r){
var m = Math.floor((l + r) / 2)
rec(l, m)
rec(m + 1, r)
var i = l, j = m + 1, k = 0;
while (i <= m && j <= r) b[k++] = (a[i] > a[j] ? a[j++] : a[i++])
while (j <= r) b[k++] = a[j++]
while (i <= m) b[k++] = a[i++]
for (k = l; k <= r; k++){
a[k] = b[k - l]
}
}
}
rec(0, a.length-1)
}
// Quick Sort
function quick_sort(a){
function rec(l, r){
if (l < r){
var p = a[l + Math.floor((r - l + 1)*Math.random())]
var i = l, j = l, k = r
while (j <= k){
if (a[j] < p){
swap(a, i++, j++)
}
else if (a[j] > p){
swap(a, j, k--)
}
else{
j++
}
}
rec(l, i - 1)
rec(k + 1, r)
}
}
rec(0, a.length - 1)
}
// Shell Sort
function shell_sort(a){
var n = a.length
var gaps = [100894, 44842, 19930, 8858, 3937, 1750, 701, 301, 132, 57, 23, 10, 4, 1]
for (let x of gaps){
for (let i = x; i < n; i++){
var t = a[i], j;
for (j = i; j >= x && a[j - x] > t; j -= x){
a[j] = a[j - x];
}
a[j] = t;
}
}
}
// Comb Sort (+ Insertion sort optimization)
function comb_sort(a){
var n = a.length
for (let x = n; x >= 10; x = Math.floor(x / 1.3)){
for (let i = 0; i + x < n; i++){
if (a[i] > a[i + x]){
swap(a, i, i + x)
}
}
}
for (let i = 1; i < n; i++){
var t = a[i], j;
for (j = i; j > 0 && a[j - 1] > t; j--){
a[j] = a[j - 1]
}
a[j] = t;
}
}
// Test
function test(f, g, e){
var res = ""
for (let n of e){
var a = new Array(n)
var s = 0
for (let k = 0; k < 10; k++){
for (let i = 0; i < n; i++){
a[i] = g(i)
}
var start = Date.now()
f(a)
s += Date.now() - start
}
res += Math.round(s / 10) + "\t"
}
return res
}
// Main
var e = [5000, 10000, 100000, 500000, 1000000, 2000000]
var sOut = "Test times in ms\n\nElements\t" + e.join("\t") + "\n\n"
sOut += "*All ones*\n"
sOut += "heap_sort\t" + test(heap_sort, (x => 1), e) + "\n"
sOut += "quick_sort\t" + test(quick_sort, (x => 1), e) + "\n"
sOut += "merge_sort\t" + test(merge_sort, (x => 1), e) + "\n"
sOut += "shell_sort\t" + test(shell_sort, (x => 1), e) + "\n"
sOut += "comb_sort\t" + test(comb_sort, (x => 1), e) + "\n\n"
sOut += "*Sorted*\n"
sOut += "heap_sort\t" + test(heap_sort, (x => x), e) + "\n"
sOut += "quick_sort\t" + test(quick_sort, (x => x), e) + "\n"
sOut += "merge_sort\t" + test(merge_sort, (x => x), e) + "\n"
sOut += "shell_sort\t" + test(shell_sort, (x => x), e) + "\n"
sOut += "comb_sort\t" + test(comb_sort, (x => x), e) + "\n\n"
sOut += "*Random*\n"
sOut += "heap_sort\t" + test(heap_sort, (x => Math.random()), e) + "\n"
sOut += "quick_sort\t" + test(quick_sort, (x => Math.random()), e) + "\n"
sOut += "merge_sort\t" + test(merge_sort, (x => Math.random()), e) + "\n"
sOut += "shell_sort\t" + test(shell_sort, (x => Math.random()), e) + "\n"
sOut += "comb_sort\t" + test(comb_sort, (x => Math.random()), e) + "\n"
console.log(sOut)
|
http://rosettacode.org/wiki/Compiler/AST_interpreter | Compiler/AST interpreter | An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is as simple as (pseudo code)
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
The interpreter algorithm is relatively simple
interp(x)
if x == NULL return NULL
elif x.node_type == Integer return x.value converted to an integer
elif x.node_type == Ident return the current value of variable x.value
elif x.node_type == String return x.value
elif x.node_type == Assign
globals[x.left.value] = interp(x.right)
return NULL
elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)
elif x.node_type is a unary operator, return return operator interp(x.left)
elif x.node_type == If
if (interp(x.left)) then interp(x.right.left)
else interp(x.right.right)
return NULL
elif x.node_type == While
while (interp(x.left)) do interp(x.right)
return NULL
elif x.node_type == Prtc
print interp(x.left) as a character, no newline
return NULL
elif x.node_type == Prti
print interp(x.left) as an integer, no newline
return NULL
elif x.node_type == Prts
print interp(x.left) as a string, respecting newlines ("\n")
return NULL
elif x.node_type == Sequence
interp(x.left)
interp(x.right)
return NULL
else
error("unknown node type")
Notes:
Because of the simple nature of our tiny language, Semantic analysis is not needed.
Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.
This means, for instance, that 3 / 2 should result in 1.
For division when one of the operands is negative, the result should be truncated towards 0.
This means, for instance, that 3 / -2 should result in -1.
Test program
prime.t
lex <prime.t | parse | interp
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
101 is prime
Total primes found: 26
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
| #Scheme | Scheme |
(import (scheme base)
(scheme file)
(scheme process-context)
(scheme write)
(only (srfi 13) string-delete string-index string-trim))
;; Mappings from operation symbols to internal procedures.
;; We define operations appropriate to virtual machine:
;; e.g. division must return an int, not a rational
;; boolean values are treated as numbers: 0 is false, other is true
(define *unary-ops*
(list (cons 'Negate (lambda (a) (- a)))
(cons 'Not (lambda (a) (if (zero? a) 1 0)))))
(define *binary-ops*
(let ((number-comp (lambda (op) (lambda (a b) (if (op a b) 1 0)))))
(list (cons 'Add +)
(cons 'Subtract -)
(cons 'Multiply *)
(cons 'Divide (lambda (a b) (truncate (/ a b)))) ; int division
(cons 'Mod modulo)
(cons 'Less (number-comp <))
(cons 'Greater (number-comp >))
(cons 'LessEqual (number-comp <=))
(cons 'GreaterEqual (number-comp >=))
(cons 'Equal (lambda (a b) (if (= a b) 1 0)))
(cons 'NotEqual (lambda (a b) (if (= a b) 0 1)))
(cons 'And (lambda (a b) ; make "and" work on numbers
(if (and (not (zero? a)) (not (zero? b))) 1 0)))
(cons 'Or (lambda (a b) ; make "or" work on numbers
(if (or (not (zero? a)) (not (zero? b))) 1 0))))))
;; Read AST from given filename
;; - return as an s-expression
(define (read-code filename)
(define (read-expr)
(let ((line (string-trim (read-line))))
(if (string=? line ";")
'()
(let ((space (string-index line #\space)))
(if space
(list (string->symbol (string-trim (substring line 0 space)))
(string-trim (substring line space (string-length line))))
(list (string->symbol line) (read-expr) (read-expr)))))))
;
(with-input-from-file
filename
(lambda ()
(read-expr))))
;; interpret AST provided as an s-expression
(define run-program
(let ((env '())) ; env is an association list for variable names
(lambda (expr)
(define (tidy-string str)
(string-delete ; remove any quote marks
#\" ; " (to appease Rosetta code's syntax highlighter)
(list->string
(let loop ((chars (string->list str))) ; replace newlines, obeying \\n
(cond ((< (length chars) 2) ; finished list
chars)
((and (>= (length chars) 3) ; preserve \\n
(char=? #\\ (car chars))
(char=? #\\ (cadr chars))
(char=? #\n (cadr (cdr chars))))
(cons (car chars)
(cons (cadr chars)
(cons (cadr (cdr chars))
(loop (cdr (cdr (cdr chars))))))))
((and (char=? #\\ (car chars)) ; replace \n with newline
(char=? #\n (cadr chars)))
(cons #\newline (loop (cdr (cdr chars)))))
(else ; keep char and look further
(cons (car chars) (loop (cdr chars)))))))))
; define some more meaningful names for fields
(define left cadr)
(define right (lambda (x) (cadr (cdr x))))
;
(if (null? expr)
'()
(case (car expr) ; interpret AST from the head node
((Integer)
(string->number (left expr)))
((Identifier)
(let ((val (assq (string->symbol (left expr)) env)))
(if val
(cdr val)
(error "Variable not in environment"))))
((String)
(left expr))
((Assign)
(set! env (cons (cons (string->symbol (left (left expr)))
(run-program (right expr)))
env)))
((Add Subtract Multiply Divide Mod
Less Greater LessEqual GreaterEqual Equal NotEqual
And Or)
(let ((binop (assq (car expr) *binary-ops*)))
(if binop
((cdr binop) (run-program (left expr))
(run-program (right expr)))
(error "Could not find binary operator"))))
((Negate Not)
(let ((unaryop (assq (car expr) *unary-ops*)))
(if unaryop
((cdr unaryop) (run-program (left expr)))
(error "Could not find unary operator"))))
((If)
(if (not (zero? (run-program (left expr)))) ; 0 means false
(run-program (left (right expr)))
(run-program (right (right expr))))
'())
((While)
(let loop ()
(unless (zero? (run-program (left expr)))
(run-program (right expr))
(loop)))
'())
((Prtc)
(display (integer->char (run-program (left expr))))
'())
((Prti)
(display (run-program (left expr)))
'())
((Prts)
(display (tidy-string (run-program (left expr))))
'())
((Sequence)
(run-program (left expr))
(run-program (right expr))
'())
(else
(error "Unknown node type")))))))
;; read AST from file and interpret, from filename passed on command line
(if (= 2 (length (command-line)))
(run-program (read-code (cadr (command-line))))
(display "Error: pass an ast filename\n"))
|
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #Haskell | Haskell | task s1 s2 = do
let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs |
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #J | J | NB. solution
NB. `Haruno-umi Hinemosu-Notari Notarikana'
NB. Spring ocean ; Swaying gently ; All day long.
,/ _2 }.\ ": (;~ #)&> <@(7&u:);._2 '春の海 ひねもすのたり のたりかな '
│3│春の海 │
│7│ひねもすのたり│
│5│のたりかな │
NB. # y is the tally of items (penultimate dimension) in the array y
# 323 43 5j3
3
# 'literal (a string)'
18
/: 'cbad' NB. index ordering vector (grade up)
2 1 0 3
;: 'j tokenize a sentence.'
┌─┬────────┬─┬─────────┐
│j│tokenize│a│sentence.│
└─┴────────┴─┴─────────┘
#S:0 ;: 'j tokenize a sentence.' NB. length of leaves (lowest box level)
1 8 1 9
A=: '1234567 abcd 123456789 abcdef' NB. global assignment
(\: #S:0) ;: A NB. order by grade down
┌─────────┬───────┬──────┬────┐
│123456789│1234567│abcdef│abcd│
└─────────┴───────┴──────┴────┘
(;:'length literal') , ((;~ #)&> \: #S:0) ;: A NB. box incompatible types with header
┌──────┬─────────┐
│length│literal │
├──────┼─────────┤
│9 │123456789│
├──────┼─────────┤
│7 │1234567 │
├──────┼─────────┤
│6 │abcdef │
├──────┼─────────┤
│4 │abcd │
└──────┴─────────┘
(;:'len vector') , ((;~ #)&> \: #S:0) 0 1 2 3 ; 0 1 ; (i. 8) ; 0
┌───┬───────────────┐
│len│vector │
├───┼───────────────┤
│8 │0 1 2 3 4 5 6 7│
├───┼───────────────┤
│4 │0 1 2 3 │
├───┼───────────────┤
│2 │0 1 │
├───┼───────────────┤
│1 │0 │
└───┴───────────────┘
|
http://rosettacode.org/wiki/Compiler/syntax_analyzer | Compiler/syntax analyzer | A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened format.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a parser module/library/class, it would be great
if two versions of the solution are provided: One without the parser module, and one
with.
Grammar
The simple programming language to be analyzed is more or less a (very tiny) subset of
C. The formal grammar in
Extended Backus-Naur Form (EBNF):
stmt_list = {stmt} ;
stmt = ';'
| Identifier '=' expr ';'
| 'while' paren_expr stmt
| 'if' paren_expr stmt ['else' stmt]
| 'print' '(' prt_list ')' ';'
| 'putc' paren_expr ';'
| '{' stmt_list '}'
;
paren_expr = '(' expr ')' ;
prt_list = (string | expr) {',' (String | expr)} ;
expr = and_expr {'||' and_expr} ;
and_expr = equality_expr {'&&' equality_expr} ;
equality_expr = relational_expr [('==' | '!=') relational_expr] ;
relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;
addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;
multiplication_expr = primary {('*' | '/' | '%') primary } ;
primary = Identifier
| Integer
| '(' expr ')'
| ('+' | '-' | '!') primary
;
The resulting AST should be formulated as a Binary Tree.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
The following table shows the input to lex, lex output, and the AST produced by the parser
Input to lex
Output from lex, input to parse
Output from parse
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Specifications
List of node type names
Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod
Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
In the text below, Null/Empty nodes are represented by ";".
Non-terminal (internal) nodes
For Operators, the following nodes should be created:
Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
For each of the above nodes, the left and right sub-nodes are the operands of the
respective operation.
In pseudo S-Expression format:
(Operator expression expression)
Negate, Not
For these node types, the left node is the operand, and the right node is null.
(Operator expression ;)
Sequence - sub-nodes are either statements or Sequences.
If - left node is the expression, the right node is If node, with it's left node being the
if-true statement part, and the right node being the if-false (else) statement part.
(If expression (If statement else-statement))
If there is not an else, the tree becomes:
(If expression (If statement ;))
Prtc
(Prtc (expression) ;)
Prts
(Prts (String "the string") ;)
Prti
(Prti (Integer 12345) ;)
While - left node is the expression, the right node is the statement.
(While expression statement)
Assign - left node is the left-hand side of the assignment, the right node is the
right-hand side of the assignment.
(Assign Identifier expression)
Terminal (leaf) nodes:
Identifier: (Identifier ident_name)
Integer: (Integer 12345)
String: (String "Hello World!")
";": Empty node
Some simple examples
Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.
This simple program:
a=11;
Produces the following AST, encoded as a binary tree:
Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:
(1) Sequence
(2) |-- ;
(3) |-- Assign
(4) |-- Identifier: a
(5) |-- Integer: 11
In flattened form:
(1) Sequence
(2) ;
(3) Assign
(4) Identifier a
(5) Integer 11
This program:
a=11;
b=22;
c=33;
Produces the following AST:
( 1) Sequence
( 2) |-- Sequence
( 3) | |-- Sequence
( 4) | | |-- ;
( 5) | | |-- Assign
( 6) | | |-- Identifier: a
( 7) | | |-- Integer: 11
( 8) | |-- Assign
( 9) | |-- Identifier: b
(10) | |-- Integer: 22
(11) |-- Assign
(12) |-- Identifier: c
(13) |-- Integer: 33
In flattened form:
( 1) Sequence
( 2) Sequence
( 3) Sequence
( 4) ;
( 5) Assign
( 6) Identifier a
( 7) Integer 11
( 8) Assign
( 9) Identifier b
(10) Integer 22
(11) Assign
(12) Identifier c
(13) Integer 33
Pseudo-code for the parser.
Uses Precedence Climbing for expression parsing, and
Recursive Descent for statement parsing. The AST is also built:
def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
Once the AST is built, it should be output in a flattened format. This can be as simple as the following
def prt_ast(t)
if t == NULL
print(";\n")
else
print(t.node_type)
if t.node_type in [Identifier, Integer, String] # leaf node
print the value of the Ident, Integer or String, "\n"
else
print("\n")
prt_ast(t.left)
prt_ast(t.right)
If the AST is correctly built, loading it into a subsequent program should be as simple as
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Finally, the AST can also be tested by running it against one of the AST Interpreter solutions.
Test program, assuming this is in a file called prime.t
lex <prime.t | parse
Input to lex
Output from lex, input to parse
Output from parse
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
4 1 Identifier count
4 7 Op_assign
4 9 Integer 1
4 10 Semicolon
5 1 Identifier n
5 3 Op_assign
5 5 Integer 1
5 6 Semicolon
6 1 Identifier limit
6 7 Op_assign
6 9 Integer 100
6 12 Semicolon
7 1 Keyword_while
7 7 LeftParen
7 8 Identifier n
7 10 Op_less
7 12 Identifier limit
7 17 RightParen
7 19 LeftBrace
8 5 Identifier k
8 6 Op_assign
8 7 Integer 3
8 8 Semicolon
9 5 Identifier p
9 6 Op_assign
9 7 Integer 1
9 8 Semicolon
10 5 Identifier n
10 6 Op_assign
10 7 Identifier n
10 8 Op_add
10 9 Integer 2
10 10 Semicolon
11 5 Keyword_while
11 11 LeftParen
11 12 LeftParen
11 13 Identifier k
11 14 Op_multiply
11 15 Identifier k
11 16 Op_lessequal
11 18 Identifier n
11 19 RightParen
11 21 Op_and
11 24 LeftParen
11 25 Identifier p
11 26 RightParen
11 27 RightParen
11 29 LeftBrace
12 9 Identifier p
12 10 Op_assign
12 11 Identifier n
12 12 Op_divide
12 13 Identifier k
12 14 Op_multiply
12 15 Identifier k
12 16 Op_notequal
12 18 Identifier n
12 19 Semicolon
13 9 Identifier k
13 10 Op_assign
13 11 Identifier k
13 12 Op_add
13 13 Integer 2
13 14 Semicolon
14 5 RightBrace
15 5 Keyword_if
15 8 LeftParen
15 9 Identifier p
15 10 RightParen
15 12 LeftBrace
16 9 Keyword_print
16 14 LeftParen
16 15 Identifier n
16 16 Comma
16 18 String " is prime\n"
16 31 RightParen
16 32 Semicolon
17 9 Identifier count
17 15 Op_assign
17 17 Identifier count
17 23 Op_add
17 25 Integer 1
17 26 Semicolon
18 5 RightBrace
19 1 RightBrace
20 1 Keyword_print
20 6 LeftParen
20 7 String "Total primes found: "
20 29 Comma
20 31 Identifier count
20 36 Comma
20 38 String "\n"
20 42 RightParen
20 43 Semicolon
21 1 End_of_input
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier n
Integer 1
Assign
Identifier limit
Integer 100
While
Less
Identifier n
Identifier limit
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier k
Integer 3
Assign
Identifier p
Integer 1
Assign
Identifier n
Add
Identifier n
Integer 2
While
And
LessEqual
Multiply
Identifier k
Identifier k
Identifier n
Identifier p
Sequence
Sequence
;
Assign
Identifier p
NotEqual
Multiply
Divide
Identifier n
Identifier k
Identifier k
Identifier n
Assign
Identifier k
Add
Identifier k
Integer 2
If
Identifier p
If
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier n
;
Prts
String " is prime\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
;
Sequence
Sequence
Sequence
;
Prts
String "Total primes found: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #Nim | Nim | import ast_lexer
type NodeKind* = enum
nIdentifier = "Identifier"
nString = "String"
nInteger = "Integer"
nSequence = "Sequence"
nIf = "If"
nPrtc = "Prtc"
nPrts = "Prts"
nPrti = "Prti"
nWhile = "While"
nAssign = "Assign"
nNegate = "Negate"
nNot = "Not"
nMultiply = "Multiply"
nDivide = "Divide"
nMod = "Mod"
nAdd = "Add"
nSubtract = "Subtract"
nLess = "Less"
nLessEqual = "LessEqual"
nGreater = "Greater"
nGreaterEqual = "GreaterEqual"
nEqual = "Equal"
nNotEqual = "NotEqual"
nAnd = "And"
nOr = "Or"
type Node* = ref object
left*: Node
right*: Node
case kind*: NodeKind
of nString: stringVal*: string
of nInteger: intVal*: int
of nIdentifier: name*: string
else: nil
type Operator = range[tokMult..tokOr]
const
Precedences: array[Operator, int] = [13, # tokMult
13, # tokDiv
13, # tokMod
12, # tokAdd
12, # tokSub
10, # tokLess
10, # tokLessEq
10, # tokGreater
10, # tokGreaterEq
9, # tokEq
9, # tokNeq
14, # tokNot
-1, # tokAssign
5, # tokAnd
4] # tokOr
UnaryPrecedence = 14
BinaryOperators = {tokMult, tokDiv, tokMod, tokAdd, tokSub, tokLess, tokLessEq,
tokGreater, tokGreaterEq, tokEq, tokNotEq, tokAnd, tokOr}
# Mapping of operators from TokenKind to NodeKind.
NodeKinds: array[Operator, NodeKind] = [nMultiply, nDivide, nMod, nAdd, nSubtract,
nLess, nLessEqual, nGreater, nGreaterEqual,
nEqual, nNotEqual, nNot, nAssign, nAnd, nOr]
type SyntaxError* = object of CatchableError
####################################################################################################
template expect(token: Token; expected: TokenKind; errmsg: string) =
## Check if a token is of the expected kind.
## Raise a SyntaxError if this is not the case.
if token.kind != expected:
raise newException(SyntaxError, "line " & $token.ln & ": " & errmsg)
token = lexer.next()
#---------------------------------------------------------------------------------------------------
proc newNode*(kind: NodeKind; left: Node; right: Node = nil): Node =
## Create a new node with given left and right children.
result = Node(kind: kind, left: left, right: right)
#---------------------------------------------------------------------------------------------------
# Forward reference.
proc parExpr(lexer: var Lexer; token: var Token): Node
#---------------------------------------------------------------------------------------------------
proc expr(lexer: var Lexer; token: var Token; p: int): Node =
## Parse an expression.
case token.kind
of tokLPar:
result = parExpr(lexer, token)
of tokAdd, tokSub, tokNot:
# Unary operators.
let savedToken = token
token = lexer.next()
let e = expr(lexer, token, UnaryPrecedence)
if savedToken.kind == tokAdd:
result = e
else:
result = newNode(if savedToken.kind == tokSub: nNegate else: nNot, e)
of tokIdent:
result = Node(kind: nIdentifier, name: token.ident)
token = lexer.next()
of tokInt:
result = Node(kind:nInteger, intVal: token.intVal)
token = lexer.next()
of tokChar:
result = Node(kind:nInteger, intVal: ord(token.charVal))
token = lexer.next()
else:
raise newException(SyntaxError, "Unexpected symbol at line " & $token.ln)
# Process the binary operators in the expression.
while token.kind in BinaryOperators and Precedences[token.kind] >= p:
let savedToken = token
token = lexer.next()
let q = Precedences[savedToken.kind] + 1 # No operator is right associative.
result = newNode(NodeKinds[savedToken.kind], result, expr(lexer, token, q))
#---------------------------------------------------------------------------------------------------
proc parExpr(lexer: var Lexer; token: var Token): Node =
## Parse a parenthetized expression.
token.expect(tokLPar, "'(' expected")
result = expr(lexer, token, 0)
token.expect(tokRPar, "')' expected")
#---------------------------------------------------------------------------------------------------
proc stmt(lexer: var Lexer; token: var Token): Node =
## Parse a statement.
case token.kind:
of tokIf:
token = lexer.next()
let e = parExpr(lexer, token)
let thenNode = stmt(lexer, token)
var elseNode: Node = nil
if token.kind == tokElse:
token = lexer.next()
elseNode = stmt(lexer, token)
result = newNode(nIf, e, newNode(nIf, thenNode, elseNode))
of tokPutc:
token = lexer.next()
result = newNode(nPrtc, parExpr(lexer, token))
token.expect(tokSemi, "';' expected")
of tokPrint:
token = lexer.next()
token.expect(tokLPar, "'(' expected")
while true:
var e: Node
if token.kind == tokString:
e = newNode(nPrts, Node(kind: nString, stringVal: token.stringVal))
token = lexer.next()
else:
e = newNode(nPrti, expr(lexer, token, 0))
result = newNode(nSequence, result, e)
if token.kind == tokComma:
token = lexer.next()
else:
break
token.expect(tokRPar, "')' expected")
token.expect(tokSemi, "';' expected")
of tokSemi:
token = lexer.next()
of tokIdent:
let v = Node(kind: nIdentifier, name: token.ident)
token = lexer.next()
token.expect(tokAssign, "'=' expected")
result = newNode(nAssign, v, expr(lexer, token, 0))
token.expect(tokSemi, "';' expected")
of tokWhile:
token = lexer.next()
let e = parExpr(lexer, token)
result = newNode(nWhile, e, stmt(lexer, token))
of tokLBrace:
token = lexer.next()
while token.kind notin {tokRBrace, tokEnd}:
result = newNode(nSequence, result, stmt(lexer, token))
token.expect(tokRBrace, "'}' expected")
of tokEnd:
discard
else:
raise newException(SyntaxError, "Unexpected symbol at line " & $token.ln)
#---------------------------------------------------------------------------------------------------
proc parse*(code: string): Node =
## Parse the code provided.
var lexer = initLexer(code)
var token = lexer.next()
while true:
result = newNode(nSequence, result, stmt(lexer, token))
if token.kind == tokEnd:
break
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import os, strformat, strutils
proc printAst(node: Node) =
## Print tha AST in linear form.
if node.isNil:
echo ';'
else:
stdout.write &"{$node.kind:<14}"
case node.kind
of nIdentifier:
echo node.name
of nInteger:
echo node.intVal
of nString:
# Need to escape and to replace hexadecimal \x0A by \n.
echo escape(node.stringVal).replace("\\x0A", "\\n")
else:
echo ""
node.left.printAst()
node.right.printAst()
let code = if paramCount() < 1: stdin.readAll() else: paramStr(1).readFile()
let tree = parse(code)
tree.printAst() |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #COBOL | COBOL | identification division.
program-id. game-of-life-program.
data division.
working-storage section.
01 grid.
05 cell-table.
10 row occurs 5 times.
15 cell pic x value space occurs 5 times.
05 next-gen-cell-table.
10 next-gen-row occurs 5 times.
15 next-gen-cell pic x occurs 5 times.
01 counters.
05 generation pic 9.
05 current-row pic 9.
05 current-cell pic 9.
05 living-neighbours pic 9.
05 neighbour-row pic 9.
05 neighbour-cell pic 9.
05 check-row pic s9.
05 check-cell pic s9.
procedure division.
control-paragraph.
perform blinker-paragraph varying current-cell from 2 by 1
until current-cell is greater than 4.
perform show-grid-paragraph through life-paragraph
varying generation from 0 by 1
until generation is greater than 2.
stop run.
blinker-paragraph.
move '#' to cell(3,current-cell).
show-grid-paragraph.
display 'GENERATION ' generation ':'.
display ' +---+'.
perform show-row-paragraph varying current-row from 2 by 1
until current-row is greater than 4.
display ' +---+'.
display ''.
life-paragraph.
perform update-row-paragraph varying current-row from 2 by 1
until current-row is greater than 4.
move next-gen-cell-table to cell-table.
show-row-paragraph.
display ' |' with no advancing.
perform show-cell-paragraph varying current-cell from 2 by 1
until current-cell is greater than 4.
display '|'.
show-cell-paragraph.
display cell(current-row,current-cell) with no advancing.
update-row-paragraph.
perform update-cell-paragraph varying current-cell from 2 by 1
until current-cell is greater than 4.
update-cell-paragraph.
move 0 to living-neighbours.
perform check-row-paragraph varying check-row from -1 by 1
until check-row is greater than 1.
evaluate living-neighbours,
when 2 move cell(current-row,current-cell) to next-gen-cell(current-row,current-cell),
when 3 move '#' to next-gen-cell(current-row,current-cell),
when other move space to next-gen-cell(current-row,current-cell),
end-evaluate.
check-row-paragraph.
add check-row to current-row giving neighbour-row.
perform check-cell-paragraph varying check-cell from -1 by 1
until check-cell is greater than 1.
check-cell-paragraph.
add check-cell to current-cell giving neighbour-cell.
if cell(neighbour-row,neighbour-cell) is equal to '#',
and check-cell is not equal to zero or check-row is not equal to zero,
then add 1 to living-neighbours. |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #PureBasic | PureBasic | Structure MyPoint
x.i
y.i
EndStructure |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Python | Python | X, Y = 0, 1
p = (3, 4)
p = [3, 4]
print p[X] |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
class Game {
static init() {
Window.title = "Constrained random points on a circle"
var width = 800
var height = 800
Window.resize(width, height)
Canvas.resize(width, height)
var rand = Random.new()
var count = 0
var max = 100 // set to 1000 to produce a much more pronounced annulus
while (true) {
var x = rand.int(-15, 16)
var y = rand.int(-15, 16)
var dist = (x*x + y*y).sqrt
if (10 <= dist && dist <= 15) {
// translate coordinates to fit in the window
Canvas.circlefill((x + 16) * 25, (y + 16) * 25, 2, Color.white)
count = count + 1
if (count == max) break
}
}
}
static update() {}
static draw(alpha) {}
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #AWK | AWK | if(i<0) i=0; else i=42 |
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #Haskell | Haskell | #!/usr/bin/env runhaskell
import Control.Monad (forM_)
import Data.Char (isDigit)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
{-
I use the suffix "2" in identifiers in place of the more conventional
prime (single quote character), because Rosetta Code's syntax highlighter
still doesn't handle primes in identifiers correctly.
-}
isDigitOrPeriod :: Char -> Bool
isDigitOrPeriod '.' = True
isDigitOrPeriod c = isDigit c
chopUp :: Int -> String -> [String]
chopUp _ [] = []
chopUp by str
| by < 1 = [str] -- invalid argument, leave string unchanged
| otherwise = let (pfx, sfx) = splitAt by str
in pfx : chopUp by sfx
addSeps :: String -> Char -> Int -> (String -> String) -> String
addSeps str sep by rev =
let (leading, number) = span (== '0') str
number2 = rev $ intercalate [sep] $ chopUp by $ rev number
in leading ++ number2
processNumber :: String -> Char -> Int -> String
processNumber str sep by =
let (beforeDecimal, rest) = span isDigit str
(decimal, afterDecimal) = splitAt 1 rest
beforeDecimal2 = addSeps beforeDecimal sep by reverse
afterDecimal2 = addSeps afterDecimal sep by id
in beforeDecimal2 ++ decimal ++ afterDecimal2
commatize2 :: String -> Char -> Int -> String
commatize2 [] _ _ = []
commatize2 str sep by =
let (pfx, sfx) = break isDigitOrPeriod str
(number, sfx2) = span isDigitOrPeriod sfx
in pfx ++ processNumber number sep by ++ sfx2
commatize :: String -> Maybe Char -> Maybe Int -> String
commatize str sep by = commatize2 str (fromMaybe ',' sep) (fromMaybe 3 by)
input :: [(String, Maybe Char, Maybe Int)]
input =
[ ("pi=3.14159265358979323846264338327950288419716939937510582097494459231", Just ' ', Just 5)
, ("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", Just '.', Nothing)
, ("\"-in Aus$+1411.8millions\"", Nothing, Nothing)
, ("===US$0017440 millions=== (in 2000 dollars)", Nothing, Nothing)
, ("123.e8000 is pretty big.", Nothing, Nothing)
, ("The land area of the earth is 57268900(29% of the surface) square miles.", Nothing, Nothing)
, ("Ain't no numbers in this here words, nohow, no way, Jose.", Nothing, Nothing)
, ("James was never known as 0000000007", Nothing, Nothing)
, ("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", Nothing, Nothing)
, (" $-140000±100 millions.", Nothing, Nothing)
, ("6/9/1946 was a good year for some.", Nothing, Nothing)
]
main :: IO ()
main =
forM_ input $ \(str, by, sep) -> do
putStrLn str
putStrLn $ commatize str by sep
putStrLn "" |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #BQN | BQN | AllEq ← ⍋≡⍒
Asc ← ¬∘AllEq∧∧≡⊢
•Show AllEq ⟨"AA", "AA", "AA", "AA"⟩
•Show Asc ⟨"AA", "AA", "AA", "AA"⟩
•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩
•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩ |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #Bracmat | Bracmat | (test1=first.~(!arg:%@?first ? (%@:~!first) ?))
& (test2=x.~(!arg:? %@?x (%@:~>!x) ?)) |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #360_Assembly | 360 Assembly | * Comma quibbling 13/03/2017
COMMAQUI CSECT
USING COMMAQUI,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(N)) do i=1 to hbound(t)
LR R1,R6 i
SLA R1,5 *32
LA R2,T-32 @t(0)
AR R1,R2 @t(i)
MVC S1,0(R1) s1=t(i)
MVC S2,=CL32'{' s2='{'
LA R8,S2+1 s2ins=1
MVC I2,=F'0' i2=0
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(L'T)) do j=1 to length(t)
LA R1,S1 @s1
BCTR R1,0 @s1-1
AR R1,R7 @s1-1+j
MVC CJ,0(R1) cj=mid(s1,j,1)
CLI CJ,C' ' if cj=' '
BE EXITJ then goto exitj
IF CLI,CJ,EQ,C',' THEN if cj="," then
MVC 0(2,R8),=C', ' s2=s2||", "
LA R8,2(R8) s2ins=s2ins+2
LR R0,R8 s2ins
LA R1,S2+1 @s2+1
SR R0,R1 len(s2)-1
ST R0,I2 i2=len(s2)-1
ELSE , else
MVC 0(1,R8),CJ s2=s2||cj
LA R8,1(R8) s2ins=s2ins+1
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
EXITJ MVI 0(R8),C'}' s2=s2||"}"
LA R8,1(R8) s2ins=s2ins+1
L R0,I2 i2
IF LTR,R0,NZ,R0 THEN if i2<>0 then
MVC S2B,S2 s2b=mid(s2,1,i2-1)
LA R1,S2B-1 @s2b-1
A R1,I2 +i2
MVC 0(5,R1),=C' and ' s2b||" and "
LA R1,5(R1) +5
LA R2,S2+1 @s2+1
A R2,I2 +i2
LR R3,R8 s2ins
LA R0,S2+1 @s2+1
SR R3,R0 s2ins-(@s2+1)
S R3,I2 -i2
BCTR R3,0 -1
EX R3,XMVC s2b||=mid(s2,i2+2)
MVC S2,S2B s2=mid(s2,1,i2-1)||" and "||mid(s2,i2+2)
ENDIF , endif
XPRNT S2,L'S2 print s2
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
XMVC MVC 0(0,R1),0(R2) mvc @r1,@r2
N EQU (TEND-T)/L'T items of t
T DC CL32' ',CL32'ABC',CL32'ABC,DEF',CL32'ABC,DEF,G,H'
TEND DS 0C
I2 DS F
S1 DS CL(L'T)
S2 DS CL(L'T)
S2B DS CL(L'T)
CJ DS CL1
YREGS
END COMMAQUI |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Given a list of strings in HL, and a pointer in DE, write
;; the resulting string starting at DE.
quibble: mvi a,'{' ; Write the first {,
stax d
inx d ; And increment the pointer
push h ; Keep start of list
call strseqlen ; Get length of list
pop h ; Restore start of list
xra a ; Is the list empty?
ora b
jz quibend ; If empty list, we're done.
quibcopy: call strcpy ; Copy current string into output
inx h ; Advance input pointer to next string
dcr b ; Decrement counter
jz quibend ; If zero, that was the last string
push h ; Push input pointer
mov a,b ; Is the counter 1 now?
cpi 1
lxi h,quibcomma ; Add a comma and space,
jnz quibsep ; unless the counter was 1,
lxi h,quiband ; then use " and "
quibsep: call strcpy ; Copy the separator into the output
pop h ; Restore the input pointer
jmp quibcopy ; Do the next string in the list
quibend: mvi a,'}' ; Write the final '}'
stax d
inx d
mvi a,'$' ; And write a string terminator
stax d
ret
quibcomma: db ', $'
quiband: db ' and $'
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copy the string under HL to DE until the terminator $.
;; The terminator is not copied; HL and DE are left one byte
;; beyond the last byte copied.
strcpy: mov a,m ; Get byte from input
cpi '$' ; Are we at the end?
rz ; Then stop.
stax d ; Otherwise, store byte at output
inx h ; Increment the pointers
inx d
jmp strcpy ; Copy next byte.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Return in B the amount of strings in the string list in HL
strseqlen: mvi a,'$' ; String end
mvi b,0 ; String counter
count: cmp m ; Empty string?
rz ; Then we're done
inr b ; Otherwise, we have a string
strsrch: cmp m ; Find the end of the string
inx h
jnz strsrch
jmp count
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Demo code: run 'quibble' on the examples
demo: mvi c,4 ; Four examples
lxi h,examples ; Pointer to first example
example: push b ; Push example count
lxi d,buffer ; Into the buffer,
call quibble ; write the output of comma-quibbling
inx h ; Point to next example
push h ; Save pointer to next example
lxi d,buffer ; Write the output to the console
mvi c,9
call 5
lxi d,newline ; Write a newline to the console
mvi c,9
call 5
pop h ; Restore example pointer
pop b ; Restore example counter
dcr c ; If not zero,
jnz example ; do the next example.
ret
newline: db 10,13,'$'
examples: db '$'
db 'ABC$$'
db 'ABC$DEF$$'
db 'ABC$DEF$G$H$$'
buffer: |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S
{\displaystyle S}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:
Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,
S
{\displaystyle S}
is
{
i
c
e
d
,
j
a
m
,
p
l
a
i
n
}
{\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}
,
|
S
|
=
3
{\displaystyle |S|=3}
, and
k
=
2
{\displaystyle k=2}
.)
A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.
Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.
Also note that doughnut can also be spelled donut.
Task
Write a function/program/routine/.. to generate all the combinations with repetitions of
n
{\displaystyle n}
types of things taken
k
{\displaystyle k}
at a time and use it to show an answer to the doughnut example above.
For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.
References
k-combination with repetitions
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #360_Assembly | 360 Assembly | * Combinations with repetitions - 16/04/2019
COMBREP CSECT
USING COMBREP,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
MVC FLAVORS(9),SET1 flavors=3,draws=2,tell=1
BAL R14,COMBINE call combine
MVC FLAVORS(9),SET2 flavors=10,draws=3,tell=0
BAL R14,COMBINE call combine
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
COMBINE SR R9,R9 n=0
MVI V,X'00' ~
MVC V+1(NN*L'V-1),V v=0
IF CLI,TELL,EQ,X'01' THEN if tell then
XPRNT =C'list:',5 print
ENDIF , endif
LOOP LA R6,1 i=1
DO WHILE=(C,R6,LE,DRAWS) do i=1 to draws
LR R1,R6 i
SLA R1,2 ~
L R2,V-4(R1) v(i)
L R3,FLAVORS flavors
BCTR R3,0 flavors-1
IF CR,R2,GT,R3 THEN if v(i)>flavors-1 then
LR R1,R6 i
SLA R1,2 ~
LA R1,V(R1) @v(i+1)
L R2,0(R1) v(i+1)
LA R2,1(R2) v(i+1)+1
ST R2,0(R1) v(i+1)=v(i+1)+1
LR R7,R6 j=i
DO WHILE=(C,R7,GE,=A(1)) do j=i to 1 by -1
LR R1,R6 i
SLA R1,2 ~
L R2,V(R1) v(i+1)
LR R1,R7 j
SLA R1,2 ~
ST R2,V-4(R1) v(j)=v(i+1)
BCTR R7,0 j--
ENDDO , enddo j
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
L R1,DRAWS draws
LA R1,1(R1) draws+1
SLA R1,2 ~
L R2,V-4(R1) v(draws+1)
LTR R2,R2 if v(draws+1)>0
BP EXITLOOP then exit loop
LA R9,1(R9) n=n+1
IF CLI,TELL,EQ,X'01' THEN if tell then
MVC BUF,=CL60' ' buf=' '
LA R10,1 ibuf=1
LA R6,1 i=1
DO WHILE=(C,R6,LE,DRAWS) do i=1 to draws
LR R1,R6 i
SLA R1,2 ~
L R1,V-4(R1) v(i)
MH R1,=AL2(L'ITEMS) ~
LA R4,ITEMS(R1) @items(v(i)+1)
LA R5,BUF-1 @buf-1
AR R5,R10 +ibuf
MVC 0(6,R5),0(R4) substr(buf,ibuf,6)=items(v(i)+1)
LA R10,L'ITEMS(R10) ibuf=ibuf+length(items)
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT BUF,L'BUF print buf
ENDIF , endif
L R2,V v(1)
LA R2,1(R2) v(1)+1
ST R2,V v(1)=v(1)+1
B LOOP loop
EXITLOOP L R1,FLAVORS flavors
XDECO R1,XDEC edit flavors
MVC PG+4(2),XDEC+10 output flavors
L R1,DRAWS draws
XDECO R1,XDEC edit draws
MVC PG+7(2),XDEC+10 output draws
XDECO R9,PG+11 edit & output n
XPRNT PG,L'PG print buffer
BR R14 return
NN EQU 16
ITEMS DC CL6'iced',CL6'jam',CL6'plain'
FLAVORS DS F
DRAWS DS F
TELL DS X
SET1 DC F'3',F'2',X'01' flavors=3,draws=2,tell=1
SET2 DC F'10',F'3',X'00' flavors=10,draws=3,tell=0
V DS (NN)F v(nn)
BUF DS CL60 buf
PG DC CL40'cwr(..,..)=............'
XDEC DS CL12 temp for xdeco
REGEQU
END COMBREP |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S
{\displaystyle S}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:
Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,
S
{\displaystyle S}
is
{
i
c
e
d
,
j
a
m
,
p
l
a
i
n
}
{\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}
,
|
S
|
=
3
{\displaystyle |S|=3}
, and
k
=
2
{\displaystyle k=2}
.)
A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.
Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.
Also note that doughnut can also be spelled donut.
Task
Write a function/program/routine/.. to generate all the combinations with repetitions of
n
{\displaystyle n}
types of things taken
k
{\displaystyle k}
at a time and use it to show an answer to the doughnut example above.
For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.
References
k-combination with repetitions
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Action.21 | Action! | PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i,ind
FOR i=0 TO len-1
DO
IF i>0 THEN Put('+) FI
ind=c(i)
IF ind=0 THEN
Print("iced")
ELSEIF ind=1 THEN
Print("jam")
ELSE
Print("plain")
FI
OD
PutE()
RETURN
BYTE FUNC NotDecreasing(BYTE ARRAY c BYTE len)
BYTE i
IF len<2 THEN RETURN (1) FI
FOR i=0 TO len-2
DO
IF c(i)>c(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC NextComb(BYTE ARRAY c BYTE n,k)
INT pos,i
DO
pos=k-1
DO
c(pos)==+1
IF c(pos)<n THEN
EXIT
ELSE
pos==-1
IF pos<0 THEN RETURN (0) FI
FI
FOR i=pos+1 TO k-1
DO
c(i)=c(pos)
OD
OD
UNTIL NotDecreasing(c,k)
OD
RETURN (1)
PROC Comb(BYTE n,k,show)
BYTE ARRAY c(10)
BYTE i,count
IF k>n THEN
Print("Error! k is greater than n.")
Break()
FI
PrintF("Choices of %B from %B:%E",k,n)
FOR i=0 TO k-1
DO
c(i)=0
OD
count=0
DO
count==+1
IF show THEN
PrintF(" %B. ",count)
PrintComb(c,k)
FI
UNTIL NextComb(c,n,k)=0
OD
PrintF("Total choices %B%E%E",count)
RETURN
PROC Main()
Comb(3,2,1)
Comb(10,3,0)
RETURN |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
COMMENT REQUIRED by "prelude_combinations_and_permutations.a68" CO
MODE CPINT = #LONG# ~;
MODE CPOUT = #LONG# ~; # the answer, can be REAL #
MODE CPREAL = ~; # the answer, can be REAL #
PROC cp fix value error = (#REF# CPARGS args)BOOL: ~;
#PROVIDES:#
# OP C = (CP~,CP~)CP~: ~ #
# OP P = (CP~,CP~)CP~: ~ #
END COMMENT
MODE CPARGS = STRUCT(CHAR name, #REF# CPINT n,k);
PRIO C = 8, P = 8; # should be 7.5, a priority between *,/ and **,SHL,SHR etc #
# I suspect there is a more reliable way of doing this using the Gamma Function approx #
OP P = (CPINT n, r)CPOUT: (
IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS("P",n,r)) THEN stop FI FI;
CPOUT out := 1;
# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #
FOR i FROM n-r+1 TO n DO out *:= i OD;
out
);
OP P = (CPREAL n, r)CPREAL: # 'ln gamma' requires GSL library #
exp(ln gamma(n+1)-ln gamma(n-r+1));
# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #
COMMENT # alternate slower version #
OP P = (CPREAL n, r)CPREAL: ( # alternate slower version #
IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS("P",ENTIER n,ENTIER r)) THEN stop FI FI;
CPREAL out := 1;
# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! #
CPREAL i := n-r+1;
WHILE i <= n DO
out*:= i;
# a crude check for underflow #
IF i = i + 1 THEN IF NOT cp fix value error(CPARGS("P",ENTIER n,ENTIER r)) THEN stop FI FI;
i+:=1
OD;
out
);
END COMMENT
# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! #
OP C = (CPINT n, r)CPOUT: (
IF n < r ORF r < 0 THEN IF NOT cp fix value error(("C",n,r)) THEN stop FI FI;
CPINT largest = ( r > n - r | r | n - r );
CPINT smallest = n - largest;
CPOUT out := 1;
INT smaller fact := 2;
FOR larger fact FROM largest+1 TO n DO
# try and prevent overflow, p.s. there must be a smarter way to do this #
# Problems: loop stalls when 'smaller fact' is a largeish co prime #
out *:= larger fact;
WHILE smaller fact <= smallest ANDF out MOD smaller fact = 0 DO
out OVERAB smaller fact;
smaller fact +:= 1
OD
OD;
out # EXIT with: n P r OVER r P r #
);
OP C = (CPREAL n, CPREAL r)CPREAL: # 'ln gamma' requires GSL library #
exp(ln gamma(n+1)-ln gamma(n-r+1)-ln gamma(r+1));
# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! #
COMMENT # alternate slower version #
OP C = (CPREAL n, REAL r)CPREAL: (
IF n < r ORF r < 0 THEN IF NOT cp fix value error(("C",ENTIER n,ENTIER r)) THEN stop FI FI;
CPREAL largest = ( r > n - r | r | n - r );
CPREAL smallest = n - largest;
CPREAL out := 1;
REAL smaller fact := 2;
REAL larger fact := largest+1;
WHILE larger fact <= n DO # todo: check underflow here #
# try and prevent overflow, p.s. there must be a smarter way to do this #
out *:= larger fact;
WHILE smaller fact <= smallest ANDF out > smaller fact DO
out /:= smaller fact;
smaller fact +:= 1
OD;
larger fact +:= 1
OD;
out # EXIT with: n P r OVER r P r #
);
END COMMENT
SKIP |
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer).
Task[edit]
Create a lexical analyzer for the simple programming language specified below. The
program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a lexer module/library/class, it would be great
if two versions of the solution are provided: One without the lexer module, and one with.
Input Specification
The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens:
Operators
Name
Common name
Character sequence
Op_multiply
multiply
*
Op_divide
divide
/
Op_mod
mod
%
Op_add
plus
+
Op_subtract
minus
-
Op_negate
unary minus
-
Op_less
less than
<
Op_lessequal
less than or equal
<=
Op_greater
greater than
>
Op_greaterequal
greater than or equal
>=
Op_equal
equal
==
Op_notequal
not equal
!=
Op_not
unary not
!
Op_assign
assignment
=
Op_and
logical and
&&
Op_or
logical or
¦¦
The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.
Symbols
Name
Common name
Character
LeftParen
left parenthesis
(
RightParen
right parenthesis
)
LeftBrace
left brace
{
RightBrace
right brace
}
Semicolon
semi-colon
;
Comma
comma
,
Keywords
Name
Character sequence
Keyword_if
if
Keyword_else
else
Keyword_while
while
Keyword_print
print
Keyword_putc
putc
Identifiers and literals
These differ from the the previous tokens, in that each occurrence of them has a value associated with it.
Name
Common name
Format description
Format regex
Value
Identifier
identifier
one or more letter/number/underscore characters, but not starting with a number
[_a-zA-Z][_a-zA-Z0-9]*
as is
Integer
integer literal
one or more digits
[0-9]+
as is, interpreted as a number
Integer
char literal
exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes
'([^'\n]|\\n|\\\\)'
the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n'
String
string literal
zero or more characters (anything except newline or double quote), enclosed by double quotes
"[^"\n]*"
the characters without the double quotes and with escape sequences converted
For char and string literals, the \n escape sequence is supported to represent a new-line character.
For char and string literals, to represent a backslash, use \\.
No other special sequences are supported. This means that:
Char literals cannot represent a single quote character (value 39).
String literals cannot represent strings containing double quote characters.
Zero-width tokens
Name
Location
End_of_input
when the end of the input stream is reached
White space
Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.
"Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =).
Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge.
This means: keywords, identifiers, and integer literals.
e.g. ifprint is recognized as an identifier, instead of the keywords if and print.
e.g. 42fred is invalid, and neither recognized as a number nor an identifier.
Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value).
e.g. & & is invalid, and not interpreted as the && operator.
For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:
if ( p /* meaning n is prime */ ) {
print ( n , " " ) ;
count = count + 1 ; /* number of primes found so far */
}
if(p){print(n," ");count=count+1;}
Complete list of token names
End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract
Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal
Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if
Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen
LeftBrace RightBrace Semicolon Comma Identifier Integer
String
Output Format
The program output should be a sequence of lines, each consisting of the following whitespace-separated fields:
the line number where the token starts
the column number where the token starts
the token name
the token value (only for Identifier, Integer, and String tokens)
the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.
This task is intended to be used as part of a pipeline, with the other compiler tasks - for example:
lex < hello.t | parse | gen | vm
Or possibly:
lex hello.t lex.out
parse lex.out parse.out
gen parse.out gen.out
vm gen.out
This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.
Diagnostics
The following error conditions should be caught:
Error
Example
Empty character constant
''
Unknown escape sequence.
\r
Multi-character constant.
'xx'
End-of-file in comment. Closing comment characters not found.
End-of-file while scanning string literal. Closing string character not found.
End-of-line while scanning string literal. Closing string character not found before end-of-line.
Unrecognized character.
|
Invalid number. Starts like a number, but ends in non-numeric characters.
123abc
Test Cases
Input
Output
Test Case 1:
/*
Hello world
*/
print("Hello, World!\n");
4 1 Keyword_print
4 6 LeftParen
4 7 String "Hello, World!\n"
4 24 RightParen
4 25 Semicolon
5 1 End_of_input
Test Case 2:
/*
Show Ident and Integers
*/
phoenix_number = 142857;
print(phoenix_number, "\n");
4 1 Identifier phoenix_number
4 16 Op_assign
4 18 Integer 142857
4 24 Semicolon
5 1 Keyword_print
5 6 LeftParen
5 7 Identifier phoenix_number
5 21 Comma
5 23 String "\n"
5 27 RightParen
5 28 Semicolon
6 1 End_of_input
Test Case 3:
/*
All lexical tokens - not syntactically correct, but that will
have to wait until syntax analysis
*/
/* Print */ print /* Sub */ -
/* Putc */ putc /* Lss */ <
/* If */ if /* Gtr */ >
/* Else */ else /* Leq */ <=
/* While */ while /* Geq */ >=
/* Lbrace */ { /* Eq */ ==
/* Rbrace */ } /* Neq */ !=
/* Lparen */ ( /* And */ &&
/* Rparen */ ) /* Or */ ||
/* Uminus */ - /* Semi */ ;
/* Not */ ! /* Comma */ ,
/* Mul */ * /* Assign */ =
/* Div */ / /* Integer */ 42
/* Mod */ % /* String */ "String literal"
/* Add */ + /* Ident */ variable_name
/* character literal */ '\n'
/* character literal */ '\\'
/* character literal */ ' '
5 16 Keyword_print
5 40 Op_subtract
6 16 Keyword_putc
6 40 Op_less
7 16 Keyword_if
7 40 Op_greater
8 16 Keyword_else
8 40 Op_lessequal
9 16 Keyword_while
9 40 Op_greaterequal
10 16 LeftBrace
10 40 Op_equal
11 16 RightBrace
11 40 Op_notequal
12 16 LeftParen
12 40 Op_and
13 16 RightParen
13 40 Op_or
14 16 Op_subtract
14 40 Semicolon
15 16 Op_not
15 40 Comma
16 16 Op_multiply
16 40 Op_assign
17 16 Op_divide
17 40 Integer 42
18 16 Op_mod
18 40 String "String literal"
19 16 Op_add
19 40 Identifier variable_name
20 26 Integer 10
21 26 Integer 92
22 26 Integer 32
23 1 End_of_input
Test Case 4:
/*** test printing, embedded \n and comments with lots of '*' ***/
print(42);
print("\nHello World\nGood Bye\nok\n");
print("Print a slash n - \\n.\n");
2 1 Keyword_print
2 6 LeftParen
2 7 Integer 42
2 9 RightParen
2 10 Semicolon
3 1 Keyword_print
3 6 LeftParen
3 7 String "\nHello World\nGood Bye\nok\n"
3 38 RightParen
3 39 Semicolon
4 1 Keyword_print
4 6 LeftParen
4 7 String "Print a slash n - \\n.\n"
4 33 RightParen
4 34 Semicolon
5 1 End_of_input
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #ATS | ATS | (********************************************************************)
(* Usage: lex [INPUTFILE [OUTPUTFILE]]
If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input
or standard output is used, respectively. *)
#define ATS_DYNLOADFLAG 0
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
#define NIL list_nil ()
#define :: list_cons
%{^
/* alloca(3) is needed for ATS exceptions. */
#include <alloca.h>
%}
(********************************************************************)
#define NUM_TOKENS 31
#define RESERVED_WORD_HASHTAB_SIZE 9
#define TOKEN_ELSE 0
#define TOKEN_IF 1
#define TOKEN_PRINT 2
#define TOKEN_PUTC 3
#define TOKEN_WHILE 4
#define TOKEN_MULTIPLY 5
#define TOKEN_DIVIDE 6
#define TOKEN_MOD 7
#define TOKEN_ADD 8
#define TOKEN_SUBTRACT 9
#define TOKEN_NEGATE 10
#define TOKEN_LESS 11
#define TOKEN_LESSEQUAL 12
#define TOKEN_GREATER 13
#define TOKEN_GREATEREQUAL 14
#define TOKEN_EQUAL 15
#define TOKEN_NOTEQUAL 16
#define TOKEN_NOT 17
#define TOKEN_ASSIGN 18
#define TOKEN_AND 19
#define TOKEN_OR 20
#define TOKEN_LEFTPAREN 21
#define TOKEN_RIGHTPAREN 22
#define TOKEN_LEFTBRACE 23
#define TOKEN_RIGHTBRACE 24
#define TOKEN_SEMICOLON 25
#define TOKEN_COMMA 26
#define TOKEN_IDENTIFIER 27
#define TOKEN_INTEGER 28
#define TOKEN_STRING 29
#define TOKEN_END_OF_INPUT 30
typedef token_t =
[i : int | TOKEN_ELSE <= i; i <= TOKEN_END_OF_INPUT]
int i
typedef tokentuple_t = (token_t, String, ullint, ullint)
typedef token_names_vt = @[string][NUM_TOKENS]
vtypedef reserved_words_vt =
@[String][RESERVED_WORD_HASHTAB_SIZE]
vtypedef reserved_word_tokens_vt =
@[token_t][RESERVED_WORD_HASHTAB_SIZE]
vtypedef lookups_vt =
[p_toknames : addr]
[p_wordtab : addr]
[p_toktab : addr]
@{
pf_toknames = token_names_vt @ p_toknames,
pf_wordtab = reserved_words_vt @ p_wordtab,
pf_toktab = reserved_word_tokens_vt @ p_toktab |
toknames = ptr p_toknames,
wordtab = ptr p_wordtab,
toktab = ptr p_toktab
}
fn
reserved_word_lookup
(s : String,
lookups : !lookups_vt,
line_no : ullint,
column_no : ullint) : tokentuple_t =
if string_length s < 2 then
(TOKEN_IDENTIFIER, s, line_no, column_no)
else
let
macdef wordtab = !(lookups.wordtab)
macdef toktab = !(lookups.toktab)
val hashval =
g1uint_mod (g1ofg0 (char2ui s[0] + char2ui s[1]),
g1i2u RESERVED_WORD_HASHTAB_SIZE)
val token = toktab[hashval]
in
if token = TOKEN_IDENTIFIER || s <> wordtab[hashval] then
(TOKEN_IDENTIFIER, s, line_no, column_no)
else
(token, s, line_no, column_no)
end
(********************************************************************)
(* Input allows pushback into a buffer. *)
typedef ch_t =
@{
ichar = int,
line_no = ullint,
column_no = ullint
}
typedef inp_t (n : int) =
[0 <= n]
@{
file = FILEref,
pushback = list (ch_t, n),
line_no = ullint,
column_no = ullint
}
typedef inp_t = [n : int] inp_t n
fn
get_ch (inp : inp_t) : (ch_t, inp_t) =
case+ (inp.pushback) of
| NIL =>
let
val c = fileref_getc (inp.file)
val ch =
@{
ichar = c,
line_no = inp.line_no,
column_no = inp.column_no
}
in
if c = char2i '\n' then
let
val inp =
@{
file = inp.file,
pushback = inp.pushback,
line_no = succ (inp.line_no),
column_no = 1ULL
}
in
(ch, inp)
end
else
let
val inp =
@{
file = inp.file,
pushback = inp.pushback,
line_no = inp.line_no,
column_no = succ (inp.column_no)
}
in
(ch, inp)
end
end
| ch :: pushback =>
let
val inp =
@{
file = inp.file,
pushback = pushback,
line_no = inp.line_no,
column_no = inp.column_no
}
in
(ch, inp)
end
fn
push_back_ch (ch : ch_t,
inp : inp_t) : [n : pos] inp_t n =
let
prval _ = lemma_list_param (inp.pushback)
in
@{
file = inp.file,
pushback = ch :: (inp.pushback),
line_no = inp.line_no,
column_no = inp.column_no
}
end
(********************************************************************)
exception unterminated_comment of (ullint, ullint)
exception unterminated_character_literal of (ullint, ullint)
exception multicharacter_literal of (ullint, ullint)
exception unterminated_string_literal of (ullint, ullint, bool)
exception unsupported_escape of (ullint, ullint, int)
exception invalid_integer_literal of (ullint, ullint, String)
exception unexpected_character of (ullint, ullint, int)
fn
scan_comment (inp : inp_t,
line_no : ullint,
column_no : ullint) : inp_t =
let
fun
loop (inp : inp_t) : inp_t =
let
val (ch, inp) = get_ch inp
in
if (ch.ichar) < 0 then
$raise unterminated_comment (line_no, column_no)
else if (ch.ichar) = char2i '*' then
let
val (ch1, inp) = get_ch inp
in
if (ch.ichar) < 0 then
$raise unterminated_comment (line_no, column_no)
else if (ch1.ichar) = char2i '/' then
inp
else
loop inp
end
else
loop inp
end
in
loop inp
end
fn
skip_spaces_and_comments (inp : inp_t) : [n : pos] inp_t n =
let
fun
loop (inp : inp_t) : [n : pos] inp_t n =
let
val (ch, inp) = get_ch inp
in
if isspace (ch.ichar) then
loop inp
else if (ch.ichar) = char2i '/' then
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '*' then
loop (scan_comment (inp, ch.line_no, ch.column_no))
else
let
val inp = push_back_ch (ch1, inp)
val inp = push_back_ch (ch, inp)
in
inp
end
end
else
push_back_ch (ch, inp)
end
in
loop inp
end
fn
reverse_list_to_string
{m : int}
(lst : list (char, m)) : string m =
let
fun
fill_array {n : nat | n <= m} .<n>.
(arr : &(@[char][m + 1]),
lst : list (char, n),
n : size_t n) : void =
case+ lst of
| NIL => ()
| c :: tail =>
begin
arr[pred n] := c;
fill_array (arr, tail, pred n)
end
prval _ = lemma_list_param lst
val m : size_t m = i2sz (list_length lst)
val (pf, pfgc | p) = array_ptr_alloc<char> (succ m)
val _ = array_initize_elt<char> (!p, succ m, '\0')
val _ = fill_array (!p, lst, m)
in
$UN.castvwtp0 @(pf, pfgc | p)
end
extern fun {}
simple_scan$pred : int -> bool
fun {}
simple_scan {u : nat}
(lst : list (char, u),
inp : inp_t) :
[m : nat]
[n : pos]
(list (char, m), inp_t n) =
let
val (ch, inp) = get_ch inp
in
if simple_scan$pred (ch.ichar) then
simple_scan<> (int2char0 (ch.ichar) :: lst, inp)
else
let
val inp = push_back_ch (ch, inp)
in
(lst, inp)
end
end
fn
is_ident_start (c : int) :<> bool =
isalpha (c) || c = char2i '_'
fn
is_ident_continuation (c : int) :<> bool =
isalnum (c) || c = char2i '_'
fn
scan_identifier_or_reserved_word
(inp : inp_t,
lookups : !lookups_vt) :
(tokentuple_t, [n : pos] inp_t n) =
let
val (ch, inp) = get_ch inp
val _ = assertloc (is_ident_start (ch.ichar))
implement simple_scan$pred<> c = is_ident_continuation c
val (lst, inp) = simple_scan (int2char0 (ch.ichar) :: NIL, inp)
val s = reverse_list_to_string lst
val toktup =
reserved_word_lookup (s, lookups, ch.line_no, ch.column_no)
in
(toktup, inp)
end
fn
scan_integer_literal
(inp : inp_t,
lookups : !lookups_vt) :
(tokentuple_t, [n : pos] inp_t n) =
let
val (ch, inp) = get_ch inp
val _ = assertloc (isdigit (ch.ichar))
implement simple_scan$pred<> c = is_ident_continuation c
val (lst, inp) = simple_scan (int2char0 (ch.ichar) :: NIL, inp)
val s = reverse_list_to_string lst
fun
check_they_are_all_digits
{n : nat} .<n>.
(lst : list (char, n)) : void =
case+ lst of
| NIL => ()
| c :: tail =>
if isdigit c then
check_they_are_all_digits tail
else
$raise invalid_integer_literal (ch.line_no, ch.column_no, s)
val _ = check_they_are_all_digits lst
in
((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)
end
fn
ichar2integer_literal (c : int) : String0 =
let
var buf = @[char][100] ('\0')
val _ = $extfcall (int, "snprintf", addr@ buf, i2sz 99, "%d", c)
val s = string1_copy ($UN.castvwtp0{String0} buf)
in
strnptr2string s
end
fn
scan_character_literal_without_checking_end (inp : inp_t) :
(tokentuple_t, inp_t) =
let
val (ch, inp) = get_ch inp
val _ = assertloc ((ch.ichar) = '\'')
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) < 0 then
$raise unterminated_character_literal (ch.line_no, ch.column_no)
else if (ch1.ichar) = char2i '\\' then
let
val (ch2, inp) = get_ch inp
in
if (ch2.ichar) < 0 then
$raise unterminated_character_literal (ch.line_no,
ch.column_no)
else if (ch2.ichar) = char2i 'n' then
let
val s = ichar2integer_literal (char2i '\n')
in
((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)
end
else if (ch2.ichar) = char2i '\\' then
let
val s = ichar2integer_literal (char2i '\\')
in
((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)
end
else
$raise unsupported_escape (ch1.line_no, ch1.column_no,
ch2.ichar)
end
else
let
val s = ichar2integer_literal (ch1.ichar)
in
((TOKEN_INTEGER, s, ch.line_no, ch.column_no), inp)
end
end
fn
scan_character_literal (inp : inp_t) : (tokentuple_t, inp_t) =
let
val (tok, inp) =
scan_character_literal_without_checking_end inp
val line_no = (tok.2)
val column_no = (tok.3)
fun
check_end (inp : inp_t) : inp_t =
let
val (ch, inp) = get_ch inp
in
if (ch.ichar) = char2i '\'' then
inp
else
let
fun
loop_to_end (ch1 : ch_t,
inp : inp_t) : inp_t =
if (ch1.ichar) < 0 then
$raise unterminated_character_literal (line_no,
column_no)
else if (ch1.ichar) = char2i '\'' then
$raise multicharacter_literal (line_no, column_no)
else
let
val (ch1, inp) = get_ch inp
in
loop_to_end (ch1, inp)
end
val inp = loop_to_end (ch, inp)
in
inp
end
end
val inp = check_end inp
in
(tok, inp)
end
fn
scan_string_literal (inp : inp_t) : (tokentuple_t, inp_t) =
let
val (ch, inp) = get_ch inp
val _ = assertloc ((ch.ichar) = '"')
fun
scan {u : pos}
(lst : list (char, u),
inp : inp_t) :
[m : pos] (list (char, m), inp_t) =
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) < 0 then
$raise unterminated_string_literal (ch.line_no,
ch.column_no, false)
else if (ch1.ichar) = char2i '\n' then
$raise unterminated_string_literal (ch.line_no,
ch.column_no, true)
else if (ch1.ichar) = char2i '"' then
(lst, inp)
else if (ch1.ichar) <> char2i '\\' then
scan (int2char0 (ch1.ichar) :: lst, inp)
else
let
val (ch2, inp) = get_ch inp
in
if (ch2.ichar) = char2i 'n' then
scan ('n' :: '\\' :: lst, inp)
else if (ch2.ichar) = char2i '\\' then
scan ('\\' :: '\\' :: lst, inp)
else
$raise unsupported_escape (ch1.line_no, ch1.column_no,
ch2.ichar)
end
end
val lst = '"' :: NIL
val (lst, inp) = scan (lst, inp)
val lst = '"' :: lst
val s = reverse_list_to_string lst
in
((TOKEN_STRING, s, ch.line_no, ch.column_no), inp)
end
fn
get_next_token (inp : inp_t,
lookups : !lookups_vt) : (tokentuple_t, inp_t) =
let
val inp = skip_spaces_and_comments inp
val (ch, inp) = get_ch inp
val ln = ch.line_no
val cn = ch.column_no
in
if ch.ichar < 0 then
((TOKEN_END_OF_INPUT, "", ln, cn), inp)
else
case+ int2char0 (ch.ichar) of
| ',' => ((TOKEN_COMMA, ",", ln, cn), inp)
| ';' => ((TOKEN_SEMICOLON, ";", ln, cn), inp)
| '\(' => ((TOKEN_LEFTPAREN, "(", ln, cn), inp)
| ')' => ((TOKEN_RIGHTPAREN, ")", ln, cn), inp)
| '\{' => ((TOKEN_LEFTBRACE, "{", ln, cn), inp)
| '}' => ((TOKEN_RIGHTBRACE, "}", ln, cn), inp)
| '*' => ((TOKEN_MULTIPLY, "*", ln, cn), inp)
| '/' => ((TOKEN_DIVIDE, "/", ln, cn), inp)
| '%' => ((TOKEN_MOD, "%", ln, cn), inp)
| '+' => ((TOKEN_ADD, "+", ln, cn), inp)
| '-' => ((TOKEN_SUBTRACT, "-", ln, cn), inp)
| '<' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '=' then
((TOKEN_LESSEQUAL, "<=", ln, cn), inp)
else
let
val inp = push_back_ch (ch1, inp)
in
((TOKEN_LESS, "<", ln, cn), inp)
end
end
| '>' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '=' then
((TOKEN_GREATEREQUAL, ">=", ln, cn), inp)
else
let
val inp = push_back_ch (ch1, inp)
in
((TOKEN_GREATER, ">", ln, cn), inp)
end
end
| '=' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '=' then
((TOKEN_EQUAL, "==", ln, cn), inp)
else
let
val inp = push_back_ch (ch1, inp)
in
((TOKEN_ASSIGN, "=", ln, cn), inp)
end
end
| '!' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '=' then
((TOKEN_NOTEQUAL, "!=", ln, cn), inp)
else
let
val inp = push_back_ch (ch1, inp)
in
((TOKEN_NOT, "!", ln, cn), inp)
end
end
| '&' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '&' then
((TOKEN_AND, "&&", ln, cn), inp)
else
$raise unexpected_character (ch.line_no, ch.column_no,
ch.ichar)
end
| '|' =>
let
val (ch1, inp) = get_ch inp
in
if (ch1.ichar) = char2i '|' then
((TOKEN_OR, "||", ln, cn), inp)
else
$raise unexpected_character (ch.line_no, ch.column_no,
ch.ichar)
end
| '"' =>
let
val inp = push_back_ch (ch, inp)
in
scan_string_literal inp
end
| '\'' =>
let
val inp = push_back_ch (ch, inp)
in
scan_character_literal inp
end
| _ when isdigit (ch.ichar) =>
let
val inp = push_back_ch (ch, inp)
in
scan_integer_literal (inp, lookups)
end
| _ when is_ident_start (ch.ichar) =>
let
val inp = push_back_ch (ch, inp)
in
scan_identifier_or_reserved_word (inp, lookups)
end
| _ => $raise unexpected_character (ch.line_no, ch.column_no,
ch.ichar)
end
fn
fprint_ullint_rightjust (outf : FILEref,
num : ullint) : void =
if num < 10ULL then
fprint! (outf, " ", num)
else if num < 100ULL then
fprint! (outf, " ", num)
else if num < 1000ULL then
fprint! (outf, " ", num)
else if num < 10000ULL then
fprint! (outf, " ", num)
else
fprint! (outf, num)
fn
print_token (outf : FILEref,
toktup : tokentuple_t,
lookups : !lookups_vt) : void =
let
macdef toknames = !(lookups.toknames)
val name = toknames[toktup.0]
val str = (toktup.1)
val line_no = (toktup.2)
val column_no = (toktup.3)
val _ = fprint_ullint_rightjust (outf, line_no)
val _ = fileref_puts (outf, " ")
val _ = fprint_ullint_rightjust (outf, column_no)
val _ = fileref_puts (outf, " ")
val _ = fileref_puts (outf, name)
in
begin
case+ toktup.0 of
| TOKEN_IDENTIFIER => fprint! (outf, " ", str)
| TOKEN_INTEGER => fprint! (outf, " ", str)
| TOKEN_STRING => fprint! (outf, " ", str)
| _ => ()
end;
fileref_putc (outf, '\n')
end
fn
scan_text (outf : FILEref,
inp : inp_t,
lookups : !lookups_vt) : void =
let
fun
loop (inp : inp_t,
lookups : !lookups_vt) : void =
let
val (toktup, inp) = get_next_token (inp, lookups)
in
print_token (outf, toktup, lookups);
if toktup.0 <> TOKEN_END_OF_INPUT then
loop (inp, lookups)
end
in
loop (inp, lookups)
end
(********************************************************************)
fn
main_program (inpf : FILEref,
outf : FILEref) : int =
let
(* Using a simple Scheme program, I found the following perfect
hash for the reserved words, using the sum of the first two
characters as the hash value. *)
var reserved_words =
@[String][RESERVED_WORD_HASHTAB_SIZE]
("if", "print", "else", "", "putc", "", "", "while", "")
var reserved_word_tokens =
@[token_t][RESERVED_WORD_HASHTAB_SIZE]
(TOKEN_IF, TOKEN_PRINT, TOKEN_ELSE, TOKEN_IDENTIFIER,
TOKEN_PUTC, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_WHILE,
TOKEN_IDENTIFIER)
var token_names =
@[string][NUM_TOKENS]
("Keyword_else",
"Keyword_if",
"Keyword_print",
"Keyword_putc",
"Keyword_while",
"Op_multiply",
"Op_divide",
"Op_mod",
"Op_add",
"Op_subtract",
"Op_negate",
"Op_less",
"Op_lessequal",
"Op_greater",
"Op_greaterequal",
"Op_equal",
"Op_notequal",
"Op_not",
"Op_assign",
"Op_and",
"Op_or",
"LeftParen",
"RightParen",
"LeftBrace",
"RightBrace",
"Semicolon",
"Comma",
"Identifier",
"Integer",
"String",
"End_of_input")
var lookups : lookups_vt =
@{
pf_toknames = view@ token_names,
pf_wordtab = view@ reserved_words,
pf_toktab = view@ reserved_word_tokens |
toknames = addr@ token_names,
wordtab = addr@ reserved_words,
toktab = addr@ reserved_word_tokens
}
val inp =
@{
file = inpf,
pushback = NIL,
line_no = 1ULL,
column_no = 1ULL
}
val _ = scan_text (outf, inp, lookups)
val @{
pf_toknames = pf_toknames,
pf_wordtab = pf_wordtab,
pf_toktab = pf_toktab |
toknames = toknames,
wordtab = wordtab,
toktab = toktab
} = lookups
prval _ = view@ token_names := pf_toknames
prval _ = view@ reserved_words := pf_wordtab
prval _ = view@ reserved_word_tokens := pf_toktab
in
0
end
macdef lex_error = "Lexical error: "
implement
main (argc, argv) =
let
val inpfname =
if 2 <= argc then
$UN.cast{string} argv[1]
else
"-"
val outfname =
if 3 <= argc then
$UN.cast{string} argv[2]
else
"-"
in
try
let
val inpf =
if (inpfname : string) = "-" then
stdin_ref
else
fileref_open_exn (inpfname, file_mode_r)
val outf =
if (outfname : string) = "-" then
stdout_ref
else
fileref_open_exn (outfname, file_mode_w)
in
main_program (inpf, outf)
end
with
| ~ unterminated_comment (line_no, column_no) =>
begin
fprintln! (stderr_ref, lex_error,
"unterminated comment starting at ",
line_no, ":", column_no);
1
end
| ~ unterminated_character_literal (line_no, column_no) =>
begin
fprintln! (stderr_ref, lex_error,
"unterminated character literal starting at ",
line_no, ":", column_no);
1
end
| ~ multicharacter_literal (line_no, column_no) =>
begin
fprintln! (stderr_ref, lex_error,
"unsupported multicharacter literal starting at ",
line_no, ":", column_no);
1
end
| ~ unterminated_string_literal (line_no, column_no,
end_of_line) =>
let
val s =
begin
if end_of_line then
"end of line"
else
"end of input"
end : String
in
fprintln! (stderr_ref, lex_error,
"unterminated string literal (", s,
") starting at ", line_no, ":", column_no);
1
end
| ~ unsupported_escape (line_no, column_no, c) =>
begin
fprintln! (stderr_ref, lex_error,
"unsupported escape \\",
int2char0 c, " starting at ",
line_no, ":", column_no);
1
end
| ~ invalid_integer_literal (line_no, column_no, s) =>
begin
fprintln! (stderr_ref, lex_error,
"invalid integer literal ", s,
" starting at ", line_no, ":", column_no);
1
end
| ~ unexpected_character (line_no, column_no, c) =>
begin
fprintln! (stderr_ref, lex_error,
"unexpected character '", int2char0 c,
"' at ", line_no, ":", column_no);
1
end
end
(********************************************************************) |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program commandLine.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
.align 4
/* code section */
.text
.global main
main: @ entry of program
push {fp,lr} @ saves registers
add fp,sp,#8 @ fp <- start address
ldr r4,[fp] @ number of Command line arguments
add r5,fp,#4 @ first parameter address
mov r2,#0 @ init loop counter
loop:
ldr r0,[r5,r2,lsl #2] @ string address parameter
bl affichageMess @ display string
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display carriage return
add r2,#1 @ increment counter
cmp r2,r4 @ number parameters ?
blt loop @ loop
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
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 systeme
pop {r0,r1,r2,r7,lr} @ restaur 2 registres
bx lr @ return
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #ACL2 | ACL2 | ; Single line comment
#| Multi-line
comment |# |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Action.21 | Action! | ;This is a comment
PROC Main() ;This is a comment as well
RETURN |
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Input format:
Given the following program:
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
The output from the Code generator is a virtual assembly code program:
Output from gen, input to VM
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
The first line of the input specifies the datasize required and the number of constant
strings, in the order that they are reference via the code.
The data can be stored in a separate array, or the data can be stored at the beginning of
the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if
referenced at address 2.
If there are one or more constant strings, they come next. The code refers to these
strings by their index. The index starts at 0. So if there are 3 strings, and the code
wants to reference the 3rd string, 2 will be used.
Next comes the actual virtual assembly code. The first number is the code address of that
instruction. After that is the instruction mnemonic, followed by optional operands,
depending on the instruction.
Registers:
sp:
the stack pointer - points to the next top of stack. The stack is a 32-bit integer
array.
pc:
the program counter - points to the current instruction to be performed. The code is an
array of bytes.
Data:
data
string pool
Instructions:
Each instruction is one byte. The following instructions also have a 32-bit integer
operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
Print the word at stack top as a character.
prtc
Print the word at stack top as an integer.
prti
Stack top points to an index into the string pool. Print that entry.
prts
Unconditional stop.
halt
A simple example virtual machine
def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
AST Interpreter task
| #Julia | Julia | mutable struct VM32
code::Vector{UInt8}
stack::Vector{Int32}
data::Vector{Int32}
strings::Vector{String}
offsets::Vector{Int32}
lastargs::Vector{Int32}
ip::Int32
VM32() = new(Vector{UInt8}(), Vector{Int32}(), Vector{Int32}(),
Vector{String}(), Vector{Int32}(), Vector{Int32}(), 1)
end
halt, add, sub, mul, Div, mod, not, neg, and, or, lt, gt, le, ge, ne, eq, prts,
prti, prtc, store, Fetch, push, jmp, jz = UInt8.(collect(1:24))
function assemble(io)
vm = VM32()
header = readline(io)
datasize, nstrings = match(r"\w+:\s*(\d+)\s+\w+:\s*(\d+)", header).captures
vm.data = zeros(Int32, parse(Int, datasize) + 4)
for i in 1:parse(Int, nstrings)
line = replace(strip(readline(io), ['"', '\n']), r"\\." => x -> x[end] == 'n' ? "\n" : string(x[end]))
push!(vm.strings, line)
end
while !eof(io)
line = readline(io)
offset, op, arg1, arg2 = match(r"(\d+)\s+(\w+)\s*(\S+)?\s*(\S+)?", line).captures
op = op in ["fetch", "div"] ? uppercasefirst(op) : op
push!(vm.code, eval(Symbol(op)))
if arg1 != nothing
v = parse(Int32, strip(arg1, ['[', ']', '(', ')']))
foreach(x -> push!(vm.code, x), reinterpret(UInt8, [v]))
end
if arg2 != nothing
push!(vm.lastargs, (x = tryparse(Int32, arg2)) == nothing ? 0 : x)
end
push!(vm.offsets, parse(Int32, offset))
end
vm
end
function runvm(vm)
value() = (x = vm.ip; vm.ip += 4; reinterpret(Int32, vm.code[x:x+3])[1])
tobool(x) = (x != 0)
ops = Dict(
halt => () -> exit(),
add => () -> begin vm.stack[end-1] += vm.stack[end]; pop!(vm.stack); vm.stack[end] end,
sub => () -> begin vm.stack[end-1] -= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,
mul => () -> begin vm.stack[end-1] *= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,
Div => () -> begin vm.stack[end-1] /= vm.stack[end]; pop!(vm.stack); vm.stack[end] end,
mod => () -> begin vm.stack[end-1] %= vm.stack[1]; pop!(vm.stack); vm.stack[end] end,
not => () -> vm.stack[end] = vm.stack[end] ? 0 : 1,
neg => () -> vm.stack[end] = -vm.stack[end],
and => () -> begin vm.stack[end-1] = tobool(vm.stack[end-1]) && tobool(vm.stack[end]) ? 1 : 0; pop!(vm.stack); vm.stack[end] end,
or => () -> begin vm.stack[end-1] = tobool(vm.stack[end-1]) || tobool(vm.stack[end]) ? 1 : 0; pop!(vm.stack); vm.stack[end] end,
lt => () -> begin x = (vm.stack[end-1] < vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
gt => () -> begin x = (vm.stack[end-1] > vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
le => () -> begin x = (vm.stack[end-1] <= vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
ge => () -> begin x = (vm.stack[end-1] >= vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
ne => () -> begin x = (vm.stack[end-1] != vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
eq => () -> begin x = (vm.stack[end-1] == vm.stack[end] ? 1 : 0); pop!(vm.stack); vm.stack[end] = x end,
prts => () -> print(vm.strings[pop!(vm.stack) + 1]),
prti => () -> print(pop!(vm.stack)),
prtc => () -> print(Char(pop!(vm.stack))),
store => () -> vm.data[value() + 1] = pop!(vm.stack),
Fetch => () -> push!(vm.stack, vm.data[value() + 1]),
push => () -> push!(vm.stack, value()),
jmp => () -> vm.ip += value(),
jz => () -> if pop!(vm.stack) == 0 vm.ip += value() else vm.ip += 4 end)
vm.ip = 1
while true
op = vm.code[vm.ip]
vm.ip += 1
ops[op]()
end
end
const testasm = """
Datasize: 1 Strings: 2
"count is: "
"\\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt """
const iob = IOBuffer(testasm)
const vm = assemble(iob)
runvm(vm)
|
http://rosettacode.org/wiki/Compiler/code_generator | Compiler/code generator | A code generator translates the output of the syntax analyzer and/or semantic analyzer
into lower level code, either assembly, object, or virtual.
Task[edit]
Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the
Virtual machine interpreter. The output is in text format, and represents virtual assembly code.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
while.ast can be input into the code generator.
The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code.
Run as: lex < while.t | parse | gen
Input to lex
Output from lex, input to parse
Output from parse
Output from gen, input to VM
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
Input format
As shown in the table, above, the output from the syntax analyzer is a flattened AST.
In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes.
Loading this data into an internal parse tree should be as simple as:
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";"
return None
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Output format - refer to the table above
The first line is the header: Size of data, and number of constant strings.
size of data is the number of 32-bit unique variables used. In this example, one variable, count
number of constant strings is just that - how many there are
After that, the constant strings
Finally, the assembly code
Registers
sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array.
pc: the program counter - points to the current instruction to be performed. The code is an array of bytes.
Data
32-bit integers and strings
Instructions
Each instruction is one byte. The following instructions also have a 32-bit integer operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
prtc
Print the word at stack top as a character.
prti
Print the word at stack top as an integer.
prts
Stack top points to an index into the string pool. Print that entry.
halt
Unconditional stop.
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Virtual Machine Interpreter task
AST Interpreter task
| #J | J | require'format/printf'
(opcodes)=: opcodes=: ;:{{)n
fetch store push add sub mul div mod lt gt le ge
eq ne and or neg not jmp jz prtc prts prti halt
}}-.LF
(ndDisp)=: ndDisp=:;:{{)n
Sequence Multiply Divide Mod Add Subtract Negate Less LessEqual Greater
GreaterEqual Equal NotEqual Not And Or Prts Assign Prti x If x x x While
x x Prtc x Identifier String Integer
}}-.LF
ndDisp,.ndOps=:;: {{)n
x mul div mod add sub neg lt le gt ge eq ne not and or
x x x x x x x x x x x x x x x x
}} -.LF
load_ast=: {{
'node_types node_values'=: 2{.|:(({.,&<&<}.@}.)~ i.&' ');._2 y
1{::0 load_ast ''
:
node_type=. x{::node_types
if. node_type-:,';' do. x;a: return.end.
node_value=. x{::node_values
if. -.''-:node_value do.x;<node_type make_leaf node_value return.end.
'x left'=.(x+1) load_ast''
'x right'=.(x+1) load_ast''
x;<node_type make_node left right
}}
make_leaf=: ;
make_node=: {{m;n;<y}}
typ=: 0&{::
val=: left=: 1&{::
right=: 2&{::
gen_code=: {{
if.y-:'' do.'' return.end.
V=. val y
W=. ;2}.y
select.op=.typ y
case.'Integer'do.gen_int _".V [ gen_op push
case.'String'do.gen_string V [ gen_op push
case.'Identifier'do.gen_var V [ gen_op fetch
case.'Assign'do.gen_var left V [ gen_op store [ gen_code W
case.;:'Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or'do.
gen_op op [ gen_code W [ gen_code V
case.;:'Not Negate'do.
gen_op op [ gen_code V
case.'If'do.
p1=. gen_int 0 [ gen_op jz [ gen_code V
gen_code left W
if.#right W do.
p2=. gen_int 0 [ gen_op jmp
gen_code right W [ p1 patch #object
p2 patch #object
else.
p1 patch #object
end.
case.'While'do.
p1=. #object
p2=. gen_int 0 [ gen_op jz [ gen_code V
gen_int p1 [ gen_op jmp [ gen_code W
p2 patch #object
case.'Prtc'do.gen_op prtc [ gen_code V
case.'Prti'do.gen_op prti [ gen_code V
case.'Prts'do.gen_op prts [ gen_code V
case.'Sequence'do.
gen_code W [ gen_code V
case.do.error'unknown node type ',typ y
end.
}}
gen_op=:{{
arg=. boxopen y
if. -.arg e. opcodes do.
arg=. (ndDisp i. arg){ndOps
end.
assert. arg e. opcodes
object=: object,opcodes i.arg
}}
gen_int=:{{
if.#$y do.num=. _ ".y
else.num=. y end.
r=. #object
object=: object,(4#256)#:num
r
}}
gen_string=: {{
strings=:~.strings,<y
gen_int strings i.<y
}}
gen_var=: {{
vars=:~.vars,<y
gen_int vars i.<y
}}
patch=: {{ #object=: ((4#256)#:y) (x+i.4)} object }}
error=: {{echo y throw.}}
getint=: _2147483648+4294967296|2147483648+256#.]
list_code=: {{
r=.'Datasize: %d Strings: %d\n' sprintf vars;&#strings
r=.r,;strings,each LF
pc=. 0
lim=.<:#object
while.do.
op=.(pc{object){::opcodes
r=.r,'%5d %s'sprintf pc;op
pc=. pc+1
i=. getint (lim<.pc+i.4){object
k=. 0
select.op
case.fetch;store do.k=.4[r=.r,' [%d]'sprintf i
case.push do.k=.4[r=.r,' %d'sprintf i
case.jmp;jz do.k=.4[r=.r,' (%d) %d'sprintf (i-pc);i
case.halt do.r=.r,LF return.
end.
pc=.pc+k
r=.r,LF
end.
}}
gen=: {{
object=:strings=:vars=:i.0
gen_code load_ast y
list_code gen_op halt
}} |
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #Julia | Julia |
function comparesorts(tosort)
a = shuffle(["i", "m", "q"])
iavg = mavg = qavg = 0.0
for c in a
if c == "i"
iavg = sum(i -> @elapsed(sort(tosort, alg=InsertionSort)), 1:100) / 100.0
elseif c == "m"
mavg = sum(i -> @elapsed(sort(tosort, alg=MergeSort)), 1:100) / 100.0
elseif c == "q"
qavg = sum(i -> @elapsed(sort(tosort, alg=QuickSort)), 1:100) / 100.0
end
end
iavg, mavg, qavg
end
allones = fill(1, 40000)
sequential = collect(1:40000)
randomized = collect(shuffle(1:40000))
comparesorts(allones)
comparesorts(allones)
iavg, mavg, qavg = comparesorts(allones)
println("Average sort times for 40000 ones:")
println("\tinsertion sort:\t$iavg\n\tmerge sort:\t$mavg\n\tquick sort\t$qavg")
comparesorts(sequential)
comparesorts(sequential)
iavg, mavg, qavg = comparesorts(sequential)
println("Average sort times for 40000 presorted:")
println("\tinsertion sort:\t$iavg\n\tmerge sort:\t$mavg\n\tquick sort\t$qavg")
comparesorts(randomized)
comparesorts(randomized)
iavg, mavg, qavg = comparesorts(randomized)
println("Average sort times for 40000 randomized:")
println("\tinsertion sort:\t$iavg\n\tmerge sort:\t$mavg\n\tquick sort\t$qavg")
|
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #Kotlin | Kotlin | // Version 1.2.31
import java.util.Random
import kotlin.system.measureNanoTime
typealias Sorter = (IntArray) -> Unit
val rand = Random()
fun onesSeq(n: Int) = IntArray(n) { 1 }
fun ascendingSeq(n: Int) = shuffledSeq(n).sorted().toIntArray()
fun shuffledSeq(n: Int) = IntArray(n) { 1 + rand.nextInt(10 * n) }
fun bubbleSort(a: IntArray) {
var n = a.size
do {
var n2 = 0
for (i in 1 until n) {
if (a[i - 1] > a[i]) {
val tmp = a[i]
a[i] = a[i - 1]
a[i - 1] = tmp
n2 = i
}
}
n = n2
} while (n != 0)
}
fun insertionSort(a: IntArray) {
for (index in 1 until a.size) {
val value = a[index]
var subIndex = index - 1
while (subIndex >= 0 && a[subIndex] > value) {
a[subIndex + 1] = a[subIndex]
subIndex--
}
a[subIndex + 1] = value
}
}
fun quickSort(a: IntArray) {
fun sorter(first: Int, last: Int) {
if (last - first < 1) return
val pivot = a[first + (last - first) / 2]
var left = first
var right = last
while (left <= right) {
while (a[left] < pivot) left++
while (a[right] > pivot) right--
if (left <= right) {
val tmp = a[left]
a[left] = a[right]
a[right] = tmp
left++
right--
}
}
if (first < right) sorter(first, right)
if (left < last) sorter(left, last)
}
sorter(0, a.lastIndex)
}
fun radixSort(a: IntArray) {
val tmp = IntArray(a.size)
for (shift in 31 downTo 0) {
tmp.fill(0)
var j = 0
for (i in 0 until a.size) {
val move = (a[i] shl shift) >= 0
val toBeMoved = if (shift == 0) !move else move
if (toBeMoved)
tmp[j++] = a[i]
else {
a[i - j] = a[i]
}
}
for (i in j until tmp.size) tmp[i] = a[i - j]
for (i in 0 until a.size) a[i] = tmp[i]
}
}
val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence
fun shellSort(a: IntArray) {
for (gap in gaps) {
for (i in gap until a.size) {
val temp = a[i]
var j = i
while (j >= gap && a[j - gap] > temp) {
a[j] = a[j - gap]
j -= gap
}
a[j] = temp
}
}
}
fun main(args: Array<String>) {
val runs = 10
val lengths = listOf(1, 10, 100, 1_000, 10_000, 100_000)
val sorts = listOf<Sorter>(
::bubbleSort, ::insertionSort, ::quickSort, ::radixSort, ::shellSort
)
/* allow JVM to compile sort functions before timings start */
for (sort in sorts) sort(intArrayOf(1))
val sortTitles = listOf("Bubble", "Insert", "Quick ", "Radix ", "Shell ")
val seqTitles = listOf("All Ones", "Ascending", "Shuffled")
val totals = List(seqTitles.size) { List(sorts.size) { LongArray(lengths.size) } }
for ((k, n) in lengths.withIndex()) {
val seqs = listOf(onesSeq(n), ascendingSeq(n), shuffledSeq(n))
repeat(runs) {
for (i in 0 until seqs.size) {
for (j in 0 until sorts.size) {
val seq = seqs[i].copyOf()
totals[i][j][k] += measureNanoTime { sorts[j](seq) }
}
}
}
}
println("All timings in micro-seconds\n")
print("Sequence length")
for (len in lengths) print("%8d ".format(len))
println("\n")
for (i in 0 until seqTitles.size) {
println(" ${seqTitles[i]}:")
for (j in 0 until sorts.size) {
print(" ${sortTitles[j]} ")
for (k in 0 until lengths.size) {
val time = totals[i][j][k] / runs / 1_000
print("%8d ".format(time))
}
println()
}
println("\n")
}
} |
http://rosettacode.org/wiki/Compiler/AST_interpreter | Compiler/AST interpreter | An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is as simple as (pseudo code)
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
The interpreter algorithm is relatively simple
interp(x)
if x == NULL return NULL
elif x.node_type == Integer return x.value converted to an integer
elif x.node_type == Ident return the current value of variable x.value
elif x.node_type == String return x.value
elif x.node_type == Assign
globals[x.left.value] = interp(x.right)
return NULL
elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)
elif x.node_type is a unary operator, return return operator interp(x.left)
elif x.node_type == If
if (interp(x.left)) then interp(x.right.left)
else interp(x.right.right)
return NULL
elif x.node_type == While
while (interp(x.left)) do interp(x.right)
return NULL
elif x.node_type == Prtc
print interp(x.left) as a character, no newline
return NULL
elif x.node_type == Prti
print interp(x.left) as an integer, no newline
return NULL
elif x.node_type == Prts
print interp(x.left) as a string, respecting newlines ("\n")
return NULL
elif x.node_type == Sequence
interp(x.left)
interp(x.right)
return NULL
else
error("unknown node type")
Notes:
Because of the simple nature of our tiny language, Semantic analysis is not needed.
Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.
This means, for instance, that 3 / 2 should result in 1.
For division when one of the operands is negative, the result should be truncated towards 0.
This means, for instance, that 3 / -2 should result in -1.
Test program
prime.t
lex <prime.t | parse | interp
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
101 is prime
Total primes found: 26
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
| #Wren | Wren | import "/dynamic" for Enum, Struct, Tuple
import "/fmt" for Conv
import "/ioutil" for FileUtil
var nodes = [
"Ident",
"String",
"Integer",
"Sequence",
"If",
"Prtc",
"Prts",
"Prti",
"While",
"Assign",
"Negate",
"Not",
"Mul",
"Div",
"Mod",
"Add",
"Sub",
"Lss",
"Leq",
"Gtr",
"Geq",
"Eql",
"Neq",
"And",
"Or"
]
var Node = Enum.create("Node", nodes)
var Tree = Struct.create("Tree", ["nodeType", "left", "right", "value"])
// dependency: Ordered by Node value, must remain in same order as Node enum
var Atr = Tuple.create("Atr", ["enumText", "nodeType"])
var atrs = [
Atr.new("Identifier", Node.Ident),
Atr.new("String", Node.String),
Atr.new("Integer", Node.Integer),
Atr.new("Sequence", Node.Sequence),
Atr.new("If", Node.If),
Atr.new("Prtc", Node.Prtc),
Atr.new("Prts", Node.Prts),
Atr.new("Prti", Node.Prti),
Atr.new("While", Node.While),
Atr.new("Assign", Node.Assign),
Atr.new("Negate", Node.Negate),
Atr.new("Not", Node.Not),
Atr.new("Multiply", Node.Mul),
Atr.new("Divide", Node.Div),
Atr.new("Mod", Node.Mod),
Atr.new("Add", Node.Add),
Atr.new("Subtract", Node.Sub),
Atr.new("Less", Node.Lss),
Atr.new("LessEqual", Node.Leq),
Atr.new("Greater", Node.Gtr),
Atr.new("GreaterEqual", Node.Geq),
Atr.new("Equal", Node.Eql),
Atr.new("NotEqual", Node.Neq),
Atr.new("And", Node.And),
Atr.new("Or", Node.Or),
]
var stringPool = []
var globalNames = []
var globalValues = {}
var reportError = Fn.new { |msg| Fiber.abort("error : %(msg)") }
var makeNode = Fn.new { |nodeType, left, right| Tree.new(nodeType, left, right, 0) }
var makeLeaf = Fn.new { |nodeType, value| Tree.new(nodeType, null, null, value) }
// interpret the parse tree
var interp // recursive function
interp = Fn.new { |x|
if (!x) return 0
var nt = x.nodeType
if (nt == Node.Integer) return x.value
if (nt == Node.Ident) return globalValues[x.value]
if (nt == Node.String) return x.value
if (nt == Node.Assign) {
var n = interp.call(x.right)
globalValues[x.left.value] = n
return n
}
if (nt == Node.Add) return interp.call(x.left) + interp.call(x.right)
if (nt == Node.Sub) return interp.call(x.left) - interp.call(x.right)
if (nt == Node.Mul) return interp.call(x.left) * interp.call(x.right)
if (nt == Node.Div) return (interp.call(x.left) / interp.call(x.right)).truncate
if (nt == Node.Mod) return interp.call(x.left) % interp.call(x.right)
if (nt == Node.Lss) return Conv.btoi(interp.call(x.left) < interp.call(x.right))
if (nt == Node.Gtr) return Conv.btoi(interp.call(x.left) > interp.call(x.right))
if (nt == Node.Leq) return Conv.btoi(interp.call(x.left) <= interp.call(x.right))
if (nt == Node.Eql) return Conv.btoi(interp.call(x.left) == interp.call(x.right))
if (nt == Node.Neq) return Conv.btoi(interp.call(x.left) != interp.call(x.right))
if (nt == Node.And) return Conv.btoi(Conv.itob(interp.call(x.left)) && Conv.itob(interp.call(x.right)))
if (nt == Node.Or) return Conv.btoi(Conv.itob(interp.call(x.left)) || Conv.itob(interp.call(x.right)))
if (nt == Node.Negate) return -interp.call(x.left)
if (nt == Node.Not) return (interp.call(x.left) == 0) ? 1 : 0
if (nt == Node.If) {
if (interp.call(x.left) != 0) {
interp.call(x.right.left)
} else {
interp.call(x.right.right)
}
return 0
}
if (nt == Node.While) {
while (interp.call(x.left) != 0) interp.call(x.right)
return 0
}
if (nt == Node.Prtc) {
System.write(String.fromByte(interp.call(x.left)))
return 0
}
if (nt == Node.Prti) {
System.write(interp.call(x.left))
return 0
}
if (nt == Node.Prts) {
System.write(stringPool[interp.call(x.left)])
return 0
}
if (nt == Node.Sequence) {
interp.call(x.left)
interp.call(x.right)
return 0
}
reportError.call("interp: unknown tree type %(x.nodeType)")
}
var getEnumValue = Fn.new { |name|
for (atr in atrs) {
if (atr.enumText == name) return atr.nodeType
}
reportError.call("Unknown token %(name)")
}
var fetchStringOffset = Fn.new { |s|
var d = ""
s = s[1...-1]
var i = 0
while (i < s.count) {
if (s[i] == "\\" && (i+1) < s.count) {
if (s[i+1] == "n") {
d = d + "\n"
i = i + 1
} else if (s[i+1] == "\\") {
d = d + "\\"
i = i + 1
}
} else {
d = d + s[i]
}
i = i + 1
}
s = d
for (i in 0...stringPool.count) {
if (s == stringPool[i]) return i
}
stringPool.add(s)
return stringPool.count - 1
}
var fetchVarOffset = Fn.new { |name|
for (i in 0...globalNames.count) {
if (globalNames[i] == name) return i
}
globalNames.add(name)
return globalNames.count - 1
}
var lines = []
var lineCount = 0
var lineNum = 0
var loadAst // recursive function
loadAst = Fn.new {
var nodeType = 0
var s = ""
if (lineNum < lineCount) {
var line = lines[lineNum].trimEnd(" \t")
lineNum = lineNum + 1
var tokens = line.split(" ").where { |s| s != "" }.toList
var first = tokens[0]
if (first[0] == ";") return null
nodeType = getEnumValue.call(first)
var le = tokens.count
if (le == 2) {
s = tokens[1]
} else if (le > 2) {
var idx = line.indexOf("\"")
s = line[idx..-1]
}
}
if (s != "") {
var n
if (nodeType == Node.Ident) {
n = fetchVarOffset.call(s)
} else if (nodeType == Node.Integer) {
n = Num.fromString(s)
} else if (nodeType == Node.String) {
n = fetchStringOffset.call(s)
} else {
reportError.call("Unknown node type: %(s)")
}
return makeLeaf.call(nodeType, n)
}
var left = loadAst.call()
var right = loadAst.call()
return makeNode.call(nodeType, left, right)
}
lines = FileUtil.readLines("ast.txt")
lineCount = lines.count
var x = loadAst.call()
interp.call(x) |
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #Java | Java | package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
compareAndReportStringsLength(strings);
}
/**
* Compare and report strings length to System.out.
*
* @param strings an array of strings
*/
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
/**
* Compare and report strings length.
*
* @param strings an array of strings
* @param stream the output stream to write results
*/
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
//@todo: StringBuilder may be faster
stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
+ " and " + predicate);
}
}
}
} |
http://rosettacode.org/wiki/Compiler/syntax_analyzer | Compiler/syntax analyzer | A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened format.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a parser module/library/class, it would be great
if two versions of the solution are provided: One without the parser module, and one
with.
Grammar
The simple programming language to be analyzed is more or less a (very tiny) subset of
C. The formal grammar in
Extended Backus-Naur Form (EBNF):
stmt_list = {stmt} ;
stmt = ';'
| Identifier '=' expr ';'
| 'while' paren_expr stmt
| 'if' paren_expr stmt ['else' stmt]
| 'print' '(' prt_list ')' ';'
| 'putc' paren_expr ';'
| '{' stmt_list '}'
;
paren_expr = '(' expr ')' ;
prt_list = (string | expr) {',' (String | expr)} ;
expr = and_expr {'||' and_expr} ;
and_expr = equality_expr {'&&' equality_expr} ;
equality_expr = relational_expr [('==' | '!=') relational_expr] ;
relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;
addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;
multiplication_expr = primary {('*' | '/' | '%') primary } ;
primary = Identifier
| Integer
| '(' expr ')'
| ('+' | '-' | '!') primary
;
The resulting AST should be formulated as a Binary Tree.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
The following table shows the input to lex, lex output, and the AST produced by the parser
Input to lex
Output from lex, input to parse
Output from parse
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Specifications
List of node type names
Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod
Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
In the text below, Null/Empty nodes are represented by ";".
Non-terminal (internal) nodes
For Operators, the following nodes should be created:
Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
For each of the above nodes, the left and right sub-nodes are the operands of the
respective operation.
In pseudo S-Expression format:
(Operator expression expression)
Negate, Not
For these node types, the left node is the operand, and the right node is null.
(Operator expression ;)
Sequence - sub-nodes are either statements or Sequences.
If - left node is the expression, the right node is If node, with it's left node being the
if-true statement part, and the right node being the if-false (else) statement part.
(If expression (If statement else-statement))
If there is not an else, the tree becomes:
(If expression (If statement ;))
Prtc
(Prtc (expression) ;)
Prts
(Prts (String "the string") ;)
Prti
(Prti (Integer 12345) ;)
While - left node is the expression, the right node is the statement.
(While expression statement)
Assign - left node is the left-hand side of the assignment, the right node is the
right-hand side of the assignment.
(Assign Identifier expression)
Terminal (leaf) nodes:
Identifier: (Identifier ident_name)
Integer: (Integer 12345)
String: (String "Hello World!")
";": Empty node
Some simple examples
Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.
This simple program:
a=11;
Produces the following AST, encoded as a binary tree:
Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:
(1) Sequence
(2) |-- ;
(3) |-- Assign
(4) |-- Identifier: a
(5) |-- Integer: 11
In flattened form:
(1) Sequence
(2) ;
(3) Assign
(4) Identifier a
(5) Integer 11
This program:
a=11;
b=22;
c=33;
Produces the following AST:
( 1) Sequence
( 2) |-- Sequence
( 3) | |-- Sequence
( 4) | | |-- ;
( 5) | | |-- Assign
( 6) | | |-- Identifier: a
( 7) | | |-- Integer: 11
( 8) | |-- Assign
( 9) | |-- Identifier: b
(10) | |-- Integer: 22
(11) |-- Assign
(12) |-- Identifier: c
(13) |-- Integer: 33
In flattened form:
( 1) Sequence
( 2) Sequence
( 3) Sequence
( 4) ;
( 5) Assign
( 6) Identifier a
( 7) Integer 11
( 8) Assign
( 9) Identifier b
(10) Integer 22
(11) Assign
(12) Identifier c
(13) Integer 33
Pseudo-code for the parser.
Uses Precedence Climbing for expression parsing, and
Recursive Descent for statement parsing. The AST is also built:
def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
Once the AST is built, it should be output in a flattened format. This can be as simple as the following
def prt_ast(t)
if t == NULL
print(";\n")
else
print(t.node_type)
if t.node_type in [Identifier, Integer, String] # leaf node
print the value of the Ident, Integer or String, "\n"
else
print("\n")
prt_ast(t.left)
prt_ast(t.right)
If the AST is correctly built, loading it into a subsequent program should be as simple as
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Finally, the AST can also be tested by running it against one of the AST Interpreter solutions.
Test program, assuming this is in a file called prime.t
lex <prime.t | parse
Input to lex
Output from lex, input to parse
Output from parse
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
4 1 Identifier count
4 7 Op_assign
4 9 Integer 1
4 10 Semicolon
5 1 Identifier n
5 3 Op_assign
5 5 Integer 1
5 6 Semicolon
6 1 Identifier limit
6 7 Op_assign
6 9 Integer 100
6 12 Semicolon
7 1 Keyword_while
7 7 LeftParen
7 8 Identifier n
7 10 Op_less
7 12 Identifier limit
7 17 RightParen
7 19 LeftBrace
8 5 Identifier k
8 6 Op_assign
8 7 Integer 3
8 8 Semicolon
9 5 Identifier p
9 6 Op_assign
9 7 Integer 1
9 8 Semicolon
10 5 Identifier n
10 6 Op_assign
10 7 Identifier n
10 8 Op_add
10 9 Integer 2
10 10 Semicolon
11 5 Keyword_while
11 11 LeftParen
11 12 LeftParen
11 13 Identifier k
11 14 Op_multiply
11 15 Identifier k
11 16 Op_lessequal
11 18 Identifier n
11 19 RightParen
11 21 Op_and
11 24 LeftParen
11 25 Identifier p
11 26 RightParen
11 27 RightParen
11 29 LeftBrace
12 9 Identifier p
12 10 Op_assign
12 11 Identifier n
12 12 Op_divide
12 13 Identifier k
12 14 Op_multiply
12 15 Identifier k
12 16 Op_notequal
12 18 Identifier n
12 19 Semicolon
13 9 Identifier k
13 10 Op_assign
13 11 Identifier k
13 12 Op_add
13 13 Integer 2
13 14 Semicolon
14 5 RightBrace
15 5 Keyword_if
15 8 LeftParen
15 9 Identifier p
15 10 RightParen
15 12 LeftBrace
16 9 Keyword_print
16 14 LeftParen
16 15 Identifier n
16 16 Comma
16 18 String " is prime\n"
16 31 RightParen
16 32 Semicolon
17 9 Identifier count
17 15 Op_assign
17 17 Identifier count
17 23 Op_add
17 25 Integer 1
17 26 Semicolon
18 5 RightBrace
19 1 RightBrace
20 1 Keyword_print
20 6 LeftParen
20 7 String "Total primes found: "
20 29 Comma
20 31 Identifier count
20 36 Comma
20 38 String "\n"
20 42 RightParen
20 43 Semicolon
21 1 End_of_input
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier n
Integer 1
Assign
Identifier limit
Integer 100
While
Less
Identifier n
Identifier limit
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier k
Integer 3
Assign
Identifier p
Integer 1
Assign
Identifier n
Add
Identifier n
Integer 2
While
And
LessEqual
Multiply
Identifier k
Identifier k
Identifier n
Identifier p
Sequence
Sequence
;
Assign
Identifier p
NotEqual
Multiply
Divide
Identifier n
Identifier k
Identifier k
Identifier n
Assign
Identifier k
Add
Identifier k
Integer 2
If
Identifier p
If
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier n
;
Prts
String " is prime\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
;
Sequence
Sequence
Sequence
;
Prts
String "Total primes found: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #ObjectIcon | ObjectIcon | # -*- ObjectIcon -*-
#
# The Rosetta Code Tiny-Language Parser, in Object Icon.
#
# This implementation is based closely on the pseudocode and the C
# reference implementation.
#
import io
record token_record (line_no, column_no, tok, tokval)
record token_getter (nxt, curr)
procedure main (args)
local inpf_name, outf_name
local inpf, outf
local nexttok, currtok, current_token, gettok
local ast
inpf_name := "-"
outf_name := "-"
if 1 <= *args then inpf_name := args[1]
if 2 <= *args then outf_name := args[2]
inpf :=
if inpf_name == "-" then
FileStream.stdin
else
(FileStream(inpf_name, FileOpt.RDONLY) | stop(&why))
outf :=
if outf_name == "-" then
FileStream.stdout
else
(FileStream(outf_name, ior(FileOpt.WRONLY,
FileOpt.TRUNC,
FileOpt.CREAT)) | stop(&why))
current_token := [&null]
nexttok := create generate_tokens(inpf, current_token)
currtok := create get_current_token (current_token)
gettok := token_getter(nexttok, currtok)
ast := parse(gettok)
prt_ast(outf, ast)
close(inpf)
close(outf)
end
procedure prt_ast (outf, ast)
if *ast = 0 then {
write(outf, ";")
} else {
writes(outf, ast[1])
if ast[1] == ("Identifier" | "Integer" | "String") then {
write(outf, " ", ast[2])
} else {
write(outf)
prt_ast(outf, ast[2])
prt_ast(outf, ast[3])
}
}
end
procedure generate_tokens (inpf, current_token)
local s
while s := read(inpf) do {
if trim(s) ~== "" then {
current_token[1] := string_to_token_record(s)
suspend current_token[1]
}
}
end
procedure get_current_token (current_token)
repeat (suspend current_token[1])
end
procedure string_to_token_record (s)
local line_no, column_no, tok, tokval
static spaces
initial {
spaces := ' \t\f\v\r\n'
}
trim(s) ? {
tab(many(spaces))
line_no := integer(tab(many(&digits)))
tab(many(spaces))
column_no := integer(tab(many(&digits)))
tab(many(spaces))
tok := tab(many(&letters ++ '_'))
tab(many(spaces))
tokval := tab(0)
}
return token_record(line_no, column_no, tok, tokval)
end
procedure parse (gettok)
local tok
local t
t := []
@gettok.nxt
tok := "Not End_of_input"
while tok ~== "End_of_input" do {
t := ["Sequence", t, stmt(gettok)]
tok := (@gettok.curr).tok
}
return t
end
procedure stmt (gettok)
local e, s, t, v
local tok
local done
t := []
if accept(gettok, "Keyword_if") then {
e := paren_expr(gettok)
s := stmt(gettok)
t := ["If", e, ["If", s,
if accept(gettok, "Keyword_else")
then stmt(gettok) else []]]
} else if accept(gettok, "Keyword_putc") then {
t := ["Prtc", paren_expr(gettok), []]
expect(gettok, "Putc", "Semicolon")
} else if accept(gettok, "Keyword_print") then {
expect(gettok, "Print", "LeftParen")
done := &no
while /done do {
tok := @gettok.curr
if tok.tok == "String" then {
e := ["Prts", ["String", tok.tokval], []]
@gettok.nxt
} else {
e := ["Prti", expr(gettok, 0), []]
}
t := ["Sequence", t, e]
accept(gettok, "Comma") | (done := &yes)
}
expect(gettok, "Print", "RightParen")
expect(gettok, "Print", "Semicolon")
} else if (@gettok.curr).tok == "Semicolon" then {
@gettok.nxt
} else if (@gettok.curr).tok == "Identifier" then {
v := ["Identifier", (@gettok.curr).tokval]
@gettok.nxt
expect(gettok, "assign", "Op_assign")
t := ["Assign", v, expr(gettok, 0)]
expect(gettok, "assign", "Semicolon")
} else if accept(gettok, "Keyword_while") then {
e := paren_expr(gettok)
t := ["While", e, stmt(gettok)]
} else if accept(gettok, "LeftBrace") then {
until (@gettok.curr).tok == ("RightBrace" | "End_of_input") do {
t := ["Sequence", t, stmt(gettok)]
}
expect(gettok, "Lbrace", "RightBrace")
} else if (@gettok.curr).tok ~== "End_of_input" then {
tok := @gettok.curr
error(tok, ("expecting start of statement, found '" ||
tok_text(tok.tok) || "'"))
}
return t
end
procedure paren_expr (gettok)
local x
expect(gettok, "paren_expr", "LeftParen");
x := expr(gettok, 0);
expect(gettok, "paren_expr", "RightParen");
return x
end
procedure expr (gettok, p)
local tok, save_tok
local x, y
local q
tok := @gettok.curr
case tok.tok of {
"LeftParen" : {
x := paren_expr(gettok)
}
"Op_subtract" : {
@gettok.nxt
y := expr(gettok, precedence("Op_negate"))
x := ["Negate", y, []]
}
"Op_add" : {
@gettok.nxt
x := expr(gettok, precedence("Op_negate"))
}
"Op_not" : {
@gettok.nxt
y := expr(gettok, precedence("Op_not"))
x := ["Not", y, []]
}
"Identifier" : {
x := ["Identifier", tok.tokval]
@gettok.nxt
}
"Integer" : {
x := ["Integer", tok.tokval]
@gettok.nxt
}
default : {
error(tok, "Expecting a primary, found: " || tok_text(tok.tok))
}
}
while (tok := @gettok.curr &
is_binary(tok.tok) &
p <= precedence(tok.tok)) do
{
save_tok := tok
@gettok.nxt
q := precedence(save_tok.tok)
if not is_right_associative(save_tok.tok) then q +:= 1
x := [operator(save_tok.tok), x, expr(gettok, q)]
}
return x
end
procedure accept (gettok, tok)
local nxt
if (@gettok.curr).tok == tok then nxt := @gettok.nxt else fail
return nxt
end
procedure expect (gettok, msg, tok)
if (@gettok.curr).tok ~== tok then {
error(@gettok.curr,
msg || ": Expecting '" || tok_text(tok) || "', found '" ||
tok_text((@gettok.curr).tok) || "'")
}
return @gettok.nxt
end
procedure error (token, msg)
write("(", token.line_no, ", ", token.column_no, ") error: ", msg)
exit(1)
end
procedure precedence (tok)
local p
case tok of {
"Op_multiply" : p := 13
"Op_divide" : p := 13
"Op_mod" : p := 13
"Op_add" : p := 12
"Op_subtract" : p := 12
"Op_negate" : p := 14
"Op_not" : p := 14
"Op_less" : p := 10
"Op_lessequal" : p := 10
"Op_greater" : p := 10
"Op_greaterequal" : p := 10
"Op_equal" : p := 9
"Op_notequal" : p := 9
"Op_and" : p := 5
"Op_or" : p := 4
default : p := -1
}
return p
end
procedure is_binary (tok)
return ("Op_add" |
"Op_subtract" |
"Op_multiply" |
"Op_divide" |
"Op_mod" |
"Op_less" |
"Op_lessequal" |
"Op_greater" |
"Op_greaterequal" |
"Op_equal" |
"Op_notequal" |
"Op_and" |
"Op_or") == tok
fail
end
procedure is_right_associative (tok)
# None of the current operators is right associative.
fail
end
procedure operator (tok)
local s
case tok of {
"Op_multiply" : s := "Multiply"
"Op_divide" : s := "Divide"
"Op_mod" : s := "Mod"
"Op_add" : s := "Add"
"Op_subtract" : s := "Subtract"
"Op_negate" : s := "Negate"
"Op_not" : s := "Not"
"Op_less" : s := "Less"
"Op_lessequal" : s := "LessEqual"
"Op_greater" : s := "Greater"
"Op_greaterequal" : s := "GreaterEqual"
"Op_equal" : s := "Equal"
"Op_notequal" : s := "NotEqual"
"Op_and" : s := "And"
"Op_or" : s := "Or"
}
return s
end
procedure tok_text (tok)
local s
case tok of {
"Keyword_else" : s := "else"
"Keyword_if" : s := "if"
"Keyword_print" : s := "print"
"Keyword_putc" : s := "putc"
"Keyword_while" : s := "while"
"Op_multiply" : s := "*"
"Op_divide" : s := "/"
"Op_mod" : s := "%"
"Op_add" : s := "+"
"Op_subtract" : s := "-"
"Op_negate" : s := "-"
"Op_less" : s := "<"
"Op_lessequal" : s := "<="
"Op_greater" : s := ">"
"Op_greaterequal" : s := ">="
"Op_equal" : s := "=="
"Op_notequal" : s := "!="
"Op_not" : s := "!"
"Op_assign" : s := "="
"Op_and" : s := "&&"
"Op_or" : s := "||"
"LeftParen" : s := "("
"RightParen" : s := ")"
"LeftBrace" : s := "{"
"RightBrace" : s := "}"
"Semicolon" : s := ";"
"Comma" : s := ","
"Identifier" : s := "Ident"
"Integer" : s := "Integer literal"
"String" : s := "String literal"
"End_of_input" : s := "EOI"
}
return s
end |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Common_Lisp | Common Lisp | (defun next-life (array &optional results)
(let* ((dimensions (array-dimensions array))
(results (or results (make-array dimensions :element-type 'bit))))
(destructuring-bind (rows columns) dimensions
(labels ((entry (row col)
"Return array(row,col) for valid (row,col) else 0."
(if (or (not (< -1 row rows))
(not (< -1 col columns)))
0
(aref array row col)))
(neighbor-count (row col &aux (count 0))
"Return the sum of the neighbors of (row,col)."
(dolist (r (list (1- row) row (1+ row)) count)
(dolist (c (list (1- col) col (1+ col)))
(unless (and (eql r row) (eql c col))
(incf count (entry r c))))))
(live-or-die? (current-state neighbor-count)
(if (or (and (eql current-state 1)
(<= 2 neighbor-count 3))
(and (eql current-state 0)
(eql neighbor-count 3)))
1
0)))
(dotimes (row rows results)
(dotimes (column columns)
(setf (aref results row column)
(live-or-die? (aref array row column)
(neighbor-count row column)))))))))
(defun print-grid (grid &optional (out *standard-output*))
(destructuring-bind (rows columns) (array-dimensions grid)
(dotimes (r rows grid)
(dotimes (c columns (terpri out))
(write-char (if (zerop (aref grid r c)) #\+ #\#) out)))))
(defun run-life (&optional world (iterations 10) (out *standard-output*))
(let* ((world (or world (make-array '(10 10) :element-type 'bit)))
(result (make-array (array-dimensions world) :element-type 'bit)))
(do ((i 0 (1+ i))) ((eql i iterations) world)
(terpri out) (print-grid world out)
(psetq world (next-life world result)
result world)))) |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #QB64 | QB64 | Type Point
x As Double
y As Double
End Type
Dim p As Point
p.x = 15.42
p.y = 2.412
Print p.x; p.y |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Quackery | Quackery |
[ ' [ 0 0 ] ] is point ( --> [ )
[ 0 ] is x ( --> n )
[ 1 ] is y ( --> n )
point
dup x peek echo cr
99 swap y poke
y peek echo cr |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, C, R2;
[SetVid($13); \set 320x200x8 graphics mode
C:= 0; \initialize point counter
repeat X:= Ran(31)-15; \range -15..+15
Y:= Ran(31)-15;
R2:= X*X + Y*Y;
if R2>=10*10 & R2<=15*15 then
[Point(X+160, Y+100, $F); C:= C+1];
until C >= 100;
C:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
] |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Axe | Axe | If 1
YEP()
End |
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #J | J | require'regex'
commatize=:3 :0"1 L:1 0
(i.0) commatize y
:
NB. deal with all those rules about options
opts=. boxopen x
char=. (#~ ' '&=@{.@(0&#)@>) opts
num=. ;opts-.char
delim=. 0 {:: char,<','
'begin period'=. _1 0+2{.num,(#num)}.1 3
NB. initialize
prefix=. begin {.y
text=. begin }. y
NB. process
'start len'=. ,'[1-9][0-9]*' rxmatch text
if.0=len do. y return. end.
number=. (start,:len) [;.0 text
numb=. (>:period|<:#number){.number
fixed=. numb,;delim&,each (-period)<\ (#numb)}.number
prefix,(start{.text),fixed,(start+len)}.text
) |
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #Java | Java | import java.io.File;
import java.util.*;
import java.util.regex.*;
public class CommatizingNumbers {
public static void main(String[] args) throws Exception {
commatize("pi=3.14159265358979323846264338327950288419716939937510582"
+ "097494459231", 6, 5, " ");
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 "
+ "trillion).", 0, 3, ".");
try (Scanner sc = new Scanner(new File("input.txt"))) {
while(sc.hasNext())
commatize(sc.nextLine());
}
}
static void commatize(String s) {
commatize(s, 0, 3, ",");
}
static void commatize(String s, int start, int step, String ins) {
if (start < 0 || start > s.length() || step < 1 || step > s.length())
return;
Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start));
StringBuffer result = new StringBuffer(s.substring(0, start));
if (m.find()) {
StringBuilder sb = new StringBuilder(m.group(1)).reverse();
for (int i = step; i < sb.length(); i += step)
sb.insert(i++, ins);
m.appendReplacement(result, sb.reverse().toString());
}
System.out.println(m.appendTail(result));
}
} |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #C | C | #include <stdbool.h>
#include <string.h>
static bool
strings_are_equal(const char **strings, size_t nstrings)
{
for (size_t i = 1; i < nstrings; i++)
if (strcmp(strings[0], strings[i]) != 0)
return false;
return true;
}
static bool
strings_are_in_ascending_order(const char **strings, size_t nstrings)
{
for (size_t i = 1; i < nstrings; i++)
if (strcmp(strings[i - 1], strings[i]) >= 0)
return false;
return true;
} |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #C.23 | C# | public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) =>
strings.Count < 2 ? (true, true) :
(
strings.Distinct().Count() < 2,
Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0)
); |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Action.21 | Action! | DEFINE PTR="CARD"
PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len
len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN
PROC Quibble(PTR ARRAY items INT count CHAR ARRAY result)
INT i
result(0)=0
Append(result,"(")
FOR i=0 TO count-1
DO
Append(result,items(i))
IF i=count-2 THEN
Append(result," and ")
ELSEIF i<count-2 THEN
Append(result,", ")
FI
OD
Append(result,")")
RETURN
PROC Test(PTR ARRAY items BYTE count)
CHAR ARRAY result(256)
Quibble(items,count,result)
PrintE(result)
RETURN
PROC Main()
PTR ARRAY items(5)
Test(items,0)
items(0)="ABC"
Test(items,1)
items(1)="DEF"
Test(items,2)
items(2)="G"
Test(items,3)
items(3)="H"
Test(items,4)
RETURN |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Ada | Ada | with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line;
procedure Comma_Quibble is
begin
case Argument_Count is
when 0 => Ada.Text_IO.Put_Line("{}");
when 1 => Ada.Text_IO.Put_Line("{" & Argument(1) & "}");
when others =>
Ada.Text_IO.Put("{");
for I in 1 .. Argument_Count-2 loop
Ada.Text_IO.Put(Argument(I) & ", ");
end loop;
Ada.Text_IO.Put(Argument(Argument_Count-1) & " and " &
Argument(Argument_Count) & "}");
end case;
end Comma_Quibble; |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S
{\displaystyle S}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:
Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,
S
{\displaystyle S}
is
{
i
c
e
d
,
j
a
m
,
p
l
a
i
n
}
{\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}
,
|
S
|
=
3
{\displaystyle |S|=3}
, and
k
=
2
{\displaystyle k=2}
.)
A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.
Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.
Also note that doughnut can also be spelled donut.
Task
Write a function/program/routine/.. to generate all the combinations with repetitions of
n
{\displaystyle n}
types of things taken
k
{\displaystyle k}
at a time and use it to show an answer to the doughnut example above.
For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.
References
k-combination with repetitions
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Ada | Ada | with Ada.Text_IO;
procedure Combinations is
generic
type Set is (<>);
function Combinations
(Count : Positive;
Output : Boolean := False)
return Natural;
function Combinations
(Count : Positive;
Output : Boolean := False)
return Natural
is
package Set_IO is new Ada.Text_IO.Enumeration_IO (Set);
type Set_Array is array (Positive range <>) of Set;
Empty_Array : Set_Array (1 .. 0);
function Recurse_Combinations
(Number : Positive;
First : Set;
Prefix : Set_Array)
return Natural
is
Combination_Count : Natural := 0;
begin
for Next in First .. Set'Last loop
if Number = 1 then
Combination_Count := Combination_Count + 1;
if Output then
for Element in Prefix'Range loop
Set_IO.Put (Prefix (Element));
Ada.Text_IO.Put ('+');
end loop;
Set_IO.Put (Next);
Ada.Text_IO.New_Line;
end if;
else
Combination_Count := Combination_Count +
Recurse_Combinations
(Number - 1,
Next,
Prefix & (1 => Next));
end if;
end loop;
return Combination_Count;
end Recurse_Combinations;
begin
return Recurse_Combinations (Count, Set'First, Empty_Array);
end Combinations;
type Donuts is (Iced, Jam, Plain);
function Donut_Combinations is new Combinations (Donuts);
subtype Ten is Positive range 1 .. 10;
function Ten_Combinations is new Combinations (Ten);
Donut_Count : constant Natural :=
Donut_Combinations (Count => 2, Output => True);
Ten_Count : constant Natural := Ten_Combinations (Count => 3);
begin
Ada.Text_IO.Put_Line ("Total Donuts:" & Natural'Image (Donut_Count));
Ada.Text_IO.Put_Line ("Total Tens:" & Natural'Image (Ten_Count));
end Combinations; |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Bracmat | Bracmat | ( ( C
= n k coef
. !arg:(?n,?k)
& (!n+-1*!k:<!k:?k|)
& 1:?coef
& whl
' ( !k:>0
& !coef*!n*!k^-1:?coef
& !k+-1:?k
& !n+-1:?n
)
& !coef
)
& ( P
= n k result
. !arg:(?n,?k)
& !n+-1*!k:?k
& 1:?result
& whl
' ( !n:>!k
& !n*!result:?result
& !n+-1:?n
)
& !result
)
& 0:?i
& whl
' ( 1+!i:~>12:?i
& div$(!i.3):?k
& out$(!i P !k "=" P$(!i,!k))
)
& 0:?i
& whl
' ( 10+!i:~>60:?i
& div$(!i.3):?k
& out$(!i C !k "=" C$(!i,!k))
)
& ( displayBig
=
. @(!arg:?show [50 ? [?length)
& !show "... (" !length+-50 " more digits)"
| !arg
)
& 5 50 500 1000 5000 15000:?is
& whl
' ( !is:%?i ?is
& div$(!i.3):?k
& out$(str$(!i " P " !k " = " displayBig$(P$(!i,!k))))
)
& 0:?i
& whl
' ( 100+!i:~>1000:?i
& div$(!i.3):?k
& out$(str$(!i " C " !k " = " displayBig$(C$(!i,!k))))
)
); |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #C | C | #include <gmp.h>
void perm(mpz_t out, int n, int k)
{
mpz_set_ui(out, 1);
k = n - k;
while (n > k) mpz_mul_ui(out, out, n--);
}
void comb(mpz_t out, int n, int k)
{
perm(out, n, k);
while (k) mpz_divexact_ui(out, out, k--);
}
int main(void)
{
mpz_t x;
mpz_init(x);
perm(x, 1000, 969);
gmp_printf("P(1000,969) = %Zd\n", x);
comb(x, 1000, 969);
gmp_printf("C(1000,969) = %Zd\n", x);
return 0;
} |
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer).
Task[edit]
Create a lexical analyzer for the simple programming language specified below. The
program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a lexer module/library/class, it would be great
if two versions of the solution are provided: One without the lexer module, and one with.
Input Specification
The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens:
Operators
Name
Common name
Character sequence
Op_multiply
multiply
*
Op_divide
divide
/
Op_mod
mod
%
Op_add
plus
+
Op_subtract
minus
-
Op_negate
unary minus
-
Op_less
less than
<
Op_lessequal
less than or equal
<=
Op_greater
greater than
>
Op_greaterequal
greater than or equal
>=
Op_equal
equal
==
Op_notequal
not equal
!=
Op_not
unary not
!
Op_assign
assignment
=
Op_and
logical and
&&
Op_or
logical or
¦¦
The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.
Symbols
Name
Common name
Character
LeftParen
left parenthesis
(
RightParen
right parenthesis
)
LeftBrace
left brace
{
RightBrace
right brace
}
Semicolon
semi-colon
;
Comma
comma
,
Keywords
Name
Character sequence
Keyword_if
if
Keyword_else
else
Keyword_while
while
Keyword_print
print
Keyword_putc
putc
Identifiers and literals
These differ from the the previous tokens, in that each occurrence of them has a value associated with it.
Name
Common name
Format description
Format regex
Value
Identifier
identifier
one or more letter/number/underscore characters, but not starting with a number
[_a-zA-Z][_a-zA-Z0-9]*
as is
Integer
integer literal
one or more digits
[0-9]+
as is, interpreted as a number
Integer
char literal
exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes
'([^'\n]|\\n|\\\\)'
the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n'
String
string literal
zero or more characters (anything except newline or double quote), enclosed by double quotes
"[^"\n]*"
the characters without the double quotes and with escape sequences converted
For char and string literals, the \n escape sequence is supported to represent a new-line character.
For char and string literals, to represent a backslash, use \\.
No other special sequences are supported. This means that:
Char literals cannot represent a single quote character (value 39).
String literals cannot represent strings containing double quote characters.
Zero-width tokens
Name
Location
End_of_input
when the end of the input stream is reached
White space
Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.
"Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =).
Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge.
This means: keywords, identifiers, and integer literals.
e.g. ifprint is recognized as an identifier, instead of the keywords if and print.
e.g. 42fred is invalid, and neither recognized as a number nor an identifier.
Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value).
e.g. & & is invalid, and not interpreted as the && operator.
For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:
if ( p /* meaning n is prime */ ) {
print ( n , " " ) ;
count = count + 1 ; /* number of primes found so far */
}
if(p){print(n," ");count=count+1;}
Complete list of token names
End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract
Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal
Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if
Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen
LeftBrace RightBrace Semicolon Comma Identifier Integer
String
Output Format
The program output should be a sequence of lines, each consisting of the following whitespace-separated fields:
the line number where the token starts
the column number where the token starts
the token name
the token value (only for Identifier, Integer, and String tokens)
the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.
This task is intended to be used as part of a pipeline, with the other compiler tasks - for example:
lex < hello.t | parse | gen | vm
Or possibly:
lex hello.t lex.out
parse lex.out parse.out
gen parse.out gen.out
vm gen.out
This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.
Diagnostics
The following error conditions should be caught:
Error
Example
Empty character constant
''
Unknown escape sequence.
\r
Multi-character constant.
'xx'
End-of-file in comment. Closing comment characters not found.
End-of-file while scanning string literal. Closing string character not found.
End-of-line while scanning string literal. Closing string character not found before end-of-line.
Unrecognized character.
|
Invalid number. Starts like a number, but ends in non-numeric characters.
123abc
Test Cases
Input
Output
Test Case 1:
/*
Hello world
*/
print("Hello, World!\n");
4 1 Keyword_print
4 6 LeftParen
4 7 String "Hello, World!\n"
4 24 RightParen
4 25 Semicolon
5 1 End_of_input
Test Case 2:
/*
Show Ident and Integers
*/
phoenix_number = 142857;
print(phoenix_number, "\n");
4 1 Identifier phoenix_number
4 16 Op_assign
4 18 Integer 142857
4 24 Semicolon
5 1 Keyword_print
5 6 LeftParen
5 7 Identifier phoenix_number
5 21 Comma
5 23 String "\n"
5 27 RightParen
5 28 Semicolon
6 1 End_of_input
Test Case 3:
/*
All lexical tokens - not syntactically correct, but that will
have to wait until syntax analysis
*/
/* Print */ print /* Sub */ -
/* Putc */ putc /* Lss */ <
/* If */ if /* Gtr */ >
/* Else */ else /* Leq */ <=
/* While */ while /* Geq */ >=
/* Lbrace */ { /* Eq */ ==
/* Rbrace */ } /* Neq */ !=
/* Lparen */ ( /* And */ &&
/* Rparen */ ) /* Or */ ||
/* Uminus */ - /* Semi */ ;
/* Not */ ! /* Comma */ ,
/* Mul */ * /* Assign */ =
/* Div */ / /* Integer */ 42
/* Mod */ % /* String */ "String literal"
/* Add */ + /* Ident */ variable_name
/* character literal */ '\n'
/* character literal */ '\\'
/* character literal */ ' '
5 16 Keyword_print
5 40 Op_subtract
6 16 Keyword_putc
6 40 Op_less
7 16 Keyword_if
7 40 Op_greater
8 16 Keyword_else
8 40 Op_lessequal
9 16 Keyword_while
9 40 Op_greaterequal
10 16 LeftBrace
10 40 Op_equal
11 16 RightBrace
11 40 Op_notequal
12 16 LeftParen
12 40 Op_and
13 16 RightParen
13 40 Op_or
14 16 Op_subtract
14 40 Semicolon
15 16 Op_not
15 40 Comma
16 16 Op_multiply
16 40 Op_assign
17 16 Op_divide
17 40 Integer 42
18 16 Op_mod
18 40 String "String literal"
19 16 Op_add
19 40 Identifier variable_name
20 26 Integer 10
21 26 Integer 92
22 26 Integer 32
23 1 End_of_input
Test Case 4:
/*** test printing, embedded \n and comments with lots of '*' ***/
print(42);
print("\nHello World\nGood Bye\nok\n");
print("Print a slash n - \\n.\n");
2 1 Keyword_print
2 6 LeftParen
2 7 Integer 42
2 9 RightParen
2 10 Semicolon
3 1 Keyword_print
3 6 LeftParen
3 7 String "\nHello World\nGood Bye\nok\n"
3 38 RightParen
3 39 Semicolon
4 1 Keyword_print
4 6 LeftParen
4 7 String "Print a slash n - \\n.\n"
4 33 RightParen
4 34 Semicolon
5 1 End_of_input
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #AWK | AWK |
BEGIN {
all_syms["tk_EOI" ] = "End_of_input"
all_syms["tk_Mul" ] = "Op_multiply"
all_syms["tk_Div" ] = "Op_divide"
all_syms["tk_Mod" ] = "Op_mod"
all_syms["tk_Add" ] = "Op_add"
all_syms["tk_Sub" ] = "Op_subtract"
all_syms["tk_Negate" ] = "Op_negate"
all_syms["tk_Not" ] = "Op_not"
all_syms["tk_Lss" ] = "Op_less"
all_syms["tk_Leq" ] = "Op_lessequal"
all_syms["tk_Gtr" ] = "Op_greater"
all_syms["tk_Geq" ] = "Op_greaterequal"
all_syms["tk_Eq" ] = "Op_equal"
all_syms["tk_Neq" ] = "Op_notequal"
all_syms["tk_Assign" ] = "Op_assign"
all_syms["tk_And" ] = "Op_and"
all_syms["tk_Or" ] = "Op_or"
all_syms["tk_If" ] = "Keyword_if"
all_syms["tk_Else" ] = "Keyword_else"
all_syms["tk_While" ] = "Keyword_while"
all_syms["tk_Print" ] = "Keyword_print"
all_syms["tk_Putc" ] = "Keyword_putc"
all_syms["tk_Lparen" ] = "LeftParen"
all_syms["tk_Rparen" ] = "RightParen"
all_syms["tk_Lbrace" ] = "LeftBrace"
all_syms["tk_Rbrace" ] = "RightBrace"
all_syms["tk_Semi" ] = "Semicolon"
all_syms["tk_Comma" ] = "Comma"
all_syms["tk_Ident" ] = "Identifier"
all_syms["tk_Integer"] = "Integer"
all_syms["tk_String" ] = "String"
## single character only symbols
symbols["{" ] = "tk_Lbrace"
symbols["}" ] = "tk_Rbrace"
symbols["(" ] = "tk_Lparen"
symbols[")" ] = "tk_Rparen"
symbols["+" ] = "tk_Add"
symbols["-" ] = "tk_Sub"
symbols["*" ] = "tk_Mul"
symbols["%" ] = "tk_Mod"
symbols[";" ] = "tk_Semi"
symbols["," ] = "tk_Comma"
key_words["if" ] = "tk_If"
key_words["else" ] = "tk_Else"
key_words["print"] = "tk_Print"
key_words["putc" ] = "tk_Putc"
key_words["while"] = "tk_While"
# Set up an array that emulates the ord() function.
for(n=0;n<256;n++)
ord[sprintf("%c",n)]=n
input_file = "-"
if (ARGC > 1)
input_file = ARGV[1]
RS=FS="" # read complete file into one line $0
getline < input_file
the_ch = " " # dummy first char - but it must be a space
the_col = 0 # always points to the current character
the_line = 1
for (the_nf=1; ; ) {
split(gettok(), t, SUBSEP)
printf("%5s %5s %-14s", t[2], t[3], all_syms[t[1]])
if (t[1] == "tk_Integer") printf(" %5s\n", t[4])
else if (t[1] == "tk_Ident" ) printf(" %s\n", t[4])
else if (t[1] == "tk_String" ) printf(" \"%s\"\n", t[4])
else print("")
if (t[1] == "tk_EOI")
break
}
}
#*** show error and exit
function error(line, col, msg) {
print(line, col, msg)
exit(1)
}
# get the next character from the input
function next_ch() {
the_ch = $the_nf
the_nf ++
the_col ++
if (the_ch == "\n") {
the_line ++
the_col = 0
}
return the_ch
}
#*** 'x' - character constants
function char_lit(err_line, err_col) {
n = ord[next_ch()] # skip opening quote
if (the_ch == "'") {
error(err_line, err_col, "empty character constant")
} else if (the_ch == "\\") {
next_ch()
if (the_ch == "n")
n = 10
else if (the_ch == "\\")
n = ord["\\"]
else
error(err_line, err_col, "unknown escape sequence " the_ch)
}
if (next_ch() != "'")
error(err_line, err_col, "multi-character constant")
next_ch()
return "tk_Integer" SUBSEP err_line SUBSEP err_col SUBSEP n
}
#*** process divide or comments
function div_or_cmt(err_line, err_col) {
if (next_ch() != "*")
return "tk_Div" SUBSEP err_line SUBSEP err_col
# comment found
next_ch()
while (1) {
if (the_ch == "*") {
if (next_ch() == "/") {
next_ch()
return gettok()
} else if (the_ch == "") {
error(err_line, err_col, "EOF in comment")
}
} else {
next_ch()
}
}
}
#*** "string"
function string_lit(start, err_line, err_col) {
text = ""
while (next_ch() != start) {
if (the_ch == "")
error(err_line, err_col, "EOF while scanning string literal")
if (the_ch == "\n")
error(err_line, err_col, "EOL while scanning string literal")
text = text the_ch
}
next_ch()
return "tk_String" SUBSEP err_line SUBSEP err_col SUBSEP text
}
#*** handle identifiers and integers
function ident_or_int(err_line, err_col) {
is_number = 1
text = ""
while ((the_ch ~ /^[0-9a-zA-Z]+$/) || (the_ch == "_")) {
text = text the_ch
if (! (the_ch ~ /^[0-9]+$/))
is_number = 0
next_ch()
}
if (text == "")
error(err_line, err_col, "ident_or_int: unrecognized character: " the_ch)
if (text ~ /^[0-9]/) {
if (! is_number)
error(err_line, err_col, "invalid number: " text)
n = text + 0
return "tk_Integer" SUBSEP err_line SUBSEP err_col SUBSEP n
}
if (text in key_words)
return key_words[text] SUBSEP err_line SUBSEP err_col
return "tk_Ident" SUBSEP err_line SUBSEP err_col SUBSEP text
}
#*** look ahead for '>=', etc.
function follow(expect, ifyes, ifno, err_line, err_col) {
if (next_ch() == expect) {
next_ch()
return ifyes SUBSEP err_line SUBSEP err_col
}
if (ifno == tk_EOI)
error(err_line, err_col, "follow: unrecognized character: " the_ch)
return ifno SUBSEP err_line SUBSEP err_col
}
#*** return the next token type
function gettok() {
while (the_ch == " " || the_ch == "\n" || the_ch == "\r")
next_ch()
err_line = the_line
err_col = the_col
if (the_ch == "" ) return "tk_EOI" SUBSEP err_line SUBSEP err_col
else if (the_ch == "/") return div_or_cmt(err_line, err_col)
else if (the_ch == "'") return char_lit(err_line, err_col)
else if (the_ch == "<") return follow("=", "tk_Leq", "tk_Lss", err_line, err_col)
else if (the_ch == ">") return follow("=", "tk_Geq", "tk_Gtr", err_line, err_col)
else if (the_ch == "=") return follow("=", "tk_Eq", "tk_Assign", err_line, err_col)
else if (the_ch == "!") return follow("=", "tk_Neq", "tk_Not", err_line, err_col)
else if (the_ch == "&") return follow("&", "tk_And", "tk_EOI", err_line, err_col)
else if (the_ch == "|") return follow("|", "tk_Or", "tk_EOI", err_line, err_col)
else if (the_ch =="\"") return string_lit(the_ch, err_line, err_col)
else if (the_ch in symbols) {
sym = symbols[the_ch]
next_ch()
return sym SUBSEP err_line SUBSEP err_col
} else {
return ident_or_int(err_line, err_col)
}
}
|
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Arturo | Arturo | loop arg 'a [
print a
] |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #AutoHotkey | AutoHotkey | Loop %0% ; number of parameters
params .= %A_Index% . A_Space
If params !=
MsgBox, %0% parameters were passed:`n`n %params%
Else
Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\"" |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #ActionScript | ActionScript | -- All Ada comments begin with "--" and extend to the end of the line |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Ada | Ada | -- All Ada comments begin with "--" and extend to the end of the line |
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Input format:
Given the following program:
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
The output from the Code generator is a virtual assembly code program:
Output from gen, input to VM
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
The first line of the input specifies the datasize required and the number of constant
strings, in the order that they are reference via the code.
The data can be stored in a separate array, or the data can be stored at the beginning of
the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if
referenced at address 2.
If there are one or more constant strings, they come next. The code refers to these
strings by their index. The index starts at 0. So if there are 3 strings, and the code
wants to reference the 3rd string, 2 will be used.
Next comes the actual virtual assembly code. The first number is the code address of that
instruction. After that is the instruction mnemonic, followed by optional operands,
depending on the instruction.
Registers:
sp:
the stack pointer - points to the next top of stack. The stack is a 32-bit integer
array.
pc:
the program counter - points to the current instruction to be performed. The code is an
array of bytes.
Data:
data
string pool
Instructions:
Each instruction is one byte. The following instructions also have a 32-bit integer
operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
Print the word at stack top as a character.
prtc
Print the word at stack top as an integer.
prti
Stack top points to an index into the string pool. Print that entry.
prts
Unconditional stop.
halt
A simple example virtual machine
def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
AST Interpreter task
| #M2000_Interpreter | M2000 Interpreter |
Module Virtual_Machine_Interpreter (a$){
\\ function to extract string, replacing escape codes.
Function GetString$(a$) {
s=instr(a$, chr$(34))
m=rinstr(a$,chr$(34))-s
if m>1 then
\\ process escape codes
=format$(mid$(a$, s+1, m-1))
else
=""
end if
}
\\ module to print a string to console using codes, 13, 10, 9
Module printsrv (a$) {
for i=1 to len(a$)
select case chrcode(Mid$(a$,i,1))
case 13
cursor 0
case 10
cursor 0 : Print
case 9
cursor ((pos+tab) div tab)*tab
else case
{
m=pos :if pos>=width then Print : m=pos
Print Mid$(a$,i,1);
if m<=width then cursor m+1
}
end select
next i
}
const nl$=chr$(13)+chr$(10)
\\ we can set starting value to any number n where 0<=n<=232
enum op { halt_=232, add_, sub_, mul_, div_, mod_, not_, neg_, and_, or_, lt_,
gt_, le_, ge_, ne_, eq_, prts_, prti_, prtc_, store_, fetch_, push_,
jmp_, jz_
}
Rem : Form 120, 60 ' change console width X height to run Ascii Mandlebrot examlpe
Report "Virtual Assembly Code:"+{
}+a$
Print "Prepare Byte Code"
\\ get datasize
a$=rightpart$(a$, "Datasize:")
m=0
data_size=val(a$, "int", m)
a$=mid$(a$, m)
\\ make stack
if data_size>0 then Buffer Clear stack_ as long*data_size
\\ dim or redim buffer append 1000 long as is.
Buffer stack_ as long*(1000+data_size)
\\ get strings
a$=rightpart$(a$, "Strings:")
m=0
strings=val(a$, "int", m)
a$=rightpart$(a$, nl$)
if strings>0 then
Dim strings$(strings)
for i=0 to strings-1
strings$(i)=GetString$(leftpart$(a$, nl$))
a$=rightpart$(a$, nl$)
Next i
End if
buffer clear code_ as byte*1000
do
m=0
offset=val(a$,"int", m)
if m<0 then exit
a$=mid$(a$,m)
line$=trim$(leftpart$(a$,nl$))
if line$="" then line$=trim$(a$) else a$=trim$(rightpart$(a$, nl$))
op$=if$(instr(line$," ")>0->leftpart$(line$," "), line$)
if not valid(eval(op$+"_")) then exit
opc=eval(op$+"_")
Return code_, offset:=opc
if opc>=store_ then
line$=rightpart$(line$," ")
select case opc
case store_, fetch_
Return code_, offset+1:=val(rightpart$(leftpart$(line$,"]"),"[")) as long : offset+=4
case push_
Return code_, offset+1:=uint(val(line$)) as long : offset+=4
case jz_, jmp_
Return code_, offset+1:=val(rightpart$(line$,")")) as long : offset+=4
end select
end if
Always
Print "Press any key" : Push key$ : Drop
\\ Prepare VM
let pc=0, sp=len(stack_) div 4
do {
func=eval(code_, pc)
pc++
select case func
case halt_
exit
case push_
sp--:return stack_, sp:=eval(code_, pc as long):pc+=4
case jz_
sp++: if eval(stack_, sp-1)=0 then pc=eval(code_, pc as long) else pc+=4
case jmp_
pc=eval(code_, pc as long)
case fetch_
sp--:Return stack_, sp:=eval(stack_, eval(code_, pc as long)):pc+=4
case store_
Return stack_, eval(code_, pc as long):=eval(stack_, sp):sp++:pc+=4
case add_
Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))+sint(eval(stack_, sp))):sp++
case sub_
Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))-sint(eval(stack_, sp))):sp++
case mul_
Return stack_, sp+1:=uint(sint(eval(stack_, sp+1))*sint(eval(stack_, sp))):sp++
case div_
Return stack_, sp+1:=uint(sint(eval(stack_, sp+1)) div sint(eval(stack_, sp))):sp++
case mod_
Return stack_, sp+1:=uint(sint(eval(stack_, sp+1)) mod sint(eval(stack_, sp))) :sp++
case not_
Return stack_, sp:=if(eval(stack_, sp)=0->uint(-1),0)
case neg_ \\ we can use neg(sint(value))+1 or uint(-sint(value))
Return stack_, sp:=uint(-sint(eval(stack_, sp)))
case and_
Return stack_, sp+1:=binary.and(eval(stack_, sp+1),eval(stack_, sp)):sp++
case or_
Return stack_, sp+1:=binary.or(eval(stack_, sp+1),eval(stack_, sp)):sp++
case lt_
Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<sint(eval(stack_, sp))->-1, 0)):sp++
case gt_
Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>sint(eval(stack_, sp))->-1, 0)):sp++
case le_
Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))<=sint(eval(stack_, sp))->-1, 0)):sp++
case ge_
Return stack_, sp+1:=uint(if(sint(eval(stack_, sp+1))>=sint(eval(stack_, sp))->-1, 0)):sp++
case ne_
Return stack_, sp+1:=uint(if(eval(stack_, sp+1)<>eval(stack_, sp)->-1, 0)):sp++
case eq_
Return stack_, sp+1:=uint(if(eval(stack_, sp+1)=eval(stack_, sp)->-1, 0)):sp++
case prts_
printsrv strings$(eval(stack_,sp)):sp++
case prti_
printsrv str$(sint(eval(stack_,sp)),0):sp++
case prtc_
printsrv chrcode$(eval(stack_,sp)):sp++
else case
Error "Unkown op "+str$(func)
end select
} always
Print "done"
}
Virtual_Machine_Interpreter {
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
}
|
http://rosettacode.org/wiki/Compiler/code_generator | Compiler/code generator | A code generator translates the output of the syntax analyzer and/or semantic analyzer
into lower level code, either assembly, object, or virtual.
Task[edit]
Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the
Virtual machine interpreter. The output is in text format, and represents virtual assembly code.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
while.ast can be input into the code generator.
The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code.
Run as: lex < while.t | parse | gen
Input to lex
Output from lex, input to parse
Output from parse
Output from gen, input to VM
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
Input format
As shown in the table, above, the output from the syntax analyzer is a flattened AST.
In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes.
Loading this data into an internal parse tree should be as simple as:
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";"
return None
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Output format - refer to the table above
The first line is the header: Size of data, and number of constant strings.
size of data is the number of 32-bit unique variables used. In this example, one variable, count
number of constant strings is just that - how many there are
After that, the constant strings
Finally, the assembly code
Registers
sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array.
pc: the program counter - points to the current instruction to be performed. The code is an array of bytes.
Data
32-bit integers and strings
Instructions
Each instruction is one byte. The following instructions also have a 32-bit integer operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
prtc
Print the word at stack top as a character.
prti
Print the word at stack top as an integer.
prts
Stack top points to an index into the string pool. Print that entry.
halt
Unconditional stop.
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Virtual Machine Interpreter task
AST Interpreter task
| #Java | Java | package codegenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class CodeGenerator {
final static int WORDSIZE = 4;
static byte[] code = {};
static Map<String, NodeType> str_to_nodes = new HashMap<>();
static List<String> string_pool = new ArrayList<>();
static List<String> variables = new ArrayList<>();
static int string_count = 0;
static int var_count = 0;
static Scanner s;
static NodeType[] unary_ops = {
NodeType.nd_Negate, NodeType.nd_Not
};
static NodeType[] operators = {
NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,
NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,
NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or
};
static enum Mnemonic {
NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,
JMP, JZ, PRTC, PRTS, PRTI, HALT
}
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE),
nd_If("If", Mnemonic.NONE),
nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE),
nd_Assign("Assign", Mnemonic.NONE),
nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD),
nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE),
nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ),
nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR);
private final String name;
private final Mnemonic m;
NodeType(String name, Mnemonic m) {
this.name = name;
this.m = m;
}
Mnemonic getMnemonic() { return this.m; }
@Override
public String toString() { return this.name; }
}
static void appendToCode(int b) {
code = Arrays.copyOf(code, code.length + 1);
code[code.length - 1] = (byte) b;
}
static void emit_byte(Mnemonic m) {
appendToCode(m.ordinal());
}
static void emit_word(int n) {
appendToCode(n >> 24);
appendToCode(n >> 16);
appendToCode(n >> 8);
appendToCode(n);
}
static void emit_word_at(int pos, int n) {
code[pos] = (byte) (n >> 24);
code[pos + 1] = (byte) (n >> 16);
code[pos + 2] = (byte) (n >> 8);
code[pos + 3] = (byte) n;
}
static int get_word(int pos) {
int result;
result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ;
return result;
}
static int fetch_var_offset(String name) {
int n;
n = variables.indexOf(name);
if (n == -1) {
variables.add(name);
n = var_count++;
}
return n;
}
static int fetch_string_offset(String str) {
int n;
n = string_pool.indexOf(str);
if (n == -1) {
string_pool.add(str);
n = string_count++;
}
return n;
}
static int hole() {
int t = code.length;
emit_word(0);
return t;
}
static boolean arrayContains(NodeType[] a, NodeType n) {
boolean result = false;
for (NodeType test: a) {
if (test.equals(n)) {
result = true;
break;
}
}
return result;
}
static void code_gen(Node x) throws Exception {
int n, p1, p2;
if (x == null) return;
switch (x.nt) {
case nd_None: return;
case nd_Ident:
emit_byte(Mnemonic.FETCH);
n = fetch_var_offset(x.value);
emit_word(n);
break;
case nd_Integer:
emit_byte(Mnemonic.PUSH);
emit_word(Integer.parseInt(x.value));
break;
case nd_String:
emit_byte(Mnemonic.PUSH);
n = fetch_string_offset(x.value);
emit_word(n);
break;
case nd_Assign:
n = fetch_var_offset(x.left.value);
code_gen(x.right);
emit_byte(Mnemonic.STORE);
emit_word(n);
break;
case nd_If:
p2 = 0; // to avoid NetBeans complaining about 'not initialized'
code_gen(x.left);
emit_byte(Mnemonic.JZ);
p1 = hole();
code_gen(x.right.left);
if (x.right.right != null) {
emit_byte(Mnemonic.JMP);
p2 = hole();
}
emit_word_at(p1, code.length - p1);
if (x.right.right != null) {
code_gen(x.right.right);
emit_word_at(p2, code.length - p2);
}
break;
case nd_While:
p1 = code.length;
code_gen(x.left);
emit_byte(Mnemonic.JZ);
p2 = hole();
code_gen(x.right);
emit_byte(Mnemonic.JMP);
emit_word(p1 - code.length);
emit_word_at(p2, code.length - p2);
break;
case nd_Sequence:
code_gen(x.left);
code_gen(x.right);
break;
case nd_Prtc:
code_gen(x.left);
emit_byte(Mnemonic.PRTC);
break;
case nd_Prti:
code_gen(x.left);
emit_byte(Mnemonic.PRTI);
break;
case nd_Prts:
code_gen(x.left);
emit_byte(Mnemonic.PRTS);
break;
default:
if (arrayContains(operators, x.nt)) {
code_gen(x.left);
code_gen(x.right);
emit_byte(x.nt.getMnemonic());
} else if (arrayContains(unary_ops, x.nt)) {
code_gen(x.left);
emit_byte(x.nt.getMnemonic());
} else {
throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator.");
}
}
}
static void list_code() throws Exception {
int pc = 0, x;
Mnemonic op;
System.out.println("Datasize: " + var_count + " Strings: " + string_count);
for (String s: string_pool) {
System.out.println(s);
}
while (pc < code.length) {
System.out.printf("%4d ", pc);
op = Mnemonic.values()[code[pc++]];
switch (op) {
case FETCH:
x = get_word(pc);
System.out.printf("fetch [%d]", x);
pc += WORDSIZE;
break;
case STORE:
x = get_word(pc);
System.out.printf("store [%d]", x);
pc += WORDSIZE;
break;
case PUSH:
x = get_word(pc);
System.out.printf("push %d", x);
pc += WORDSIZE;
break;
case ADD: case SUB: case MUL: case DIV: case MOD:
case LT: case GT: case LE: case GE: case EQ: case NE:
case AND: case OR: case NEG: case NOT:
case PRTC: case PRTI: case PRTS: case HALT:
System.out.print(op.toString().toLowerCase());
break;
case JMP:
x = get_word(pc);
System.out.printf("jmp (%d) %d", x, pc + x);
pc += WORDSIZE;
break;
case JZ:
x = get_word(pc);
System.out.printf("jz (%d) %d", x, pc + x);
pc += WORDSIZE;
break;
default:
throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1));
}
System.out.println();
}
}
static Node load_ast() throws Exception {
String command, value;
String line;
Node left, right;
while (s.hasNext()) {
line = s.nextLine();
value = null;
if (line.length() > 16) {
command = line.substring(0, 15).trim();
value = line.substring(15).trim();
} else {
command = line.trim();
}
if (command.equals(";")) {
return null;
}
if (!str_to_nodes.containsKey(command)) {
throw new Exception("Command not found: '" + command + "'");
}
if (value != null) {
return Node.make_leaf(str_to_nodes.get(command), value);
}
left = load_ast(); right = load_ast();
return Node.make_node(str_to_nodes.get(command), left, right);
}
return null; // for the compiler, not needed
}
public static void main(String[] args) {
Node n;
str_to_nodes.put(";", NodeType.nd_None);
str_to_nodes.put("Sequence", NodeType.nd_Sequence);
str_to_nodes.put("Identifier", NodeType.nd_Ident);
str_to_nodes.put("String", NodeType.nd_String);
str_to_nodes.put("Integer", NodeType.nd_Integer);
str_to_nodes.put("If", NodeType.nd_If);
str_to_nodes.put("While", NodeType.nd_While);
str_to_nodes.put("Prtc", NodeType.nd_Prtc);
str_to_nodes.put("Prts", NodeType.nd_Prts);
str_to_nodes.put("Prti", NodeType.nd_Prti);
str_to_nodes.put("Assign", NodeType.nd_Assign);
str_to_nodes.put("Negate", NodeType.nd_Negate);
str_to_nodes.put("Not", NodeType.nd_Not);
str_to_nodes.put("Multiply", NodeType.nd_Mul);
str_to_nodes.put("Divide", NodeType.nd_Div);
str_to_nodes.put("Mod", NodeType.nd_Mod);
str_to_nodes.put("Add", NodeType.nd_Add);
str_to_nodes.put("Subtract", NodeType.nd_Sub);
str_to_nodes.put("Less", NodeType.nd_Lss);
str_to_nodes.put("LessEqual", NodeType.nd_Leq);
str_to_nodes.put("Greater", NodeType.nd_Gtr);
str_to_nodes.put("GreaterEqual", NodeType.nd_Geq);
str_to_nodes.put("Equal", NodeType.nd_Eql);
str_to_nodes.put("NotEqual", NodeType.nd_Neq);
str_to_nodes.put("And", NodeType.nd_And);
str_to_nodes.put("Or", NodeType.nd_Or);
if (args.length > 0) {
try {
s = new Scanner(new File(args[0]));
n = load_ast();
code_gen(n);
emit_byte(Mnemonic.HALT);
list_code();
} catch (Exception e) {
System.out.println("Ex: "+e);//.getMessage());
}
}
}
}
|
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[BubbleSort,ShellSort]
BubbleSort[in_List]:=Module[{x=in,l=Length[in],swapped},swapped=True;
While[swapped,swapped=False;
Do[If[x[[i]]>x[[i+1]],x[[{i,i+1}]]//=Reverse;
swapped=True;],{i,l-1}];];
x]
ShellSort[lst_]:=Module[{list=lst,incr,temp,i,j},incr=Round[Length[list]/2];
While[incr>0,For[i=incr+1,i<=Length[list],i++,temp=list[[i]];j=i;
While[(j>=(incr+1))&&(list[[j-incr]]>temp),list[[j]]=list[[j-incr]];j=j-incr;];
list[[j]]=temp;];
If[incr==2,incr=1,incr=Round[incr/2.2]]];list
]
times=Table[
arr=ConstantArray[1,n];
t1={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
arr=Sort[RandomInteger[{10^6},n]];
t2={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
arr=RandomInteger[{10^6},n];
t3={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
{t1,t2,t3}
,
{n,2^Range[13]}
];
ListLogLogPlot[Transpose@times[[All,1]],PlotLegends->{"Bubble","Shell"},PlotLabel->"Ones"]
ListLogLogPlot[Transpose@times[[All,2]],PlotLegends->{"Bubble","Shell"},PlotLabel->"Ascending integers"]
ListLogLogPlot[Transpose@times[[All,3]],PlotLegends->{"Bubble","Shell"},PlotLabel->"Shuffled"] |
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #Nim | Nim | import algorithm
import random
import sequtils
import times
####################################################################################################
# Data.
proc oneSeq(n: int): seq[int] = repeat(1, n)
#---------------------------------------------------------------------------------------------------
proc shuffledSeq(n: int): seq[int] =
result.setLen(n)
for item in result.mitems: item = rand(1..(10 * n))
#---------------------------------------------------------------------------------------------------
proc ascendingSeq(n: int): seq[int] = sorted(shuffledSeq(n))
####################################################################################################
# Algorithms.
func bubbleSort(a: var openArray[int]) {.locks: "unknown".} =
var n = a.len
while true:
var n2 = 0
for i in 1..<n:
if a[i - 1] > a[i]:
swap a[i], a[i - 1]
n2 = i
n = n2
if n == 0: break
#---------------------------------------------------------------------------------------------------
func insertionSort(a: var openArray[int]) {.locks: "unknown".} =
for index in 1..a.high:
let value = a[index]
var subIndex = index - 1
while subIndex >= 0 and a[subIndex] > value:
a[subIndex + 1] = a[subIndex]
dec subIndex
a[subIndex + 1] = value
#---------------------------------------------------------------------------------------------------
func quickSort(a: var openArray[int]) {.locks: "unknown".} =
func sorter(a: var openArray[int]; first, last: int) =
if last - first < 1: return
let pivot = a[first + (last - first) div 2]
var left = first
var right = last
while left <= right:
while a[left] < pivot: inc left
while a[right] > pivot: dec right
if left <= right:
swap a[left], a[right]
inc left
dec right
if first < right: a.sorter(first, right)
if left < last: a.sorter(left, last)
a.sorter(0, a.high)
#---------------------------------------------------------------------------------------------------
func radixSort(a: var openArray[int]) {.locks: "unknown".} =
var tmp = newSeq[int](a.len)
for shift in countdown(63, 0):
for item in tmp.mitems: item = 0
var j = 0
for i in 0..a.high:
let move = a[i] shl shift >= 0
let toBeMoved = if shift == 0: not move else: move
if toBeMoved:
tmp[j] = a[i]
inc j
else:
a[i - j] = a[i]
for i in j..tmp.high: tmp[i] = a[i - j]
for i in 0..a.high: a[i] = tmp[i]
#---------------------------------------------------------------------------------------------------
func shellSort(a: var openArray[int]) {.locks: "unknown".} =
const Gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in Gaps:
for i in gap..a.high:
let temp = a[i]
var j = i
while j >= gap and a[j - gap] > temp:
a[j] = a[j - gap]
dec j, gap
a[j] = temp
#---------------------------------------------------------------------------------------------------
func standardSort(a: var openArray[int]) =
a.sort()
####################################################################################################
# Main code.
import strformat
const
Runs = 10
Lengths = [1, 10, 100, 1_000, 10_000, 100_000]
Sorts = [bubbleSort, insertionSort, quickSort, radixSort, shellSort, standardSort]
const
SortTitles = ["Bubble", "Insert", "Quick ", "Radix ", "Shell ", "Standard"]
SeqTitles = ["All Ones", "Ascending", "Shuffled"]
var totals: array[SeqTitles.len, array[Sorts.len, array[Lengths.len, Duration]]]
randomize()
for k, n in Lengths:
let seqs = [oneSeq(n), ascendingSeq(n), shuffledSeq(n)]
for _ in 1..Runs:
for i, s in seqs:
for j, sort in Sorts:
var s = s
let t0 = getTime()
s.sort()
totals[i][j][k] += getTime() - t0
echo "All timings in microseconds\n"
stdout.write "Sequence length "
for length in Lengths:
stdout.write &"{length:6d} "
echo '\n'
for i in 0..SeqTitles.high:
echo &" {SeqTitles[i]}:"
for j in 0..Sorts.high:
stdout.write &" {SortTitles[j]:8s} "
for k in 0..Lengths.high:
let time = totals[i][j][k].inMicroseconds div Runs
stdout.write &"{time:8d} "
echo ""
echo '\n' |
http://rosettacode.org/wiki/Compiler/AST_interpreter | Compiler/AST interpreter | An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is as simple as (pseudo code)
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
The interpreter algorithm is relatively simple
interp(x)
if x == NULL return NULL
elif x.node_type == Integer return x.value converted to an integer
elif x.node_type == Ident return the current value of variable x.value
elif x.node_type == String return x.value
elif x.node_type == Assign
globals[x.left.value] = interp(x.right)
return NULL
elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)
elif x.node_type is a unary operator, return return operator interp(x.left)
elif x.node_type == If
if (interp(x.left)) then interp(x.right.left)
else interp(x.right.right)
return NULL
elif x.node_type == While
while (interp(x.left)) do interp(x.right)
return NULL
elif x.node_type == Prtc
print interp(x.left) as a character, no newline
return NULL
elif x.node_type == Prti
print interp(x.left) as an integer, no newline
return NULL
elif x.node_type == Prts
print interp(x.left) as a string, respecting newlines ("\n")
return NULL
elif x.node_type == Sequence
interp(x.left)
interp(x.right)
return NULL
else
error("unknown node type")
Notes:
Because of the simple nature of our tiny language, Semantic analysis is not needed.
Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.
This means, for instance, that 3 / 2 should result in 1.
For division when one of the operands is negative, the result should be truncated towards 0.
This means, for instance, that 3 / -2 should result in -1.
Test program
prime.t
lex <prime.t | parse | interp
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
101 is prime
Total primes found: 26
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
| #Zig | Zig |
const std = @import("std");
pub const ASTInterpreterError = error{OutOfMemory};
pub const ASTInterpreter = struct {
output: std.ArrayList(u8),
globals: std.StringHashMap(NodeValue),
const Self = @This();
pub fn init(allocator: std.mem.Allocator) Self {
return ASTInterpreter{
.output = std.ArrayList(u8).init(allocator),
.globals = std.StringHashMap(NodeValue).init(allocator),
};
}
// Returning `NodeValue` from this function looks suboptimal and this should
// probably be a separate type.
pub fn interp(self: *Self, tree: ?*Tree) ASTInterpreterError!?NodeValue {
if (tree) |t| {
switch (t.typ) {
.sequence => {
_ = try self.interp(t.left);
_ = try self.interp(t.right);
},
.assign => try self.globals.put(
t.left.?.value.?.string,
(try self.interp(t.right)).?,
),
.identifier => return self.globals.get(t.value.?.string).?,
.kw_while => {
while ((try self.interp(t.left)).?.integer != 0) {
_ = try self.interp(t.right);
}
},
.kw_if => {
const condition = (try self.interp(t.left)).?.integer;
if (condition == 1) {
_ = try self.interp(t.right.?.left);
} else {
_ = try self.interp(t.right.?.right);
}
},
.less => return NodeValue{ .integer = try self.binOp(less, t.left, t.right) },
.less_equal => return NodeValue{ .integer = try self.binOp(less_equal, t.left, t.right) },
.greater => return NodeValue{ .integer = try self.binOp(greater, t.left, t.right) },
.greater_equal => return NodeValue{ .integer = try self.binOp(greater_equal, t.left, t.right) },
.add => return NodeValue{ .integer = try self.binOp(add, t.left, t.right) },
.subtract => return NodeValue{ .integer = try self.binOp(sub, t.left, t.right) },
.multiply => return NodeValue{ .integer = try self.binOp(mul, t.left, t.right) },
.divide => return NodeValue{ .integer = try self.binOp(div, t.left, t.right) },
.mod => return NodeValue{ .integer = try self.binOp(mod, t.left, t.right) },
.equal => return NodeValue{ .integer = try self.binOp(equal, t.left, t.right) },
.not_equal => return NodeValue{ .integer = try self.binOp(not_equal, t.left, t.right) },
.bool_and => return NodeValue{ .integer = try self.binOp(@"and", t.left, t.right) },
.bool_or => return NodeValue{ .integer = try self.binOp(@"or", t.left, t.right) },
.negate => return NodeValue{ .integer = -(try self.interp(t.left)).?.integer },
.not => {
const arg = (try self.interp(t.left)).?.integer;
const result: i32 = if (arg == 0) 1 else 0;
return NodeValue{ .integer = result };
},
.prts => _ = try self.out("{s}", .{(try self.interp(t.left)).?.string}),
.prti => _ = try self.out("{d}", .{(try self.interp(t.left)).?.integer}),
.prtc => _ = try self.out("{c}", .{@intCast(u8, (try self.interp(t.left)).?.integer)}),
.string => return t.value,
.integer => return t.value,
.unknown => {
std.debug.print("\nINTERP: UNKNOWN {}\n", .{t});
std.os.exit(1);
},
}
}
return null;
}
pub fn out(self: *Self, comptime format: []const u8, args: anytype) ASTInterpreterError!void {
try self.output.writer().print(format, args);
}
fn binOp(
self: *Self,
func: fn (a: i32, b: i32) i32,
a: ?*Tree,
b: ?*Tree,
) ASTInterpreterError!i32 {
return func(
(try self.interp(a)).?.integer,
(try self.interp(b)).?.integer,
);
}
fn less(a: i32, b: i32) i32 {
return @boolToInt(a < b);
}
fn less_equal(a: i32, b: i32) i32 {
return @boolToInt(a <= b);
}
fn greater(a: i32, b: i32) i32 {
return @boolToInt(a > b);
}
fn greater_equal(a: i32, b: i32) i32 {
return @boolToInt(a >= b);
}
fn equal(a: i32, b: i32) i32 {
return @boolToInt(a == b);
}
fn not_equal(a: i32, b: i32) i32 {
return @boolToInt(a != b);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
fn sub(a: i32, b: i32) i32 {
return a - b;
}
fn mul(a: i32, b: i32) i32 {
return a * b;
}
fn div(a: i32, b: i32) i32 {
return @divTrunc(a, b);
}
fn mod(a: i32, b: i32) i32 {
return @mod(a, b);
}
fn @"or"(a: i32, b: i32) i32 {
return @boolToInt((a != 0) or (b != 0));
}
fn @"and"(a: i32, b: i32) i32 {
return @boolToInt((a != 0) and (b != 0));
}
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var arg_it = std.process.args();
_ = try arg_it.next(allocator) orelse unreachable; // program name
const file_name = arg_it.next(allocator);
// We accept both files and standard input.
var file_handle = blk: {
if (file_name) |file_name_delimited| {
const fname: []const u8 = try file_name_delimited;
break :blk try std.fs.cwd().openFile(fname, .{});
} else {
break :blk std.io.getStdIn();
}
};
defer file_handle.close();
const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));
var string_pool = std.ArrayList([]const u8).init(allocator);
const ast = try loadAST(allocator, input_content, &string_pool);
var ast_interpreter = ASTInterpreter.init(allocator);
_ = try ast_interpreter.interp(ast);
const result: []const u8 = ast_interpreter.output.items;
_ = try std.io.getStdOut().write(result);
}
pub const NodeType = enum {
unknown,
identifier,
string,
integer,
sequence,
kw_if,
prtc,
prts,
prti,
kw_while,
assign,
negate,
not,
multiply,
divide,
mod,
add,
subtract,
less,
less_equal,
greater,
greater_equal,
equal,
not_equal,
bool_and,
bool_or,
const from_string_map = std.ComptimeStringMap(NodeType, .{
.{ "UNKNOWN", .unknown },
.{ "Identifier", .identifier },
.{ "String", .string },
.{ "Integer", .integer },
.{ "Sequence", .sequence },
.{ "If", .kw_if },
.{ "Prtc", .prtc },
.{ "Prts", .prts },
.{ "Prti", .prti },
.{ "While", .kw_while },
.{ "Assign", .assign },
.{ "Negate", .negate },
.{ "Not", .not },
.{ "Multiply", .multiply },
.{ "Divide", .divide },
.{ "Mod", .mod },
.{ "Add", .add },
.{ "Subtract", .subtract },
.{ "Less", .less },
.{ "LessEqual", .less_equal },
.{ "Greater", .greater },
.{ "GreaterEqual", .greater_equal },
.{ "Equal", .equal },
.{ "NotEqual", .not_equal },
.{ "And", .bool_and },
.{ "Or", .bool_or },
});
pub fn fromString(str: []const u8) NodeType {
return from_string_map.get(str).?;
}
};
pub const NodeValue = union(enum) {
integer: i32,
string: []const u8,
};
pub const Tree = struct {
left: ?*Tree,
right: ?*Tree,
typ: NodeType = .unknown,
value: ?NodeValue = null,
fn makeNode(allocator: std.mem.Allocator, typ: NodeType, left: ?*Tree, right: ?*Tree) !*Tree {
const result = try allocator.create(Tree);
result.* = Tree{ .left = left, .right = right, .typ = typ };
return result;
}
fn makeLeaf(allocator: std.mem.Allocator, typ: NodeType, value: ?NodeValue) !*Tree {
const result = try allocator.create(Tree);
result.* = Tree{ .left = null, .right = null, .typ = typ, .value = value };
return result;
}
};
const LoadASTError = error{OutOfMemory} || std.fmt.ParseIntError;
fn loadAST(
allocator: std.mem.Allocator,
str: []const u8,
string_pool: *std.ArrayList([]const u8),
) LoadASTError!?*Tree {
var line_it = std.mem.split(u8, str, "\n");
return try loadASTHelper(allocator, &line_it, string_pool);
}
fn loadASTHelper(
allocator: std.mem.Allocator,
line_it: *std.mem.SplitIterator(u8),
string_pool: *std.ArrayList([]const u8),
) LoadASTError!?*Tree {
if (line_it.next()) |line| {
var tok_it = std.mem.tokenize(u8, line, " ");
const tok_str = tok_it.next().?;
if (tok_str[0] == ';') return null;
const node_type = NodeType.fromString(tok_str);
const pre_iteration_index = tok_it.index;
if (tok_it.next()) |leaf_value| {
const node_value = blk: {
switch (node_type) {
.integer => break :blk NodeValue{ .integer = try std.fmt.parseInt(i32, leaf_value, 10) },
.identifier => break :blk NodeValue{ .string = leaf_value },
.string => {
tok_it.index = pre_iteration_index;
const str = tok_it.rest();
var string_literal = try std.ArrayList(u8).initCapacity(allocator, str.len);
var escaped = false;
// Truncate double quotes
for (str[1 .. str.len - 1]) |ch| {
if (escaped) {
escaped = false;
switch (ch) {
'n' => try string_literal.append('\n'),
'\\' => try string_literal.append('\\'),
else => unreachable,
}
} else {
switch (ch) {
'\\' => escaped = true,
else => try string_literal.append(ch),
}
}
}
try string_pool.append(string_literal.items);
break :blk NodeValue{ .string = string_literal.items };
},
else => unreachable,
}
};
return try Tree.makeLeaf(allocator, node_type, node_value);
}
const left = try loadASTHelper(allocator, line_it, string_pool);
const right = try loadASTHelper(allocator, line_it, string_pool);
return try Tree.makeNode(allocator, node_type, left, right);
} else {
return null;
}
}
|
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #JavaScript | JavaScript | /**
* Compare and report strings lengths.
*
* @param {Element} input - a TextArea DOM element with input
* @param {Element} output - a TextArea DOM element for output
*/
function compareStringsLength(input, output) {
// Safe defaults.
//
output.value = "";
let output_lines = [];
// Split input into an array of lines.
//
let strings = input.value.split(/\r\n|\r|\n/g);
// Is strings array empty?
//
if (strings && strings.length > 0) {
// Remove leading and trailing spaces.
//
for (let i = 0; i < strings.length; i++)
strings[i] = strings[i].trim();
// Sort by lengths.
//
strings.sort((a, b) => a.length - b.length);
// Remove empty strings.
//
while (strings[0] == "")
strings.shift();
// Check if any strings remain.
//
if (strings && strings.length > 0) {
// Get min and max length of strings.
//
const min = strings[0].length;
const max = strings[strings.length - 1].length;
// Build output verses - longest strings first.
//
for (let i = strings.length - 1; i >= 0; i--) {
let length = strings[i].length;
let predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
output_lines.push(`"${strings[i]}" has length ${length} and ${predicate}\n`);
}
// Send all lines from output_lines array to an TextArea control.
//
output.value = output_lines.join('');
}
}
}
document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output); |
http://rosettacode.org/wiki/Compiler/syntax_analyzer | Compiler/syntax analyzer | A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened format.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a parser module/library/class, it would be great
if two versions of the solution are provided: One without the parser module, and one
with.
Grammar
The simple programming language to be analyzed is more or less a (very tiny) subset of
C. The formal grammar in
Extended Backus-Naur Form (EBNF):
stmt_list = {stmt} ;
stmt = ';'
| Identifier '=' expr ';'
| 'while' paren_expr stmt
| 'if' paren_expr stmt ['else' stmt]
| 'print' '(' prt_list ')' ';'
| 'putc' paren_expr ';'
| '{' stmt_list '}'
;
paren_expr = '(' expr ')' ;
prt_list = (string | expr) {',' (String | expr)} ;
expr = and_expr {'||' and_expr} ;
and_expr = equality_expr {'&&' equality_expr} ;
equality_expr = relational_expr [('==' | '!=') relational_expr] ;
relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;
addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;
multiplication_expr = primary {('*' | '/' | '%') primary } ;
primary = Identifier
| Integer
| '(' expr ')'
| ('+' | '-' | '!') primary
;
The resulting AST should be formulated as a Binary Tree.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
The following table shows the input to lex, lex output, and the AST produced by the parser
Input to lex
Output from lex, input to parse
Output from parse
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Specifications
List of node type names
Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod
Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
In the text below, Null/Empty nodes are represented by ";".
Non-terminal (internal) nodes
For Operators, the following nodes should be created:
Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
For each of the above nodes, the left and right sub-nodes are the operands of the
respective operation.
In pseudo S-Expression format:
(Operator expression expression)
Negate, Not
For these node types, the left node is the operand, and the right node is null.
(Operator expression ;)
Sequence - sub-nodes are either statements or Sequences.
If - left node is the expression, the right node is If node, with it's left node being the
if-true statement part, and the right node being the if-false (else) statement part.
(If expression (If statement else-statement))
If there is not an else, the tree becomes:
(If expression (If statement ;))
Prtc
(Prtc (expression) ;)
Prts
(Prts (String "the string") ;)
Prti
(Prti (Integer 12345) ;)
While - left node is the expression, the right node is the statement.
(While expression statement)
Assign - left node is the left-hand side of the assignment, the right node is the
right-hand side of the assignment.
(Assign Identifier expression)
Terminal (leaf) nodes:
Identifier: (Identifier ident_name)
Integer: (Integer 12345)
String: (String "Hello World!")
";": Empty node
Some simple examples
Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.
This simple program:
a=11;
Produces the following AST, encoded as a binary tree:
Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:
(1) Sequence
(2) |-- ;
(3) |-- Assign
(4) |-- Identifier: a
(5) |-- Integer: 11
In flattened form:
(1) Sequence
(2) ;
(3) Assign
(4) Identifier a
(5) Integer 11
This program:
a=11;
b=22;
c=33;
Produces the following AST:
( 1) Sequence
( 2) |-- Sequence
( 3) | |-- Sequence
( 4) | | |-- ;
( 5) | | |-- Assign
( 6) | | |-- Identifier: a
( 7) | | |-- Integer: 11
( 8) | |-- Assign
( 9) | |-- Identifier: b
(10) | |-- Integer: 22
(11) |-- Assign
(12) |-- Identifier: c
(13) |-- Integer: 33
In flattened form:
( 1) Sequence
( 2) Sequence
( 3) Sequence
( 4) ;
( 5) Assign
( 6) Identifier a
( 7) Integer 11
( 8) Assign
( 9) Identifier b
(10) Integer 22
(11) Assign
(12) Identifier c
(13) Integer 33
Pseudo-code for the parser.
Uses Precedence Climbing for expression parsing, and
Recursive Descent for statement parsing. The AST is also built:
def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
Once the AST is built, it should be output in a flattened format. This can be as simple as the following
def prt_ast(t)
if t == NULL
print(";\n")
else
print(t.node_type)
if t.node_type in [Identifier, Integer, String] # leaf node
print the value of the Ident, Integer or String, "\n"
else
print("\n")
prt_ast(t.left)
prt_ast(t.right)
If the AST is correctly built, loading it into a subsequent program should be as simple as
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Finally, the AST can also be tested by running it against one of the AST Interpreter solutions.
Test program, assuming this is in a file called prime.t
lex <prime.t | parse
Input to lex
Output from lex, input to parse
Output from parse
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
4 1 Identifier count
4 7 Op_assign
4 9 Integer 1
4 10 Semicolon
5 1 Identifier n
5 3 Op_assign
5 5 Integer 1
5 6 Semicolon
6 1 Identifier limit
6 7 Op_assign
6 9 Integer 100
6 12 Semicolon
7 1 Keyword_while
7 7 LeftParen
7 8 Identifier n
7 10 Op_less
7 12 Identifier limit
7 17 RightParen
7 19 LeftBrace
8 5 Identifier k
8 6 Op_assign
8 7 Integer 3
8 8 Semicolon
9 5 Identifier p
9 6 Op_assign
9 7 Integer 1
9 8 Semicolon
10 5 Identifier n
10 6 Op_assign
10 7 Identifier n
10 8 Op_add
10 9 Integer 2
10 10 Semicolon
11 5 Keyword_while
11 11 LeftParen
11 12 LeftParen
11 13 Identifier k
11 14 Op_multiply
11 15 Identifier k
11 16 Op_lessequal
11 18 Identifier n
11 19 RightParen
11 21 Op_and
11 24 LeftParen
11 25 Identifier p
11 26 RightParen
11 27 RightParen
11 29 LeftBrace
12 9 Identifier p
12 10 Op_assign
12 11 Identifier n
12 12 Op_divide
12 13 Identifier k
12 14 Op_multiply
12 15 Identifier k
12 16 Op_notequal
12 18 Identifier n
12 19 Semicolon
13 9 Identifier k
13 10 Op_assign
13 11 Identifier k
13 12 Op_add
13 13 Integer 2
13 14 Semicolon
14 5 RightBrace
15 5 Keyword_if
15 8 LeftParen
15 9 Identifier p
15 10 RightParen
15 12 LeftBrace
16 9 Keyword_print
16 14 LeftParen
16 15 Identifier n
16 16 Comma
16 18 String " is prime\n"
16 31 RightParen
16 32 Semicolon
17 9 Identifier count
17 15 Op_assign
17 17 Identifier count
17 23 Op_add
17 25 Integer 1
17 26 Semicolon
18 5 RightBrace
19 1 RightBrace
20 1 Keyword_print
20 6 LeftParen
20 7 String "Total primes found: "
20 29 Comma
20 31 Identifier count
20 36 Comma
20 38 String "\n"
20 42 RightParen
20 43 Semicolon
21 1 End_of_input
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier n
Integer 1
Assign
Identifier limit
Integer 100
While
Less
Identifier n
Identifier limit
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier k
Integer 3
Assign
Identifier p
Integer 1
Assign
Identifier n
Add
Identifier n
Integer 2
While
And
LessEqual
Multiply
Identifier k
Identifier k
Identifier n
Identifier p
Sequence
Sequence
;
Assign
Identifier p
NotEqual
Multiply
Divide
Identifier n
Identifier k
Identifier k
Identifier n
Assign
Identifier k
Add
Identifier k
Integer 2
If
Identifier p
If
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier n
;
Prts
String " is prime\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
;
Sequence
Sequence
Sequence
;
Prts
String "Total primes found: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #Perl | Perl | #!/usr/bin/perl
use strict; # parse.pl - inputs lex, outputs flattened ast
use warnings; # http://www.rosettacode.org/wiki/Compiler/syntax_analyzer
my $h = qr/\G\s*\d+\s+\d+\s+/; # header of each line
sub error { die "*** Expected @_ at " . (/\G(.*\n)/ ?
$1 =~ s/^\s*(\d+)\s+(\d+)\s+/line $1 character $2 got /r : "EOF\n") }
sub want { /$h \Q$_[1]\E.*\n/gcx ? shift : error "'$_[1]'" }
local $_ = join '', <>;
print want stmtlist(), 'End_of_input';
sub stmtlist
{
/(?=$h (RightBrace|End_of_input))/gcx and return ";\n";
my ($stmt, $stmtlist) = (stmt(), stmtlist());
$stmtlist eq ";\n" ? $stmt : "Sequence\n$stmt$stmtlist";
}
sub stmt
{
/$h Semicolon\n/gcx ? ";\n" :
/$h Identifier \s+ (\w+) \n/gcx ? want("Assign\nIdentifier\t$1\n",
'Op_assign') . want expr(0), 'Semicolon' :
/$h Keyword_while \n/gcx ? "While\n" . parenexp() . stmt() :
/$h Keyword_if \n/gcx ? "If\n" . parenexp() . "If\n" . stmt() .
(/$h Keyword_else \n/gcx ? stmt() : ";\n") :
/$h Keyword_print \n/gcx ? want('', 'LeftParen') .
want want(printlist(), 'RightParen'), 'Semicolon' :
/$h Keyword_putc \n/gcx ? want "Prtc\n" . parenexp() . ";\n", 'Semicolon' :
/$h LeftBrace \n/gcx ? want stmtlist(), 'RightBrace' :
error 'A STMT';
}
sub parenexp { want('', 'LeftParen') . want expr(0), 'RightParen' } # (expr)
sub printlist
{
my $ast = /$h String \s+ (".*") \n/gcx ?
"Prts\nString\t\t$1\n;\n" : "Prti\n" . expr(0) . ";\n";
/$h Comma \n/gcx ? "Sequence\n$ast" . printlist() : $ast;
}
sub expr # (sort of EBNF) expr = operand { operator expr }
{
my $ast = # operand
/$h Integer \s+ (\d+) \n/gcx ? "Integer\t\t$1\n" :
/$h Identifier \s+ (\w+) \n/gcx ? "Identifier\t$1\n" :
/$h LeftParen \n/gcx ? want expr(0), 'RightParen' :
/$h Op_(negate|subtract) \n/gcx ? "Negate\n" . expr(8) . ";\n" :
/$h Op_not \n/gcx ? "Not\n" . expr(8) . ";\n" :
/$h Op_add \n/gcx ? expr(8) :
error "A PRIMARY";
$ast = # { operator expr }
$_[0] <= 7 && /$h Op_multiply \n/gcx ? "Multiply\n$ast" . expr(8) :
$_[0] <= 7 && /$h Op_divide \n/gcx ? "Divide\n$ast" . expr(8) :
$_[0] <= 7 && /$h Op_mod \n/gcx ? "Mod\n$ast" . expr(8) :
$_[0] <= 6 && /$h Op_add \n/gcx ? "Add\n$ast" . expr(7) :
$_[0] <= 6 && /$h Op_subtract \n/gcx ? "Subtract\n$ast" . expr(7) :
$_[0] == 5 && /(?=$h Op_(less|greater)(equal)? \n)/gcx ? error 'NO ASSOC' :
$_[0] <= 5 && /$h Op_lessequal \n/gcx ? "LessEqual\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_less \n/gcx ? "Less\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_greater \n/gcx ? "Greater\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_greaterequal \n/gcx ? "GreaterEqual\n$ast" . expr(5) :
$_[0] == 3 && /(?=$h Op_(not)?equal \n)/gcx ? error 'NO ASSOC' :
$_[0] <= 3 && /$h Op_equal \n/gcx ? "Equal\n$ast" . expr(3) :
$_[0] <= 3 && /$h Op_notequal \n/gcx ? "NotEqual\n$ast" . expr(3) :
$_[0] <= 1 && /$h Op_and \n/gcx ? "And\n$ast" . expr(2) :
$_[0] <= 0 && /$h Op_or \n/gcx ? "Or\n$ast" . expr(1) :
return $ast while 1;
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #D | D | import std.stdio, std.string, std.algorithm, std.array, std.conv;
struct GameOfLife {
enum Cell : char { dead = ' ', alive = '#' }
Cell[][] grid, newGrid;
this(in int x, in int y) pure nothrow @safe {
grid = new typeof(grid)(y + 2, x + 2);
newGrid = new typeof(grid)(y + 2, x + 2);
}
void opIndexAssign(in string[] v, in size_t y, in size_t x)
pure /*nothrow*/ @safe /*@nogc*/ {
foreach (immutable nr, row; v)
foreach (immutable nc, state; row)
grid[y + nr][x + nc] = state.to!Cell;
}
void iteration() pure nothrow @safe @nogc {
newGrid[0][] = Cell.dead;
newGrid[$ - 1][] = Cell.dead;
foreach (row; newGrid)
row[0] = row[$ - 1] = Cell.dead;
foreach (immutable r; 1 .. grid.length - 1)
foreach (immutable c; 1 .. grid[0].length - 1) {
uint count = 0;
foreach (immutable i; -1 .. 2)
foreach (immutable j; -1 .. 2)
if (i != 0 || j != 0)
count += grid[r + i][c + j] == Cell.alive;
immutable a = count == 3 ||
(count == 2 && grid[r][c] == Cell.alive);
newGrid[r][c] = a ? Cell.alive : Cell.dead;
}
grid.swap(newGrid);
}
string toString() const pure /*nothrow @safe*/ {
auto ret = "-".replicate(grid[0].length - 1) ~ "\n";
foreach (const row; grid[1 .. $ - 1])
ret ~= "|%(%c%)|\n".format(row[1 .. $ - 1]);
return ret ~ "-".replicate(grid[0].length - 1);
}
}
void main() /*@safe*/ {
immutable glider1 = [" #", "# #", " ##"];
immutable glider2 = ["# ", "# #", "## "];
auto uni = GameOfLife(60, 20);
uni[3, 2] = glider1;
uni[3, 15] = glider2;
uni[3, 19] = glider1;
uni[3, 32] = glider2;
uni[5, 50] = [" # #", "# ", "# #", "#### "];
uni.writeln;
foreach (immutable _; 0 .. 20) {
uni.iteration;
uni.writeln;
}
} |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #R | R | mypoint <- list(x=3.4, y=6.7)
# $x
# [1] 3.4
# $y
# [1] 6.7
mypoint$x # 3.4
list(a=1:10, b="abc", c=runif(10), d=list(e=1L, f=TRUE))
# $a
# [1] 1 2 3 4 5 6 7 8 9 10
# $b
# [1] "abc"
# $c
# [1] 0.64862897 0.73669435 0.11138945 0.10408015 0.46843836 0.32351247
# [7] 0.20528914 0.78512472 0.06139691 0.76937113
# $d
# $d$e
# [1] 1
# $d$f
# [1] TRUE |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Racket | Racket |
#lang racket
(struct point (x y))
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #zkl | zkl | xy:=(0).walker(*).tweak(fcn{ // generate infinite random pairs (lazy)
x:=(-15).random(16); y:=(-15).random(16);
if(not (100<=(x*x + y*y)<=225)) Void.Skip else T(x,y)
});
const N=31; // [-15..15] includes 0
array:=(" ,"*N*N).split(",").copy(); // bunch of spaces (list)
xy.walk(100).apply2(fcn([(x,y)],array){array[x+15 + N*(y+15)]="*"},array);
foreach n in ([0..30]){ array[n*N,30].concat().println(); } |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Babel | Babel |
"foo" "bar" 3 4 > sel <<
|
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #Julia | Julia | input = [
["pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 5],
[raw"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."],
[raw"-in Aus$+1411.8millions"],
[raw"===US$0017440 millions=== (in 2000 dollars)"],
["123.e8000 is pretty big."],
["The land area of the earth is 57268900(29% of the surface) square miles."],
["Ain\'t no numbers in this here words, nohow, no way, Jose."],
["James was never known as 0000000007"],
["Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."],
[raw" $-140000±100 millions."],
["6/9/1946 was a good year for some."]]
function commatize(tst)
grouping = (length(tst) == 3) ? tst[3] : 3
sep = (length(tst) > 1) ? tst[2] : ","
rmend(s) = replace(s, Regex("$sep\\Z") =>"")
greg = Regex(".{$grouping}")
cins(str) = reverse(rmend(replace(reverse(str), greg => s -> s * sep)))
mat = match(Regex("(?<![eE\\/])([1-9]\\d{$grouping,})"), tst[1])
if mat != nothing
return replace(tst[1], mat.match => cins)
end
return tst[1]
end
for tst in input
println(commatize(tst))
end
|
http://rosettacode.org/wiki/Commatizing_numbers | Commatizing numbers | Commatizing numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
Task
Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.
Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.
The number may be part of a larger (non-numeric) string such as:
«US$1744 millions» ──or──
±25000 motes.
The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated.
If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution). Error message generation is optional.
The exponent part of a number is never commatized. The following string isn't suitable for commatizing: 9.7e+12000
Leading zeroes are never commatized. The string 0000000005714.882 after commatization is: 0000000005,714.882
Any period (.) in a number is assumed to be a decimal point.
The original string is never changed except by the addition of commas [or whatever character(s) is/are used for insertion], if at all.
To wit, the following should be preserved:
leading signs (+, -) ── even superfluous signs
leading/trailing/embedded blanks, tabs, and other whitespace
the case (upper/lower) of the exponent indicator, e.g.: 4.8903d-002
Any exponent character(s) should be supported:
1247e12
57256.1D-4
4444^60
7500∙10**35
8500x10**35
9500↑35
+55000↑3
1000**100
2048²
409632
10000pow(pi)
Numbers may be terminated with any non-digit character, including subscripts and/or superscript: 41421356243 or 7320509076(base 24).
The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters. The default is the comma (,) character.
The period length can be specified (sometimes referred to as "thousands" or "thousands separators"). The period length can be defined as the length (or number) of the decimal digits between commas. The default period length is 3.
E.G.: in this example, the period length is five: 56789,12340,14148
The location of where to start the scanning for the target field (the numeric part) should be able to be specified. The default is 1.
The character strings below may be placed in a file (and read) or stored as simple strings within the program.
Strings to be used as a minimum
The value of pi (expressed in base 10) should be separated with blanks every 5 places past the decimal point,
the Zimbabwe dollar amount should use a decimal point for the "comma" separator:
pi=3.14159265358979323846264338327950288419716939937510582097494459231
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
"-in Aus$+1411.8millions"
===US$0017440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57268900(29% of the surface) square miles.
Ain't no numbers in this here words, nohow, no way, Jose.
James was never known as 0000000007
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
␢␢␢$-140000±100 millions.
6/9/1946 was a good year for some.
where the penultimate string has three leading blanks (real blanks are to be used).
Also see
The Wiki entry: (sir) Arthur Eddington's number of protons in the universe.
| #Kotlin | Kotlin | // version 1.1.4-3
val r = Regex("""(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)""")
fun String.commatize(startIndex: Int = 0, period: Int = 3, sep: String = ","): String {
if ((startIndex !in 0 until this.length) || period < 1 || sep == "") return this
val m = r.find(this, startIndex)
if (m == null) return this
val splits = m.value.split('.')
var ip = splits[0]
if (ip.length > period) {
val sb = StringBuilder(ip.reversed())
for (i in (ip.length - 1) / period * period downTo period step period) {
sb.insert(i, sep)
}
ip = sb.toString().reversed()
}
if ('.' in m.value) {
var dp = splits[1]
if (dp.length > period) {
val sb2 = StringBuilder(dp)
for (i in (dp.length - 1) / period * period downTo period step period) {
sb2.insert(i, sep)
}
dp = sb2.toString()
}
ip += "." + dp
}
return this.take(startIndex) + this.drop(startIndex).replaceFirst(m.value, ip)
}
fun main(args: Array<String>) {
val tests = arrayOf(
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-in Aus$+1411.8millions",
"===US$0017440 millions=== (in 2000 dollars)",
"123.e8000 is pretty big.",
"The land area of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000±100 millions.",
"6/9/1946 was a good year for some."
)
println(tests[0].commatize(period = 2, sep = "*"))
println(tests[1].commatize(period = 3, sep = "-"))
println(tests[2].commatize(period = 4, sep = "__"))
println(tests[3].commatize(period = 5, sep = " "))
println(tests[4].commatize(sep = "."))
for (test in tests.drop(5)) println(test.commatize())
} |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #C.2B.2B | C++ | #include <algorithm>
#include <string>
// Bug: calling operator++ on an empty collection invokes undefined behavior.
std::all_of( ++(strings.begin()), strings.end(),
[&](std::string a){ return a == strings.front(); } ) // All equal
std::is_sorted( strings.begin(), strings.end(),
[](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is no need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
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
| #Clojure | Clojure |
;; Checks if all items in strings list are equal (returns true if list is empty)
(every? (fn [[a nexta]] (= a nexta)) (map vector strings (rest strings))))
;; Checks strings list is in ascending order (returns true if list is empty)
(every? (fn [[a nexta]] (<= (compare a nexta) 0)) (map vector strings (rest strings))))
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #ALGOL_68 | ALGOL 68 | # returns a string ( assumed to be of space-separated words ) with the words #
# separated by ", ", except for the last which is separated from the rest by #
# " and ". The list is enclosed by braces #
PROC to list = ( STRING words ) STRING:
BEGIN
# count the number of words #
INT word count := 0;
BOOL in word := FALSE;
FOR char pos FROM LWB words TO UPB words
DO
IF NOT is upper( words[ char pos ] )
THEN
# not an upper-case letter, possibly a word has been ended #
in word := FALSE
ELSE
# not a delimitor, possibly the start of a word #
IF NOT in word
THEN
# we are starting a new word #
word count +:= 1;
in word := TRUE
FI
FI
OD;
# format the result #
STRING result := "{";
in word := FALSE;
INT word number := 0;
FOR char pos FROM LWB words TO UPB words
DO
IF NOT is upper( words[ char pos ] )
THEN
# not an upper-case letter, possibly a word has been ended #
in word := FALSE
ELSE
# not a delimitor, possibly the start of a word #
IF NOT in word
THEN
# we are starting a new word #
word number +:= 1;
in word := TRUE;
IF word number > 1
THEN
# second or subsequent word - need a separator #
result +:= IF word number = word count
THEN # final word #
" and "
ELSE # non-final word #
", "
FI
FI
FI;
# add the character to the result #
result +:= words[ char pos ]
FI
OD;
result + "}"
END # to list # ;
# procedure to test the to list PROC #
PROC test to list = ( STRING words ) VOID:
print( ( ( words
+ ": "
+ to list( words )
)
, newline
)
);
# test the to list PROC #
test to list( "" );
test to list( "ABC" );
test to list( "ABC DEF" );
test to list( "ABC DEF G H" ) |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S
{\displaystyle S}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:
Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,
S
{\displaystyle S}
is
{
i
c
e
d
,
j
a
m
,
p
l
a
i
n
}
{\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}
,
|
S
|
=
3
{\displaystyle |S|=3}
, and
k
=
2
{\displaystyle k=2}
.)
A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.
Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.
Also note that doughnut can also be spelled donut.
Task
Write a function/program/routine/.. to generate all the combinations with repetitions of
n
{\displaystyle n}
types of things taken
k
{\displaystyle k}
at a time and use it to show an answer to the doughnut example above.
For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.
References
k-combination with repetitions
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AppleScript | AppleScript | --------------- COMBINATIONS WITH REPETITION -------------
-- combinationsWithRepetition :: Int -> [a] -> [kTuple a]
on combinationsWithRepetition(k, xs)
-- A list of lists, representing
-- sets of cardinality k, with
-- members drawn from xs.
script combinationsBySize
script f
on |λ|(a, x)
script prefix
on |λ|(z)
{x} & z
end |λ|
end script
script go
on |λ|(ys, xs)
xs & map(prefix, ys)
end |λ|
end script
scanl1(go, a)
end |λ|
end script
on |λ|(xs)
foldl(f, {{{}}} & take(k, |repeat|({})), xs)
end |λ|
end script
|Just| of |index|(|λ|(xs) of combinationsBySize, 1 + k)
end combinationsWithRepetition
--------------------------- TEST -------------------------
on run
{length of combinationsWithRepetition(3, enumFromTo(0, 9)), ¬
combinationsWithRepetition(2, {"iced", "jam", "plain"})}
end run
------------------------- GENERIC ------------------------
-- Just :: a -> Maybe a
on Just(x)
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
-- enumFromTo :: (Int, Int) -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- index (!!) :: [a] -> Int -> Maybe a
-- index (!!) :: Gen [a] -> Int -> Maybe a
-- index (!!) :: String -> Int -> Maybe Char
on |index|(xs, i)
if script is class of xs then
repeat with j from 1 to i
set v to |λ|() of xs
end repeat
if missing value is not v then
Just(v)
else
Nothing()
end if
else
if length of xs < i then
Nothing()
else
Just(item i of xs)
end if
end if
end |index|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- repeat :: a -> Generator [a]
on |repeat|(x)
script
on |λ|()
return x
end |λ|
end script
end |repeat|
-- scanl :: (b -> a -> b) -> b -> [a] -> [b]
on scanl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
set lst to {startValue}
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
set end of lst to v
end repeat
return lst
end tell
end scanl
-- scanl1 :: (a -> a -> a) -> [a] -> [a]
on scanl1(f, xs)
if 0 < length of xs then
scanl(f, item 1 of xs, rest of xs)
else
{}
end if
end scanl1
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #C.2B.2B | C++ | #include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
mpz_int p(uint n, uint p) {
mpz_int r = 1;
mpz_int k = n - p;
while (n > k)
r *= n--;
return r;
}
mpz_int c(uint n, uint k) {
mpz_int r = p(n, k);
while (k)
r /= k--;
return r;
}
int main() {
for (uint i = 1u; i < 12u; i++)
std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
for (uint i = 10u; i < 60u; i += 10u)
std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at Permutation. 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)
Task
Implement the combination (nCk) and permutation (nPk) operators in the target language:
n
C
k
=
(
n
k
)
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
See the Wikipedia articles for a more detailed description.
To test, generate and print examples of:
A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.
Related task
Evaluate binomial coefficients
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Common_Lisp | Common Lisp | (defun combinations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m))
(b i (* b i)))
((= i k) (/ a b))))))
(defun permutations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m)))
((= i k) a)))))
|
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer).
Task[edit]
Create a lexical analyzer for the simple programming language specified below. The
program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a lexer module/library/class, it would be great
if two versions of the solution are provided: One without the lexer module, and one with.
Input Specification
The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens:
Operators
Name
Common name
Character sequence
Op_multiply
multiply
*
Op_divide
divide
/
Op_mod
mod
%
Op_add
plus
+
Op_subtract
minus
-
Op_negate
unary minus
-
Op_less
less than
<
Op_lessequal
less than or equal
<=
Op_greater
greater than
>
Op_greaterequal
greater than or equal
>=
Op_equal
equal
==
Op_notequal
not equal
!=
Op_not
unary not
!
Op_assign
assignment
=
Op_and
logical and
&&
Op_or
logical or
¦¦
The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task.
Symbols
Name
Common name
Character
LeftParen
left parenthesis
(
RightParen
right parenthesis
)
LeftBrace
left brace
{
RightBrace
right brace
}
Semicolon
semi-colon
;
Comma
comma
,
Keywords
Name
Character sequence
Keyword_if
if
Keyword_else
else
Keyword_while
while
Keyword_print
print
Keyword_putc
putc
Identifiers and literals
These differ from the the previous tokens, in that each occurrence of them has a value associated with it.
Name
Common name
Format description
Format regex
Value
Identifier
identifier
one or more letter/number/underscore characters, but not starting with a number
[_a-zA-Z][_a-zA-Z0-9]*
as is
Integer
integer literal
one or more digits
[0-9]+
as is, interpreted as a number
Integer
char literal
exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes
'([^'\n]|\\n|\\\\)'
the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n'
String
string literal
zero or more characters (anything except newline or double quote), enclosed by double quotes
"[^"\n]*"
the characters without the double quotes and with escape sequences converted
For char and string literals, the \n escape sequence is supported to represent a new-line character.
For char and string literals, to represent a backslash, use \\.
No other special sequences are supported. This means that:
Char literals cannot represent a single quote character (value 39).
String literals cannot represent strings containing double quote characters.
Zero-width tokens
Name
Location
End_of_input
when the end of the input stream is reached
White space
Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below.
"Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =).
Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge.
This means: keywords, identifiers, and integer literals.
e.g. ifprint is recognized as an identifier, instead of the keywords if and print.
e.g. 42fred is invalid, and neither recognized as a number nor an identifier.
Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value).
e.g. & & is invalid, and not interpreted as the && operator.
For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:
if ( p /* meaning n is prime */ ) {
print ( n , " " ) ;
count = count + 1 ; /* number of primes found so far */
}
if(p){print(n," ");count=count+1;}
Complete list of token names
End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract
Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal
Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if
Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen
LeftBrace RightBrace Semicolon Comma Identifier Integer
String
Output Format
The program output should be a sequence of lines, each consisting of the following whitespace-separated fields:
the line number where the token starts
the column number where the token starts
the token name
the token value (only for Identifier, Integer, and String tokens)
the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.
This task is intended to be used as part of a pipeline, with the other compiler tasks - for example:
lex < hello.t | parse | gen | vm
Or possibly:
lex hello.t lex.out
parse lex.out parse.out
gen parse.out gen.out
vm gen.out
This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.
Diagnostics
The following error conditions should be caught:
Error
Example
Empty character constant
''
Unknown escape sequence.
\r
Multi-character constant.
'xx'
End-of-file in comment. Closing comment characters not found.
End-of-file while scanning string literal. Closing string character not found.
End-of-line while scanning string literal. Closing string character not found before end-of-line.
Unrecognized character.
|
Invalid number. Starts like a number, but ends in non-numeric characters.
123abc
Test Cases
Input
Output
Test Case 1:
/*
Hello world
*/
print("Hello, World!\n");
4 1 Keyword_print
4 6 LeftParen
4 7 String "Hello, World!\n"
4 24 RightParen
4 25 Semicolon
5 1 End_of_input
Test Case 2:
/*
Show Ident and Integers
*/
phoenix_number = 142857;
print(phoenix_number, "\n");
4 1 Identifier phoenix_number
4 16 Op_assign
4 18 Integer 142857
4 24 Semicolon
5 1 Keyword_print
5 6 LeftParen
5 7 Identifier phoenix_number
5 21 Comma
5 23 String "\n"
5 27 RightParen
5 28 Semicolon
6 1 End_of_input
Test Case 3:
/*
All lexical tokens - not syntactically correct, but that will
have to wait until syntax analysis
*/
/* Print */ print /* Sub */ -
/* Putc */ putc /* Lss */ <
/* If */ if /* Gtr */ >
/* Else */ else /* Leq */ <=
/* While */ while /* Geq */ >=
/* Lbrace */ { /* Eq */ ==
/* Rbrace */ } /* Neq */ !=
/* Lparen */ ( /* And */ &&
/* Rparen */ ) /* Or */ ||
/* Uminus */ - /* Semi */ ;
/* Not */ ! /* Comma */ ,
/* Mul */ * /* Assign */ =
/* Div */ / /* Integer */ 42
/* Mod */ % /* String */ "String literal"
/* Add */ + /* Ident */ variable_name
/* character literal */ '\n'
/* character literal */ '\\'
/* character literal */ ' '
5 16 Keyword_print
5 40 Op_subtract
6 16 Keyword_putc
6 40 Op_less
7 16 Keyword_if
7 40 Op_greater
8 16 Keyword_else
8 40 Op_lessequal
9 16 Keyword_while
9 40 Op_greaterequal
10 16 LeftBrace
10 40 Op_equal
11 16 RightBrace
11 40 Op_notequal
12 16 LeftParen
12 40 Op_and
13 16 RightParen
13 40 Op_or
14 16 Op_subtract
14 40 Semicolon
15 16 Op_not
15 40 Comma
16 16 Op_multiply
16 40 Op_assign
17 16 Op_divide
17 40 Integer 42
18 16 Op_mod
18 40 String "String literal"
19 16 Op_add
19 40 Identifier variable_name
20 26 Integer 10
21 26 Integer 92
22 26 Integer 32
23 1 End_of_input
Test Case 4:
/*** test printing, embedded \n and comments with lots of '*' ***/
print(42);
print("\nHello World\nGood Bye\nok\n");
print("Print a slash n - \\n.\n");
2 1 Keyword_print
2 6 LeftParen
2 7 Integer 42
2 9 RightParen
2 10 Semicolon
3 1 Keyword_print
3 6 LeftParen
3 7 String "\nHello World\nGood Bye\nok\n"
3 38 RightParen
3 39 Semicolon
4 1 Keyword_print
4 6 LeftParen
4 7 String "Print a slash n - \\n.\n"
4 33 RightParen
4 34 Semicolon
5 1 End_of_input
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #C | C | #include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <limits.h>
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
#define da_dim(name, type) type *name = NULL; \
int _qy_ ## name ## _p = 0; \
int _qy_ ## name ## _max = 0
#define da_rewind(name) _qy_ ## name ## _p = 0
#define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \
name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)
#define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)
#define da_len(name) _qy_ ## name ## _p
typedef enum {
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,
tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,
tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,
tk_Ident, tk_Integer, tk_String
} TokenType;
typedef struct {
TokenType tok;
int err_ln, err_col;
union {
int n; /* value for constants */
char *text; /* text for idents */
};
} tok_s;
static FILE *source_fp, *dest_fp;
static int line = 1, col = 0, the_ch = ' ';
da_dim(text, char);
tok_s gettok(void);
static void error(int err_line, int err_col, const char *fmt, ... ) {
char buf[1000];
va_list ap;
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf("(%d,%d) error: %s\n", err_line, err_col, buf);
exit(1);
}
static int next_ch(void) { /* get next char from input */
the_ch = getc(source_fp);
++col;
if (the_ch == '\n') {
++line;
col = 0;
}
return the_ch;
}
static tok_s char_lit(int n, int err_line, int err_col) { /* 'x' */
if (the_ch == '\'')
error(err_line, err_col, "gettok: empty character constant");
if (the_ch == '\\') {
next_ch();
if (the_ch == 'n')
n = 10;
else if (the_ch == '\\')
n = '\\';
else error(err_line, err_col, "gettok: unknown escape sequence \\%c", the_ch);
}
if (next_ch() != '\'')
error(err_line, err_col, "multi-character constant");
next_ch();
return (tok_s){tk_Integer, err_line, err_col, {n}};
}
static tok_s div_or_cmt(int err_line, int err_col) { /* process divide or comments */
if (the_ch != '*')
return (tok_s){tk_Div, err_line, err_col, {0}};
/* comment found */
next_ch();
for (;;) {
if (the_ch == '*') {
if (next_ch() == '/') {
next_ch();
return gettok();
}
} else if (the_ch == EOF)
error(err_line, err_col, "EOF in comment");
else
next_ch();
}
}
static tok_s string_lit(int start, int err_line, int err_col) { /* "st" */
da_rewind(text);
while (next_ch() != start) {
if (the_ch == '\n') error(err_line, err_col, "EOL in string");
if (the_ch == EOF) error(err_line, err_col, "EOF in string");
da_append(text, (char)the_ch);
}
da_append(text, '\0');
next_ch();
return (tok_s){tk_String, err_line, err_col, {.text=text}};
}
static int kwd_cmp(const void *p1, const void *p2) {
return strcmp(*(char **)p1, *(char **)p2);
}
static TokenType get_ident_type(const char *ident) {
static struct {
const char *s;
TokenType sym;
} kwds[] = {
{"else", tk_Else},
{"if", tk_If},
{"print", tk_Print},
{"putc", tk_Putc},
{"while", tk_While},
}, *kwp;
return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym;
}
static tok_s ident_or_int(int err_line, int err_col) {
int n, is_number = true;
da_rewind(text);
while (isalnum(the_ch) || the_ch == '_') {
da_append(text, (char)the_ch);
if (!isdigit(the_ch))
is_number = false;
next_ch();
}
if (da_len(text) == 0)
error(err_line, err_col, "gettok: unrecognized character (%d) '%c'\n", the_ch, the_ch);
da_append(text, '\0');
if (isdigit(text[0])) {
if (!is_number)
error(err_line, err_col, "invalid number: %s\n", text);
n = strtol(text, NULL, 0);
if (n == LONG_MAX && errno == ERANGE)
error(err_line, err_col, "Number exceeds maximum value");
return (tok_s){tk_Integer, err_line, err_col, {n}};
}
return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}};
}
static tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) { /* look ahead for '>=', etc. */
if (the_ch == expect) {
next_ch();
return (tok_s){ifyes, err_line, err_col, {0}};
}
if (ifno == tk_EOI)
error(err_line, err_col, "follow: unrecognized character '%c' (%d)\n", the_ch, the_ch);
return (tok_s){ifno, err_line, err_col, {0}};
}
tok_s gettok(void) { /* return the token type */
/* skip white space */
while (isspace(the_ch))
next_ch();
int err_line = line;
int err_col = col;
switch (the_ch) {
case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}};
case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}};
case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}};
case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}};
case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}};
case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}};
case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}};
case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}};
case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}};
case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}};
case '/': next_ch(); return div_or_cmt(err_line, err_col);
case '\'': next_ch(); return char_lit(the_ch, err_line, err_col);
case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col);
case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col);
case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col);
case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col);
case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col);
case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col);
case '"' : return string_lit(the_ch, err_line, err_col);
default: return ident_or_int(err_line, err_col);
case EOF: return (tok_s){tk_EOI, err_line, err_col, {0}};
}
}
void run(void) { /* tokenize the given input */
tok_s tok;
do {
tok = gettok();
fprintf(dest_fp, "%5d %5d %.15s",
tok.err_ln, tok.err_col,
&"End_of_input Op_multiply Op_divide Op_mod Op_add "
"Op_subtract Op_negate Op_not Op_less Op_lessequal "
"Op_greater Op_greaterequal Op_equal Op_notequal Op_assign "
"Op_and Op_or Keyword_if Keyword_else Keyword_while "
"Keyword_print Keyword_putc LeftParen RightParen LeftBrace "
"RightBrace Semicolon Comma Identifier Integer "
"String "
[tok.tok * 16]);
if (tok.tok == tk_Integer) fprintf(dest_fp, " %4d", tok.n);
else if (tok.tok == tk_Ident) fprintf(dest_fp, " %s", tok.text);
else if (tok.tok == tk_String) fprintf(dest_fp, " \"%s\"", tok.text);
fprintf(dest_fp, "\n");
} while (tok.tok != tk_EOI);
if (dest_fp != stdout)
fclose(dest_fp);
}
void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {
if (fn[0] == '\0')
*fp = std;
else if ((*fp = fopen(fn, mode)) == NULL)
error(0, 0, "Can't open %s\n", fn);
}
int main(int argc, char *argv[]) {
init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : "");
init_io(&dest_fp, stdout, "wb", argc > 2 ? argv[2] : "");
run();
return 0;
} |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
print "There are " ARGC "command line parameters"
for(l=1; l<ARGC; l++) {
print "Argument " l " is " ARGV[l]
}
} |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Babel | Babel | babel -i Larry Mo Curly |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Agena | Agena | # single line comment
#/ multi-line comment
- ends with the "/ followed by #" terminator on the next line
/#
/* multi-line comment - C-style
- ends with the "* followed by /" terminator on the next line
*/ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #ALGOL_60 | ALGOL 60 |
'COMMENT' this is a first comment;
'COMMENT'
****** this is a second comment ******
;
|
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Input format:
Given the following program:
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
The output from the Code generator is a virtual assembly code program:
Output from gen, input to VM
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
The first line of the input specifies the datasize required and the number of constant
strings, in the order that they are reference via the code.
The data can be stored in a separate array, or the data can be stored at the beginning of
the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if
referenced at address 2.
If there are one or more constant strings, they come next. The code refers to these
strings by their index. The index starts at 0. So if there are 3 strings, and the code
wants to reference the 3rd string, 2 will be used.
Next comes the actual virtual assembly code. The first number is the code address of that
instruction. After that is the instruction mnemonic, followed by optional operands,
depending on the instruction.
Registers:
sp:
the stack pointer - points to the next top of stack. The stack is a 32-bit integer
array.
pc:
the program counter - points to the current instruction to be performed. The code is an
array of bytes.
Data:
data
string pool
Instructions:
Each instruction is one byte. The following instructions also have a 32-bit integer
operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
Print the word at stack top as a character.
prtc
Print the word at stack top as an integer.
prti
Stack top points to an index into the string pool. Print that entry.
prts
Unconditional stop.
halt
A simple example virtual machine
def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
AST Interpreter task
| #Mercury | Mercury | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% The Rosetta Code Virtual Machine, in Mercury.
%%%
%%% (This particular machine is arbitrarily chosen to be big-endian.)
%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module vm.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module array.
:- import_module bool.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module int32.
:- import_module list.
:- import_module string.
:- import_module uint.
:- import_module uint8.
:- import_module uint32.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% uint32 operations.
%%%
:- func twos_cmp(uint32) = uint32.
:- mode twos_cmp(in) = out is det.
:- pragma inline(twos_cmp/1).
twos_cmp(U) = NegU :-
(NegU = (\U) + 1_u32).
:- func unsigned_add(uint32, uint32) = uint32.
:- mode unsigned_add(in, in) = out is det.
:- pragma inline(unsigned_add/2).
unsigned_add(U, V) = U_plus_V :-
(U_plus_V = U + V).
:- func unsigned_sub(uint32, uint32) = uint32.
:- mode unsigned_sub(in, in) = out is det.
:- pragma inline(unsigned_sub/2).
unsigned_sub(U, V) = U_minus_V :-
(U_minus_V = U - V).
:- func signed_mul(uint32, uint32) = uint32.
:- mode signed_mul(in, in) = out is det.
:- pragma inline(signed_mul/2).
signed_mul(U, V) = UV :-
UV = cast_from_int32(cast_from_uint32(U) * cast_from_uint32(V)).
:- func signed_quot(uint32, uint32) = uint32.
:- mode signed_quot(in, in) = out is det.
:- pragma inline(signed_quot/2).
signed_quot(U, V) = U_quot_V :- % Truncation towards zero.
U_quot_V = cast_from_int32(cast_from_uint32(U)
// cast_from_uint32(V)).
:- func signed_rem(uint32, uint32) = uint32.
:- mode signed_rem(in, in) = out is det.
:- pragma inline(signed_rem/2).
signed_rem(U, V) = U_rem_V :- % Truncation towards zero, sign of U.
U_rem_V = cast_from_int32(cast_from_uint32(U)
rem cast_from_uint32(V)).
:- func signed_lt(uint32, uint32) = uint32.
:- mode signed_lt(in, in) = out is det.
:- pragma inline(signed_lt/2).
signed_lt(U, V) = U_lt_V :-
if (int32.cast_from_uint32(U) < int32.cast_from_uint32(V))
then (U_lt_V = 1_u32)
else (U_lt_V = 0_u32).
:- func signed_le(uint32, uint32) = uint32.
:- mode signed_le(in, in) = out is det.
:- pragma inline(signed_le/2).
signed_le(U, V) = U_le_V :-
if (int32.cast_from_uint32(U) =< int32.cast_from_uint32(V))
then (U_le_V = 1_u32)
else (U_le_V = 0_u32).
:- func signed_gt(uint32, uint32) = uint32.
:- mode signed_gt(in, in) = out is det.
:- pragma inline(signed_gt/2).
signed_gt(U, V) = U_gt_V :-
U_gt_V = signed_lt(V, U).
:- func signed_ge(uint32, uint32) = uint32.
:- mode signed_ge(in, in) = out is det.
:- pragma inline(signed_ge/2).
signed_ge(U, V) = U_ge_V :-
U_ge_V = signed_le(V, U).
:- func unsigned_eq(uint32, uint32) = uint32.
:- mode unsigned_eq(in, in) = out is det.
:- pragma inline(unsigned_eq/2).
unsigned_eq(U, V) = U_eq_V :-
if (U = V)
then (U_eq_V = 1_u32)
else (U_eq_V = 0_u32).
:- func unsigned_ne(uint32, uint32) = uint32.
:- mode unsigned_ne(in, in) = out is det.
:- pragma inline(unsigned_ne/2).
unsigned_ne(U, V) = U_ne_V :-
if (U \= V)
then (U_ne_V = 1_u32)
else (U_ne_V = 0_u32).
:- func logical_cmp(uint32) = uint32.
:- mode logical_cmp(in) = out is det.
:- pragma inline(logical_cmp/1).
logical_cmp(U) = NotU :-
if (U = 0_u32)
then (NotU = 1_u32)
else (NotU = 0_u32).
:- func logical_and(uint32, uint32) = uint32.
:- mode logical_and(in, in) = out is det.
:- pragma inline(logical_and/2).
logical_and(U, V) = U_and_V :-
if (U \= 0_u32, V \= 0_u32)
then (U_and_V = 1_u32)
else (U_and_V = 0_u32).
:- func logical_or(uint32, uint32) = uint32.
:- mode logical_or(in, in) = out is det.
:- pragma inline(logical_or/2).
logical_or(U, V) = U_or_V :-
if (U \= 0_u32; V \= 0_u32)
then (U_or_V = 1_u32)
else (U_or_V = 0_u32).
:- pred to_bytes(uint32, uint8, uint8, uint8, uint8).
:- mode to_bytes(in, out, out, out, out) is det.
:- pragma inline(to_bytes/5).
to_bytes(U, B3, B2, B1, B0) :-
(B0 = cast_from_int(cast_to_int(U /\ 0xFF_u32))),
(B1 = cast_from_int(cast_to_int((U >> 8) /\ 0xFF_u32))),
(B2 = cast_from_int(cast_to_int((U >> 16) /\ 0xFF_u32))),
(B3 = cast_from_int(cast_to_int((U >> 24) /\ 0xFF_u32))).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% String operations.
%%%
:- pred digit_u32(char, uint32).
:- mode digit_u32(in, out) is semidet.
digit_u32(('0'), 0_u32).
digit_u32(('1'), 1_u32).
digit_u32(('2'), 2_u32).
digit_u32(('3'), 3_u32).
digit_u32(('4'), 4_u32).
digit_u32(('5'), 5_u32).
digit_u32(('6'), 6_u32).
digit_u32(('7'), 7_u32).
digit_u32(('8'), 8_u32).
digit_u32(('9'), 9_u32).
:- pred is_not_digit(char).
:- mode is_not_digit(in) is semidet.
is_not_digit(C) :-
not is_digit(C).
:- pred is_not_alnum_nor_minus(char).
:- mode is_not_alnum_nor_minus(in) is semidet.
is_not_alnum_nor_minus(C) :-
not (is_alnum(C); C = ('-')).
:- pred det_string_to_uint32(string, uint32).
:- mode det_string_to_uint32(in, out) is det.
det_string_to_uint32(S, U) :-
to_char_list(S) = CL,
(if (det_string_to_uint32_loop(CL, 0_u32, U1))
then (U = U1)
else throw("cannot convert string to uint32")).
:- pred det_string_to_uint32_loop(list(char), uint32, uint32).
:- mode det_string_to_uint32_loop(in, in, out) is semidet.
det_string_to_uint32_loop([], U0, U1) :- U1 = U0.
det_string_to_uint32_loop([C | Tail], U0, U1) :-
digit_u32(C, Digit),
det_string_to_uint32_loop(Tail, (U0 * 10_u32) + Digit, U1).
:- pred det_signed_string_to_uint32(string, uint32).
:- mode det_signed_string_to_uint32(in, out) is det.
det_signed_string_to_uint32(S, U) :-
if prefix(S, "-")
then (det_remove_prefix("-", S, S1),
det_string_to_uint32(S1, U1),
U = twos_cmp(U1))
else det_string_to_uint32(S, U).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% Parsing the "assembly" language.
%%%
:- func opcode_halt = uint8.
:- func opcode_add = uint8.
:- func opcode_sub = uint8.
:- func opcode_mul = uint8.
:- func opcode_div = uint8.
:- func opcode_mod = uint8.
:- func opcode_lt = uint8.
:- func opcode_gt = uint8.
:- func opcode_le = uint8.
:- func opcode_ge = uint8.
:- func opcode_eq = uint8.
:- func opcode_ne = uint8.
:- func opcode_and = uint8.
:- func opcode_or = uint8.
:- func opcode_neg = uint8.
:- func opcode_not = uint8.
:- func opcode_prtc = uint8.
:- func opcode_prti = uint8.
:- func opcode_prts = uint8.
:- func opcode_fetch = uint8.
:- func opcode_store = uint8.
:- func opcode_push = uint8.
:- func opcode_jmp = uint8.
:- func opcode_jz = uint8.
opcode_halt = 0_u8.
opcode_add = 1_u8.
opcode_sub = 2_u8.
opcode_mul = 3_u8.
opcode_div = 4_u8.
opcode_mod = 5_u8.
opcode_lt = 6_u8.
opcode_gt = 7_u8.
opcode_le = 8_u8.
opcode_ge = 9_u8.
opcode_eq = 10_u8.
opcode_ne = 11_u8.
opcode_and = 12_u8.
opcode_or = 13_u8.
opcode_neg = 14_u8.
opcode_not = 15_u8.
opcode_prtc = 16_u8.
opcode_prti = 17_u8.
opcode_prts = 18_u8.
opcode_fetch = 19_u8.
opcode_store = 20_u8.
opcode_push = 21_u8.
opcode_jmp = 22_u8.
opcode_jz = 23_u8.
:- pred opcode(string, uint8).
:- mode opcode(in, out) is semidet.
%:- mode opcode(out, in) is semidet. <-- Not needed.
opcode("halt", opcode_halt).
opcode("add", opcode_add).
opcode("sub", opcode_sub).
opcode("mul", opcode_mul).
opcode("div", opcode_div).
opcode("mod", opcode_mod).
opcode("lt", opcode_lt).
opcode("gt", opcode_gt).
opcode("le", opcode_le).
opcode("ge", opcode_ge).
opcode("eq", opcode_eq).
opcode("ne", opcode_ne).
opcode("and", opcode_and).
opcode("or", opcode_or).
opcode("neg", opcode_neg).
opcode("not", opcode_not).
opcode("prtc", opcode_prtc).
opcode("prti", opcode_prti).
opcode("prts", opcode_prts).
opcode("fetch", opcode_fetch).
opcode("store", opcode_store).
opcode("push", opcode_push).
opcode("jmp", opcode_jmp).
opcode("jz", opcode_jz).
:- pred parse_header(string, uint32, uint32).
:- mode parse_header(in, out, out) is det.
parse_header(S, Datasize, Strings_Count) :-
% Split S on any non-digit characters, leaving a list of the two
% runs of digits.
if (words_separator(is_not_digit, S) = [S_Datasize, S_Strings])
% Convert the runs of digits to uint32.
then (det_string_to_uint32(S_Datasize, Datasize),
det_string_to_uint32(S_Strings, Strings_Count))
else throw("cannot parse the header").
:- pred parse_string_literal(string, string).
:- mode parse_string_literal(in, out) is det.
parse_string_literal(S0, S) :-
% Strip leading/trailing space.
S1 = strip(S0),
% Remove the " characters.
det_remove_prefix("\"", S1, S2),
det_remove_suffix(S2, "\"") = S3,
% Deal with "\\" and "\n".
replace_escapes(S3, S).
:- pred replace_escapes(string, string).
:- mode replace_escapes(in, out) is det.
replace_escapes(S0, S) :-
CL0 = to_char_list(S0),
replace_escapes(CL0, [], CL),
S = from_rev_char_list(CL).
:- pred replace_escapes(list(char), list(char), list(char)).
:- mode replace_escapes(in, in, out) is det.
replace_escapes([], Dst0, Dst) :-
Dst = Dst0.
replace_escapes([C | Tail], Dst0, Dst) :-
if (C \= ('\\'))
then replace_escapes(Tail, [C | Dst0], Dst)
else (if (Tail = [C1 | Tail1])
then (if (C1 = ('n'))
then replace_escapes(Tail1, [('\n') | Dst0], Dst)
else if (C1 = ('\\'))
then replace_escapes(Tail1, [('\\') | Dst0], Dst)
else throw("illegal escape sequence"))
else throw("truncated escape sequence")).
:- pred parse_instruction(string, {uint32, uint8, uint32}).
:- mode parse_instruction(in, out) is det.
parse_instruction(S, {Address, Opcode, Arg}) :-
words_separator(is_not_alnum_nor_minus, S) = Lst,
(if parse_instr_lst(Lst, {Addr, Op, A})
then (Address = Addr, Opcode = Op, Arg = A)
else throw("cannot parse instruction")).
:- pred parse_instr_lst(list(string), {uint32, uint8, uint32}).
:- mode parse_instr_lst(in, out) is semidet.
parse_instr_lst([S_Address, S_Opcode],
{Address, Opcode, Arg}) :-
det_string_to_uint32(S_Address, Address),
opcode(S_Opcode, Opcode),
Arg = 0_u32.
parse_instr_lst([S_Address, S_Opcode, S_Arg | _],
{Address, Opcode, Arg}) :-
det_string_to_uint32(S_Address, Address),
opcode(S_Opcode, Opcode),
det_signed_string_to_uint32(S_Arg, Arg).
:- pred parse_assembly((io.text_input_stream), uint32, uint32,
array(string),
list({uint32, uint8, uint32}),
io, io).
:- mode parse_assembly(in, out, out, out, out, di, uo) is det.
parse_assembly(InpF, Datasize, Strings_Count, Strings,
Instructions, !IO) :-
read_line_as_string(InpF, Res, !IO),
(if (Res = ok(Line))
then (parse_header(Line, Datasize, Strings_Count),
read_and_parse_strings(InpF, Strings_Count, Strings, !IO),
read_and_parse_instructions(InpF, Instructions, !IO))
else if (Res = eof)
then throw("empty input")
else throw("read error")).
:- pred read_and_parse_strings((io.text_input_stream), uint32,
array(string), io, io).
:- mode read_and_parse_strings(in, in, out, di, uo) is det.
read_and_parse_strings(InpF, Strings_Count, Strings, !IO) :-
read_n_string_literals(InpF, Strings_Count, [], Lst, !IO),
Strings = array(Lst).
:- pred read_n_string_literals((io.text_input_stream), uint32,
list(string), list(string),
io, io).
:- mode read_n_string_literals(in, in, in, out, di, uo) is det.
read_n_string_literals(InpF, N, Lst0, Lst, !IO) :-
if (N = 0_u32)
then (Lst = reverse(Lst0))
else (read_line_as_string(InpF, Res, !IO),
(if (Res = ok(Line))
then (parse_string_literal(Line, S),
read_n_string_literals(InpF, N - 1_u32,
[S | Lst0], Lst, !IO))
else if (Res = eof)
then throw("premature end of input")
else throw("read error"))).
:- pred read_and_parse_instructions((io.text_input_stream),
list({uint32, uint8, uint32}),
io, io).
:- mode read_and_parse_instructions(in, out, di, uo) is det.
read_and_parse_instructions(InpF, Instructions, !IO) :-
read_all_instructions(InpF, [], Instructions, !IO).
:- pred read_all_instructions((io.text_input_stream),
list({uint32, uint8, uint32}),
list({uint32, uint8, uint32}),
io, io).
:- mode read_all_instructions(in, in, out, di, uo) is det.
read_all_instructions(InpF, Lst0, Lst, !IO) :-
read_line_as_string(InpF, Res, !IO),
(if (Res = eof)
then (Lst = Lst0) % There is no need to reverse the list.
else if (Res = ok(Line))
then (strip(Line) = S,
(if is_empty(S)
then read_all_instructions(InpF, Lst0, Lst, !IO)
else (parse_instruction(S, Instr),
read_all_instructions(InpF, [Instr | Lst0], Lst,
!IO))))
else throw("read error")).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% Constructing the executable memory.
%%%
:- func greatest_address(list({uint32, uint8, uint32}),
uint32) = uint32.
:- mode greatest_address(in, in) = out is det.
greatest_address([], Min_Result) = Result :-
Result = Min_Result.
greatest_address([{Addr, _, _} | Tail], Min_Result) = Result :-
if (Min_Result < Addr)
then (Result = greatest_address(Tail, Addr))
else (Result = greatest_address(Tail, Min_Result)).
:- pred executable_memory(list({uint32, uint8, uint32}),
array(uint8)).
:- mode executable_memory(in, out) is det.
executable_memory(Instructions, Code) :-
greatest_address(Instructions, 0_u32) = Addr,
Code_Size = (Addr + 5_u32), % At least enough memory.
init(cast_to_int(Code_Size), opcode_halt, Code0),
fill_executable_memory(Instructions, Code0, Code).
:- pred fill_executable_memory(list({uint32, uint8, uint32}),
array(uint8), array(uint8)).
:- mode fill_executable_memory(in, array_di, array_uo) is det.
fill_executable_memory([], !Code) :- true.
fill_executable_memory([Instr | Tail], !Code) :-
Instr = {Address, Opcode, Arg},
Addr = cast_to_int(Address),
set(Addr, Opcode, !Code),
(if (Opcode = opcode_fetch;
Opcode = opcode_store;
Opcode = opcode_push;
Opcode = opcode_jmp;
Opcode = opcode_jz)
then (to_bytes(Arg, B3, B2, B1, B0),
% Store the argument in big-endian order.
set(Addr + 1, B3, !Code),
set(Addr + 2, B2, !Code),
set(Addr + 3, B1, !Code),
set(Addr + 4, B0, !Code))
else true),
fill_executable_memory(Tail, !Code).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%e
%%%
%%% Executing the code.
%%%
:- pred machine_add(array(uint32), array(uint32), uint32, uint32).
:- mode machine_add(array_di, array_uo, in, out) is det.
:- pragma inline(machine_add/4).
machine_add(Stack0, Stack, SP0, SP) :-
Result = unsigned_add(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_sub(array(uint32), array(uint32), uint32, uint32).
:- mode machine_sub(array_di, array_uo, in, out) is det.
:- pragma inline(machine_sub/4).
machine_sub(Stack0, Stack, SP0, SP) :-
Result = unsigned_sub(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_mul(array(uint32), array(uint32), uint32, uint32).
:- mode machine_mul(array_di, array_uo, in, out) is det.
:- pragma inline(machine_mul/4).
machine_mul(Stack0, Stack, SP0, SP) :-
Result = signed_mul(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_div(array(uint32), array(uint32), uint32, uint32).
:- mode machine_div(array_di, array_uo, in, out) is det.
:- pragma inline(machine_div/4).
machine_div(Stack0, Stack, SP0, SP) :-
Result = signed_quot(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_mod(array(uint32), array(uint32), uint32, uint32).
:- mode machine_mod(array_di, array_uo, in, out) is det.
:- pragma inline(machine_mod/4).
machine_mod(Stack0, Stack, SP0, SP) :-
Result = signed_rem(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_lt(array(uint32), array(uint32), uint32, uint32).
:- mode machine_lt(array_di, array_uo, in, out) is det.
:- pragma inline(machine_lt/4).
machine_lt(Stack0, Stack, SP0, SP) :-
Result = signed_lt(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_le(array(uint32), array(uint32), uint32, uint32).
:- mode machine_le(array_di, array_uo, in, out) is det.
:- pragma inline(machine_le/4).
machine_le(Stack0, Stack, SP0, SP) :-
Result = signed_le(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_gt(array(uint32), array(uint32), uint32, uint32).
:- mode machine_gt(array_di, array_uo, in, out) is det.
:- pragma inline(machine_gt/4).
machine_gt(Stack0, Stack, SP0, SP) :-
Result = signed_gt(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_ge(array(uint32), array(uint32), uint32, uint32).
:- mode machine_ge(array_di, array_uo, in, out) is det.
:- pragma inline(machine_ge/4).
machine_ge(Stack0, Stack, SP0, SP) :-
Result = signed_ge(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_eq(array(uint32), array(uint32), uint32, uint32).
:- mode machine_eq(array_di, array_uo, in, out) is det.
:- pragma inline(machine_eq/4).
machine_eq(Stack0, Stack, SP0, SP) :-
Result = unsigned_eq(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_ne(array(uint32), array(uint32), uint32, uint32).
:- mode machine_ne(array_di, array_uo, in, out) is det.
:- pragma inline(machine_ne/4).
machine_ne(Stack0, Stack, SP0, SP) :-
Result = unsigned_ne(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_and(array(uint32), array(uint32), uint32, uint32).
:- mode machine_and(array_di, array_uo, in, out) is det.
:- pragma inline(machine_and/4).
machine_and(Stack0, Stack, SP0, SP) :-
Result = logical_and(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_or(array(uint32), array(uint32), uint32, uint32).
:- mode machine_or(array_di, array_uo, in, out) is det.
:- pragma inline(machine_or/4).
machine_or(Stack0, Stack, SP0, SP) :-
Result = logical_or(lookup(Stack0, cast_to_int(SP - 1_u32)),
lookup(Stack0, cast_to_int(SP))),
set(cast_to_int(SP - 1_u32), Result, Stack0, Stack),
SP = SP0 - 1_u32.
:- pred machine_neg(array(uint32), array(uint32), uint32, uint32).
:- mode machine_neg(array_di, array_uo, in, out) is det.
:- pragma inline(machine_neg/4).
machine_neg(Stack0, Stack, SP0, SP) :-
SP = SP0,
(I = uint32.cast_to_int(SP0)),
Result = twos_cmp(lookup(Stack0, I - 1)),
set(I - 1, Result, Stack0, Stack).
:- pred machine_not(array(uint32), array(uint32), uint32, uint32).
:- mode machine_not(array_di, array_uo, in, out) is det.
:- pragma inline(machine_not/4).
machine_not(Stack0, Stack, SP0, SP) :-
SP = SP0,
(I = uint32.cast_to_int(SP0)),
Result = logical_cmp(lookup(Stack0, I - 1)),
set(I - 1, Result, Stack0, Stack).
:- pred machine_prtc((io.text_output_stream),
array(uint32), array(uint32),
uint32, uint32, io, io).
:- mode machine_prtc(in, array_di, array_uo, in, out,
di, uo) is det.
machine_prtc(OutF, Stack0, Stack, SP0, SP, !IO) :-
Stack = Stack0,
(I = uint32.cast_to_int(SP0)),
X = lookup(Stack0, I - 1),
C = (char.det_from_int(uint32.cast_to_int(X))),
(io.write_char(OutF, C, !IO)),
SP = SP0 - 1_u32.
:- pred machine_prti((io.text_output_stream),
array(uint32), array(uint32),
uint32, uint32, io, io).
:- mode machine_prti(in, array_di, array_uo, in, out,
di, uo) is det.
machine_prti(OutF, Stack0, Stack, SP0, SP, !IO) :-
Stack = Stack0,
(I = uint32.cast_to_int(SP0)),
(X = int32.cast_from_uint32(lookup(Stack0, I - 1))),
(io.write_int32(OutF, X, !IO)),
SP = SP0 - 1_u32.
:- pred machine_prts((io.text_output_stream),
array(string),
array(uint32), array(uint32),
uint32, uint32, io, io).
:- mode machine_prts(in, in, array_di, array_uo, in, out,
di, uo) is det.
machine_prts(OutF, Strings, Stack0, Stack, SP0, SP, !IO) :-
Stack = Stack0,
(I = uint32.cast_to_int(SP0)),
(K = uint32.cast_to_int(lookup(Stack0, I - 1))),
S = lookup(Strings, K),
(io.write_string(OutF, S, !IO)),
SP = SP0 - 1_u32.
:- func get_immediate(array(uint8), uint32) = uint32.
:- mode get_immediate(in, in) = out is det.
:- pragma inline(get_immediate/2).
get_immediate(Code, IP) = Immediate_Value :-
% Big-endian order.
I = cast_to_int(IP),
B3 = lookup(Code, I),
B2 = lookup(Code, I + 1),
B1 = lookup(Code, I + 2),
B0 = lookup(Code, I + 3),
Immediate_Value = from_bytes_be(B3, B2, B1, B0).
:- pred machine_fetch(array(uint32), array(uint32),
array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32).
:- mode machine_fetch(array_di, array_uo, in, in, out,
array_di, array_uo, in, out) is det.
:- pragma inline(machine_fetch/9).
machine_fetch(Data0, Data, Code, IP0, IP, !Stack, SP0, SP) :-
Data = Data0,
K = get_immediate(Code, IP0),
IP = IP0 + 4_u32,
X = lookup(Data0, cast_to_int(K)),
set(cast_to_int(SP0), X, !Stack),
SP = SP0 + 1_u32.
:- pred machine_store(array(uint32), array(uint32),
array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32).
:- mode machine_store(array_di, array_uo, in, in, out,
array_di, array_uo, in, out) is det.
:- pragma inline(machine_store/9).
machine_store(!Data, Code, IP0, IP, Stack0, Stack, SP0, SP) :-
Stack = Stack0,
K = get_immediate(Code, IP0),
IP = IP0 + 4_u32,
SP = SP0 - 1_u32,
X = lookup(Stack0, cast_to_int(SP)),
set(cast_to_int(K), X, !Data).
:- pred machine_push(array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32).
:- mode machine_push(in, in, out, array_di, array_uo, in, out) is det.
:- pragma inline(machine_push/7).
machine_push(Code, IP0, IP, !Stack, SP0, SP) :-
X = get_immediate(Code, IP0),
IP = IP0 + 4_u32,
set(cast_to_int(SP0), X, !Stack),
SP = SP0 + 1_u32.
:- pred machine_jmp(array(uint8), uint32, uint32).
:- mode machine_jmp(in, in, out) is det.
:- pragma inline(machine_jmp/3).
machine_jmp(Code, IP0, IP) :-
Offset = get_immediate(Code, IP0),
IP = unsigned_add(IP0, Offset).
:- pred machine_jz(array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32).
:- mode machine_jz(in, in, out, array_di, array_uo, in, out) is det.
:- pragma inline(machine_jz/7).
machine_jz(Code, IP0, IP, Stack0, Stack, SP0, SP) :-
Stack = Stack0,
SP = SP0 - 1_u32,
X = lookup(Stack0, cast_to_int(SP)),
(if (X = 0_u32)
then (Offset = get_immediate(Code, IP0),
IP = unsigned_add(IP0, Offset))
else (IP = IP0 + 4_u32)).
:- pred run_one_instruction((io.text_output_stream),
array(string),
array(uint32), array(uint32),
array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32, bool, io, io).
:- mode run_one_instruction(in, in, array_di, array_uo,
in, in, out, array_di, array_uo,
in, out, out, di, uo) is det.
run_one_instruction(OutF, Strings, !Data,
Code, IP0, IP, !Stack, !SP,
Halt, !IO) :-
%
% In the following implementation, any unrecognized instruction
% causes a HALT, just as an actual "halt" opcode would.
%
Opcode = lookup(Code, cast_to_int(IP0)),
IP1 = IP0 + 1_u32,
I = (Opcode >> 2),
J = (Opcode /\ 0x03_u8),
(if (I = 0_u8)
then (IP = IP1,
(if (J = 0_u8)
then (Halt = yes)
else if (J = 1_u8)
then (machine_add(!Stack, !SP),
Halt = no)
else if (J = 2_u8)
then (machine_sub(!Stack, !SP),
Halt = no)
else (machine_mul(!Stack, !SP),
Halt = no)))
else if (I = 1_u8)
then (Halt = no,
IP = IP1,
(if (J = 0_u8)
then machine_div(!Stack, !SP)
else if (J = 1_u8)
then machine_mod(!Stack, !SP)
else if (J = 2_u8)
then machine_lt(!Stack, !SP)
else machine_gt(!Stack, !SP)))
else if (I = 2_u8)
then (Halt = no,
IP = IP1,
(if (J = 0_u8)
then machine_le(!Stack, !SP)
else if (J = 1_u8)
then machine_ge(!Stack, !SP)
else if (J = 2_u8)
then machine_eq(!Stack, !SP)
else machine_ne(!Stack, !SP)))
else if (I = 3_u8)
then (Halt = no,
IP = IP1,
(if (J = 0_u8)
then machine_and(!Stack, !SP)
else if (J = 1_u8)
then machine_or(!Stack, !SP)
else if (J = 2_u8)
then machine_neg(!Stack, !SP)
else machine_not(!Stack, !SP)))
else if (I = 4_u8)
then (Halt = no,
(if (J = 0_u8)
then (machine_prtc(OutF, !Stack, !SP, !IO),
IP = IP1)
else if (J = 1_u8)
then (machine_prti(OutF, !Stack, !SP, !IO),
IP = IP1)
else if (J = 2_u8)
then (machine_prts(OutF, Strings, !Stack, !SP, !IO),
IP = IP1)
else machine_fetch(!Data, Code, IP1, IP, !Stack, !SP)))
else if (I = 5_u8)
then (Halt = no,
(if (J = 0_u8)
then machine_store(!Data, Code, IP1, IP, !Stack, !SP)
else if (J = 1_u8)
then machine_push(Code, IP1, IP, !Stack, !SP)
else if (J = 2_u8)
then machine_jmp(Code, IP1, IP)
else machine_jz(Code, IP1, IP, !Stack, !SP)))
else (Halt = yes, IP = IP1)).
:- pred run_program((io.text_output_stream), array(string),
array(uint32), array(uint32),
array(uint8), uint32, uint32,
array(uint32), array(uint32),
uint32, uint32, io, io).
:- mode run_program(in, in, array_di, array_uo,
in, in, out, array_di, array_uo,
in, out, di, uo) is det.
run_program(OutF, Strings, !Data, Code, !IP, !Stack, !SP, !IO) :-
run_one_instruction(OutF, Strings, !Data, Code, !IP, !Stack, !SP,
Halt, !IO),
(if (Halt = yes)
then true
else run_program(OutF, Strings, !Data, Code, !IP, !Stack,
!SP, !IO)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- pred open_InpF(text_input_stream, string, io, io).
:- mode open_InpF(out, in, di, uo) is det.
open_InpF(InpF, InpF_filename, !IO) :-
if (InpF_filename = "-")
then (InpF = io.stdin_stream)
else (open_input(InpF_filename, InpF_result, !IO),
(if (InpF_result = ok(F))
then (InpF = F)
else throw("Error: cannot open " ++ InpF_filename ++
" for input"))).
:- pred open_OutF(text_output_stream, string, io, io).
:- mode open_OutF(out, in, di, uo) is det.
open_OutF(OutF, OutF_filename, !IO) :-
if (OutF_filename = "-")
then (OutF = io.stdout_stream)
else (open_output(OutF_filename, OutF_result, !IO),
(if (OutF_result = ok(F))
then (OutF = F)
else throw("Error: cannot open " ++ OutF_filename ++
" for output"))).
:- pred main_program(string, string, io, io).
:- mode main_program(in, in, di, uo) is det.
main_program(InpF_filename, OutF_filename, !IO) :-
open_InpF(InpF, InpF_filename, !IO),
open_OutF(OutF, OutF_filename, !IO),
parse_assembly(InpF, Datasize, _Strings_Count, Strings,
Instructions, !IO),
(if (InpF_filename = "-")
then true
else close_input(InpF, !IO)),
executable_memory(Instructions, Code),
init(cast_to_int(Datasize), 0_u32, Data0),
init(2048, 0_u32, Stack0), % Stack is 2048 words.
IP0 = 0_u32,
SP0 = 0_u32,
run_program(OutF, Strings, Data0, _Data, Code, IP0, _IP,
Stack0, _Stack, SP0, _SP, !IO),
(if (OutF_filename = "-")
then true
else close_output(OutF, !IO)).
:- pred usage_error(io, io).
:- mode usage_error(di, uo) is det.
usage_error(!IO) :-
progname("lex", ProgName, !IO),
(io.format("Usage: %s [INPUT_FILE [OUTPUT_FILE]]\n",
[s(ProgName)], !IO)),
(io.write_string(
"If INPUT_FILE is \"-\" or not present then standard input is used.\n",
!IO)),
(io.write_string(
"If OUTPUT_FILE is \"-\" or not present then standard output is used.\n",
!IO)),
set_exit_status(1, !IO).
main(!IO) :-
command_line_arguments(Args, !IO),
(if (Args = [])
then (InpF_filename = "-",
OutF_filename = "-",
main_program(InpF_filename, OutF_filename, !IO))
else if (Args = [F1])
then (InpF_filename = F1,
OutF_filename = "-",
main_program(InpF_filename, OutF_filename, !IO))
else if (Args = [F1, F2])
then (InpF_filename = F1,
OutF_filename = F2,
main_program(InpF_filename, OutF_filename, !IO))
else usage_error(!IO)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Instructions for GNU Emacs--
%%% local variables:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% end:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
http://rosettacode.org/wiki/Compiler/code_generator | Compiler/code generator | A code generator translates the output of the syntax analyzer and/or semantic analyzer
into lower level code, either assembly, object, or virtual.
Task[edit]
Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the
Virtual machine interpreter. The output is in text format, and represents virtual assembly code.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
while.ast can be input into the code generator.
The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code.
Run as: lex < while.t | parse | gen
Input to lex
Output from lex, input to parse
Output from parse
Output from gen, input to VM
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt
Input format
As shown in the table, above, the output from the syntax analyzer is a flattened AST.
In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes.
Loading this data into an internal parse tree should be as simple as:
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";"
return None
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Output format - refer to the table above
The first line is the header: Size of data, and number of constant strings.
size of data is the number of 32-bit unique variables used. In this example, one variable, count
number of constant strings is just that - how many there are
After that, the constant strings
Finally, the assembly code
Registers
sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array.
pc: the program counter - points to the current instruction to be performed. The code is an array of bytes.
Data
32-bit integers and strings
Instructions
Each instruction is one byte. The following instructions also have a 32-bit integer operand:
fetch [index]
where index is an index into the data array.
store [index]
where index is an index into the data array.
push n
where value is a 32-bit integer that will be pushed onto the stack.
jmp (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
jz (n) addr
where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.
The following instructions do not have an operand. They perform their operation directly
against the stack:
For the following instructions, the operation is performed against the top two entries in
the stack:
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
For the following instructions, the operation is performed against the top entry in the
stack:
neg
not
prtc
Print the word at stack top as a character.
prti
Print the word at stack top as an integer.
prts
Stack top points to an index into the string pool. Print that entry.
halt
Unconditional stop.
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Virtual Machine Interpreter task
AST Interpreter task
| #Julia | Julia | import Base.show
mutable struct Asm32
offset::Int32
code::String
arg::Int32
targ::Int32
end
Asm32(code, arg = 0) = Asm32(0, code, arg, 0)
show(io::IO, a::Asm32) = print(io, lpad("$(a.offset)", 6), lpad(a.code, 8),
a.targ > 0 ? (lpad("($(a.arg))", 8) * lpad("$(a.targ)", 4)) :
(a.code in ["store", "fetch"] ? lpad("[$(a.arg)]", 8) :
(a.code in ["push"] ? lpad("$(a.arg)", 8) : "")))
const ops32 = Dict{String,String}("Multiply" => "mul", "Divide" => "div", "Mod" => "mod", "Add" => "add",
"Subtract" => "sub", "Less" => "lt", "Greater" => "gt", "LessEqual" => "le", "GreaterEqual" => "ge",
"Equal" => "eq", "NotEqual" => "ne", "And" => "and", "or" => "or", "Not" => "not", "Minus" => "neg",
"Prtc" => "prtc", "Prti" => "prti", "Prts" => "prts")
function compiletoasm(io)
identifiers = Vector{String}()
strings = Vector{String}()
labels = Vector{Int}()
function cpile(io, islefthandside = false)
arr = Vector{Asm32}()
jlabel() = (push!(labels, length(labels) + 1); labels[end])
m = match(r"^(\w+|;)\s*([\d\w\"\\ \S]+)?", strip(readline(io)))
x, val = m == nothing ? Pair(";", 0) : m.captures
if x == ";" return arr
elseif x == "Assign"
lhs = cpile(io, true)
rhs = cpile(io)
append!(arr, rhs)
append!(arr, lhs)
if length(arr) > 100 exit() end
elseif x == "Integer" push!(arr, Asm32("push", parse(Int32, val)))
elseif x == "String"
if !(val in strings)
push!(strings, val)
end
push!(arr, Asm32("push", findfirst(x -> x == val, strings) - 1))
elseif x == "Identifier"
if !(val in identifiers)
if !islefthandside
throw("Identifier $val referenced before it is assigned")
end
push!(identifiers, val)
end
push!(arr, Asm32(islefthandside ? "store" : "fetch", findfirst(x -> x == val, identifiers) - 1))
elseif haskey(ops32, x)
append!(arr, cpile(io))
append!(arr, cpile(io))
push!(arr, Asm32(ops32[x]))
elseif x == "If"
append!(arr, cpile(io))
x, y = jlabel(), jlabel()
push!(arr, Asm32("jz", x))
append!(arr, cpile(io))
push!(arr, Asm32("jmp", y))
a = cpile(io)
if length(a) < 1
push!(a, Asm32("nop", 0))
end
a[1].offset = x
append!(arr, a)
push!(arr, Asm32(y, "nop", 0, 0)) # placeholder
elseif x == "While"
x, y = jlabel(), jlabel()
a = cpile(io)
if length(a) < 1
push!(a, Asm32("nop", 0))
end
a[1].offset = x
append!(arr, a)
push!(arr, Asm32("jz", y))
append!(arr, cpile(io))
push!(arr, Asm32("jmp", x), Asm32(y, "nop", 0, 0))
elseif x == "Sequence"
append!(arr, cpile(io))
append!(arr, cpile(io))
else
throw("unknown node type: $x")
end
arr
end
# compile AST
asmarr = cpile(io)
push!(asmarr, Asm32("halt"))
# move address markers to working code and prune nop code
for (i, acode) in enumerate(asmarr)
if acode.code == "nop" && acode.offset != 0 && i < length(asmarr)
asmarr[i + 1].offset = asmarr[i].offset
end
end
filter!(x -> x.code != "nop", asmarr)
# renumber offset column with actual offsets
pos = 0
jmps = Dict{Int, Int}()
for acode in asmarr
if acode.offset > 0
jmps[acode.offset] = pos
end
acode.offset = pos
pos += acode.code in ["push", "store", "fetch", "jz", "jmp"] ? 5 : 1
end
# fix up jump destinations
for acode in asmarr
if acode.code in ["jz", "jmp"]
if haskey(jmps, acode.arg)
acode.targ = jmps[acode.arg]
acode.arg = acode.targ - acode.offset -1
else
throw("unknown jump location: $acode")
end
end
end
# print Datasize and Strings header
println("Datasize: $(length(identifiers)) Strings: $(length(strings))\n" *
join(strings, "\n") )
# print assembly lines
foreach(println, asmarr)
end
const testAST = raw"""
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1 """
iob = IOBuffer(testAST) # use an io buffer here for testing, but could use stdin instead of iob
compiletoasm(iob)
|
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance | Compare sorting algorithms' performance |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Measure a relative performance of sorting algorithms implementations.
Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).
Consider three type of input sequences:
ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}
Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).
For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.
Preliminary subtask:
Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
Query Performance
Write float arrays to a text file
Plot x, y arrays
Polynomial Fitting
General steps:
Define sorting routines to be considered.
Define appropriate sequence generators and write timings.
Plot timings.
What conclusions about relative performance of the sorting routines could be made based on the plots?
| #Phix | Phix | -- demo\rosetta\Compare_sorting_algorithms.exw
constant XQS = 01 -- (set to 1 to exclude quick_sort and shell_sort from ones)
include pGUI.e
Ihandle dlg, tabs, plot
Ihandles plots
function quick_sort2(sequence x)
integer n = length(x)
if n<2 then
return x -- already sorted (trivial case)
end if
integer mid = floor((n+1)/2),
midn = 1
object midval = x[mid]
sequence left = {}, right = {}
x[mid] = x[1]
for i=2 to n do
object xi = x[i]
integer c = compare(xi,midval)
if c<0 then
left = append(left,xi)
elsif c>0 then
right = append(right,xi)
else
midn += 1
end if
end for
return quick_sort2(left) & repeat(midval,midn) & quick_sort2(right)
end function
function quick_sort(sequence s)
sequence qstack = repeat(0,floor((length(s)/5)+10)) -- create a stack
integer first = 1,
last = length(s),
stackptr = 0
while true do
while first<last do
object pivot = s[floor(last+first)/2],
si, sj
integer I = first,
J = last
while true do
while true do
si = s[I]
if si>=pivot then exit end if
I += 1
end while
while true do
sj = s[J]
if sj<=pivot then exit end if
J -= 1
end while
if I>J then exit end if
if I<J then
if si=sj then
{I,J} = {J+1,I-1}
exit
end if
s[I] = sj
s[J] = si
end if
I += 1
J -= 1
if I>J then exit end if
end while
if I<last then
qstack[stackptr+1] = I
qstack[stackptr+2] = last
stackptr += 2
end if
last = J
end while
if stackptr=0 then exit end if
stackptr -= 2
first = qstack[stackptr+1]
last = qstack[stackptr+2]
end while
return s
end function
function radixSortn(sequence s, integer n)
sequence buckets = repeat({},10)
sequence res = {}
for i=1 to length(s) do
integer digit = remainder(floor(s[i]/power(10,n-1)),10)+1
buckets[digit] = append(buckets[digit],s[i])
end for
for i=1 to length(buckets) do
integer len = length(buckets[i])
if len!=0 then
if len=1 or n=1 then
res &= buckets[i]
else
res &= radixSortn(buckets[i],n-1)
end if
end if
end for
return res
end function
function split_by_sign(sequence s)
sequence buckets = {{},{}}
for i=1 to length(s) do
integer si = s[i]
if si<0 then
buckets[1] = append(buckets[1],-si)
else
buckets[2] = append(buckets[2],si)
end if
end for
return buckets
end function
function radix_sort(sequence s)
-- NB this is an integer-only sort
integer mins = min(s),
passes = floor(log10(max(max(s),abs(mins))))+1
if mins<0 then
sequence buckets = split_by_sign(s)
buckets[1] = reverse(sq_uminus(radixSortn(buckets[1],passes)))
buckets[2] = radixSortn(buckets[2],passes)
s = buckets[1]&buckets[2]
else
s = radixSortn(s,passes)
end if
return s
end function
function shell_sort(sequence s)
integer gap = floor(length(s)/2)
while gap>0 do
for i=gap to length(s) do
object temp = s[i]
integer j = i-gap
while j>=1 and temp<=s[j] do
s[j+gap] = s[j]
j -= gap
end while
s[j+gap] = temp
end for
gap = floor(gap/2)
end while
return s
end function
function shell_sort2(sequence x)
integer last = length(x),
gap = floor(last/10)+1
while TRUE do
integer first = gap+1
for i=first to last do
object xi = x[i]
integer j = i-gap
while TRUE do
object xj = x[j]
if xi>=xj then
j += gap
exit
end if
x[j+gap] = xj
if j<=gap then
exit
end if
j -= gap
end while
x[j] = xi
end for
if gap=1 then
return x
else
gap = floor(gap/3.5)+1
end if
end while
end function
function siftDown(sequence arr, integer s, integer last)
integer root = s
while root*2<=last do
integer child = root*2
if child<last and arr[child]<arr[child+1] then
child += 1
end if
if arr[root]>=arr[child] then exit end if
object tmp = arr[root]
arr[root] = arr[child]
arr[child] = tmp
root = child
end while
return arr
end function
function heapify(sequence arr, integer count)
integer s = floor(count/2)
while s>0 do
arr = siftDown(arr,s,count)
s -= 1
end while
return arr
end function
function heap_sort(sequence arr)
integer last = length(arr)
arr = heapify(arr,last)
while last>1 do
object tmp = arr[1]
arr[1] = arr[last]
arr[last] = tmp
last -= 1
arr = siftDown(arr,1,last)
end while
return arr
end function
include builtins/sort.e
enum ONES = 1, SORTED = 2, RANDOM = 3, REVERSE = 4
constant tabtitles = {"ones","sorted","random","reverse"}
integer tabidx = 3
integer STEP
function tr(sequence name, integer rid=routine_id(name))
return {name,rid}
end function
constant tests = {tr("quick_sort"),
tr("quick_sort2"),
tr("radix_sort"),
tr("shell_sort"),
tr("shell_sort2"),
tr("heap_sort"),
tr("sort"), -- builtin
}
sequence results = repeat(repeat({}, length(tests)),length(tabtitles))
sequence dsdx = repeat(repeat(0,length(tests)),length(tabtitles))
integer ds_index
function idle_action_cb()
atom best = -1, -- fastest last
besti = 0, -- 1..length(tests)
bestt = 0, -- 1..length(tabtitles)
len
--
-- Search for something to do, active/visible tab first.
-- Any result set of length 0 -> just do one.
-- Of all result sets<8, pick the lowest [$].
--
sequence todo = {tabidx}
for t=1 to length(tabtitles) do
if t!=tabidx then todo &= t end if
end for
for t=1 to length(tabtitles) do
integer ti = todo[t]
for i=1 to length(results[ti]) do
len = length(results[ti][i])
if len=0 then
best = 0
besti = i
bestt = ti
exit
elsif len<8 then
if (best=-1) or (best>results[ti][i][$]) then
best = results[ti][i][$]
besti = i
bestt = ti
end if
end if
end for
if (t=1) and (besti!=0) then exit end if
end for
if best>10 then
-- cop out if it is getting too slow
besti = 0
end if
if besti!=0 then
STEP = iff(not XQS and bestt=ONES?1000:100000)
len = (length(results[bestt][besti])+1)*STEP
sequence test = iff(bestt=ONES?repeat(1,len):
iff(bestt=SORTED?tagset(len):
iff(bestt=RANDOM?shuffle(tagset(len)):
iff(bestt=REVERSE?reverse(tagset(len)):9/0))))
ds_index = dsdx[bestt][besti]
atom t0 = time()
sequence check = call_func(tests[besti][2],{test})
t0 = time()-t0
-- if check!=sort(test) then ?9/0 end if
plot = plots[bestt]
IupPlotInsert(plot, ds_index, -1, len, t0)
results[bestt][besti] = append(results[bestt][besti],t0)
IupSetAttribute(plot,"REDRAW",NULL)
sequence progress = {bestt}
for i=1 to length(results[bestt]) do
progress &= length(results[bestt][i])
end for
IupSetStrAttribute(dlg,"TITLE","Compare sorting algorithms %s",{sprint(progress)})
return IUP_CONTINUE
end if
IupSetAttribute(dlg,"TITLE","Compare sorting algorithms (all done, idle)")
return IUP_IGNORE -- all done, remove callback
end function
constant cb_idle_action = Icallback("idle_action_cb")
function tabchange_cb(Ihandle /*self*/, Ihandle /*new_tab*/)
tabidx = IupGetInt(tabs,"VALUEPOS")+1
plot = plots[tabidx]
return IUP_DEFAULT;
end function
procedure main()
IupOpen()
plots = {}
for i=1 to length(tabtitles) do
if XQS then
-- results[ONES][1] = repeat(0,8)
results[ONES][4] = repeat(0,8)
end if
plot = IupPlot()
IupSetAttribute(plot,"MENUITEMPROPERTIES","YES")
IupSetAttribute(plot,"TABTITLE",tabtitles[i])
IupSetAttribute(plot,"GRID","YES")
IupSetAttribute(plot,"MARGINLEFT","50")
IupSetAttribute(plot,"MARGINBOTTOM","40")
IupSetAttribute(plot,"LEGEND","YES")
IupSetAttribute(plot,"LEGENDPOS","TOPLEFT")
-- IupSetAttribute(plot,"AXS_YSCALE","LOG10")
-- IupSetAttribute(plot,"AXS_XSCALE","LOG10")
for j=1 to length(tests) do
IupPlotBegin(plot)
dsdx[i][j] = IupPlotEnd(plot)
IupSetAttribute(plot,"DS_NAME",tests[j][1])
end for
plots = append(plots,plot)
end for
tabs = IupTabs(plots)
IupSetCallback(tabs, "TABCHANGE_CB", Icallback("tabchange_cb"))
dlg = IupDialog(tabs, "RASTERSIZE=800x480")
IupSetAttribute(dlg, "TITLE", "Compare sorting algorithms")
IupShow(dlg)
IupSetInt(tabs, "VALUEPOS", tabidx-1)
IupSetGlobalFunction("IDLE_ACTION", cb_idle_action)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Compiler/AST_interpreter | Compiler/AST interpreter | An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is as simple as (pseudo code)
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
The interpreter algorithm is relatively simple
interp(x)
if x == NULL return NULL
elif x.node_type == Integer return x.value converted to an integer
elif x.node_type == Ident return the current value of variable x.value
elif x.node_type == String return x.value
elif x.node_type == Assign
globals[x.left.value] = interp(x.right)
return NULL
elif x.node_type is a binary operator return interp(x.left) operator interp(x.right)
elif x.node_type is a unary operator, return return operator interp(x.left)
elif x.node_type == If
if (interp(x.left)) then interp(x.right.left)
else interp(x.right.right)
return NULL
elif x.node_type == While
while (interp(x.left)) do interp(x.right)
return NULL
elif x.node_type == Prtc
print interp(x.left) as a character, no newline
return NULL
elif x.node_type == Prti
print interp(x.left) as an integer, no newline
return NULL
elif x.node_type == Prts
print interp(x.left) as a string, respecting newlines ("\n")
return NULL
elif x.node_type == Sequence
interp(x.left)
interp(x.right)
return NULL
else
error("unknown node type")
Notes:
Because of the simple nature of our tiny language, Semantic analysis is not needed.
Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0.
This means, for instance, that 3 / 2 should result in 1.
For division when one of the operands is negative, the result should be truncated towards 0.
This means, for instance, that 3 / -2 should result in -1.
Test program
prime.t
lex <prime.t | parse | interp
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
101 is prime
Total primes found: 26
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Syntax Analyzer task
Code Generator task
Virtual Machine Interpreter task
| #zkl | zkl | const{ var _n=-1; var[proxy]N=fcn{ _n+=1 }; } // enumerator
const FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N,
LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N,
AND=N, OR=N, NEG=N, NOT=N,
JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N;
const nd_String=N, nd_Sequence=N, nd_If=N, nd_While=N;
var [const]
all_syms=Dictionary(
"Identifier" ,FETCH, "String" ,nd_String,
"Integer" ,PUSH, "Sequence" ,nd_Sequence,
"If" ,nd_If, "Prtc" ,PRTC,
"Prts" ,PRTS, "Prti" ,PRTI,
"While" ,nd_While, "Assign" ,STORE,
"Negate" ,NEG, "Not" ,NOT,
"Multiply" ,MUL, "Divide" ,DIV,
"Mod" ,MOD, "Add" ,ADD,
"Subtract" ,SUB, "Less" ,LT,
"LessEqual" ,LE, "Greater" ,GT,
"GreaterEqual",GE, "Equal" ,EQ,
"NotEqual" ,NE, "And" ,AND,
"Or" ,OR, "halt" ,HALT),
bops=Dictionary(ADD,'+, SUB,'-, MUL,'*, DIV,'/, MOD,'%,
LT,'<, GT,'>, LE,'<=, GE,'>=, NE,'!=, EQ,'==, NE,'!=);
class Node{
fcn init(_node_type, _value, _left=Void, _right=Void){
var type=_node_type, left=_left, right=_right, value=_value;
}
}
fcn runNode(node){
var vars=Dictionary(); // fcn local static var
if(Void==node) return();
switch(node.type){
case(PUSH,nd_String){ return(node.value) }
case(FETCH){ return(vars[node.value]) }
case(STORE){ vars[node.left.value]=runNode(node.right); return(Void); }
case(nd_If){
if(runNode(node.left)) runNode(node.right.left);
else runNode(node.right.right);
}
case(nd_While)
{ while(runNode(node.left)){ runNode(node.right) } return(Void) }
case(nd_Sequence){ runNode(node.left); runNode(node.right); return(Void) }
case(PRTC) { print(runNode(node.left).toAsc()) }
case(PRTI,PRTS) { print(runNode(node.left)) }
case(NEG) { return(-runNode(node.left)) }
case(NOT) { return(not runNode(node.left)) }
case(AND) { return(runNode(node.left) and runNode(node.right)) }
case(OR) { return(runNode(node.left) or runNode(node.right)) }
else{
if(op:=bops.find(node.type))
return(op(runNode(node.left),runNode(node.right)));
else throw(Exception.AssertionError(
"Unknown node type: %d".fmt(node.type)))
}
}
Void
} |
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #Julia | Julia | s = "niño"
println("Position Char Bytes\n==============================")
for (i, c) in enumerate(s)
println("$i $c $(sizeof(c))")
end
|
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.
Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.
Extra credit
Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.
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
| #jq | jq |
def s1: "longer";
def s2: "shorter😀";
[s1,s2]
| sort_by(length)
| reverse[]
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."
|
http://rosettacode.org/wiki/Compiler/syntax_analyzer | Compiler/syntax analyzer | A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened format.
The program should read input from a file and/or stdin, and write output to a file and/or
stdout. If the language being used has a parser module/library/class, it would be great
if two versions of the solution are provided: One without the parser module, and one
with.
Grammar
The simple programming language to be analyzed is more or less a (very tiny) subset of
C. The formal grammar in
Extended Backus-Naur Form (EBNF):
stmt_list = {stmt} ;
stmt = ';'
| Identifier '=' expr ';'
| 'while' paren_expr stmt
| 'if' paren_expr stmt ['else' stmt]
| 'print' '(' prt_list ')' ';'
| 'putc' paren_expr ';'
| '{' stmt_list '}'
;
paren_expr = '(' expr ')' ;
prt_list = (string | expr) {',' (String | expr)} ;
expr = and_expr {'||' and_expr} ;
and_expr = equality_expr {'&&' equality_expr} ;
equality_expr = relational_expr [('==' | '!=') relational_expr] ;
relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ;
addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ;
multiplication_expr = primary {('*' | '/' | '%') primary } ;
primary = Identifier
| Integer
| '(' expr ')'
| ('+' | '-' | '!') primary
;
The resulting AST should be formulated as a Binary Tree.
Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions
lex < while.t > while.lex
Run one of the Syntax analyzer solutions
parse < while.lex > while.ast
The following table shows the input to lex, lex output, and the AST produced by the parser
Input to lex
Output from lex, input to parse
Output from parse
count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
1 1 Identifier count
1 7 Op_assign
1 9 Integer 1
1 10 Semicolon
2 1 Keyword_while
2 7 LeftParen
2 8 Identifier count
2 14 Op_less
2 16 Integer 10
2 18 RightParen
2 20 LeftBrace
3 5 Keyword_print
3 10 LeftParen
3 11 String "count is: "
3 23 Comma
3 25 Identifier count
3 30 Comma
3 32 String "\n"
3 36 RightParen
3 37 Semicolon
4 5 Identifier count
4 11 Op_assign
4 13 Identifier count
4 19 Op_add
4 21 Integer 1
4 22 Semicolon
5 1 RightBrace
6 1 End_of_input
Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
Specifications
List of node type names
Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod
Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
In the text below, Null/Empty nodes are represented by ";".
Non-terminal (internal) nodes
For Operators, the following nodes should be created:
Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or
For each of the above nodes, the left and right sub-nodes are the operands of the
respective operation.
In pseudo S-Expression format:
(Operator expression expression)
Negate, Not
For these node types, the left node is the operand, and the right node is null.
(Operator expression ;)
Sequence - sub-nodes are either statements or Sequences.
If - left node is the expression, the right node is If node, with it's left node being the
if-true statement part, and the right node being the if-false (else) statement part.
(If expression (If statement else-statement))
If there is not an else, the tree becomes:
(If expression (If statement ;))
Prtc
(Prtc (expression) ;)
Prts
(Prts (String "the string") ;)
Prti
(Prti (Integer 12345) ;)
While - left node is the expression, the right node is the statement.
(While expression statement)
Assign - left node is the left-hand side of the assignment, the right node is the
right-hand side of the assignment.
(Assign Identifier expression)
Terminal (leaf) nodes:
Identifier: (Identifier ident_name)
Integer: (Integer 12345)
String: (String "Hello World!")
";": Empty node
Some simple examples
Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path.
This simple program:
a=11;
Produces the following AST, encoded as a binary tree:
Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node:
(1) Sequence
(2) |-- ;
(3) |-- Assign
(4) |-- Identifier: a
(5) |-- Integer: 11
In flattened form:
(1) Sequence
(2) ;
(3) Assign
(4) Identifier a
(5) Integer 11
This program:
a=11;
b=22;
c=33;
Produces the following AST:
( 1) Sequence
( 2) |-- Sequence
( 3) | |-- Sequence
( 4) | | |-- ;
( 5) | | |-- Assign
( 6) | | |-- Identifier: a
( 7) | | |-- Integer: 11
( 8) | |-- Assign
( 9) | |-- Identifier: b
(10) | |-- Integer: 22
(11) |-- Assign
(12) |-- Identifier: c
(13) |-- Integer: 33
In flattened form:
( 1) Sequence
( 2) Sequence
( 3) Sequence
( 4) ;
( 5) Assign
( 6) Identifier a
( 7) Integer 11
( 8) Assign
( 9) Identifier b
(10) Integer 22
(11) Assign
(12) Identifier c
(13) Integer 33
Pseudo-code for the parser.
Uses Precedence Climbing for expression parsing, and
Recursive Descent for statement parsing. The AST is also built:
def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
Once the AST is built, it should be output in a flattened format. This can be as simple as the following
def prt_ast(t)
if t == NULL
print(";\n")
else
print(t.node_type)
if t.node_type in [Identifier, Integer, String] # leaf node
print the value of the Ident, Integer or String, "\n"
else
print("\n")
prt_ast(t.left)
prt_ast(t.right)
If the AST is correctly built, loading it into a subsequent program should be as simple as
def load_ast()
line = readline()
# Each line has at least one token
line_list = tokenize the line, respecting double quotes
text = line_list[0] # first token is always the node type
if text == ";" # a terminal node
return NULL
node_type = text # could convert to internal form if desired
# A line with two tokens is a leaf node
# Leaf nodes are: Identifier, Integer, String
# The 2nd token is the value
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
Finally, the AST can also be tested by running it against one of the AST Interpreter solutions.
Test program, assuming this is in a file called prime.t
lex <prime.t | parse
Input to lex
Output from lex, input to parse
Output from parse
/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
4 1 Identifier count
4 7 Op_assign
4 9 Integer 1
4 10 Semicolon
5 1 Identifier n
5 3 Op_assign
5 5 Integer 1
5 6 Semicolon
6 1 Identifier limit
6 7 Op_assign
6 9 Integer 100
6 12 Semicolon
7 1 Keyword_while
7 7 LeftParen
7 8 Identifier n
7 10 Op_less
7 12 Identifier limit
7 17 RightParen
7 19 LeftBrace
8 5 Identifier k
8 6 Op_assign
8 7 Integer 3
8 8 Semicolon
9 5 Identifier p
9 6 Op_assign
9 7 Integer 1
9 8 Semicolon
10 5 Identifier n
10 6 Op_assign
10 7 Identifier n
10 8 Op_add
10 9 Integer 2
10 10 Semicolon
11 5 Keyword_while
11 11 LeftParen
11 12 LeftParen
11 13 Identifier k
11 14 Op_multiply
11 15 Identifier k
11 16 Op_lessequal
11 18 Identifier n
11 19 RightParen
11 21 Op_and
11 24 LeftParen
11 25 Identifier p
11 26 RightParen
11 27 RightParen
11 29 LeftBrace
12 9 Identifier p
12 10 Op_assign
12 11 Identifier n
12 12 Op_divide
12 13 Identifier k
12 14 Op_multiply
12 15 Identifier k
12 16 Op_notequal
12 18 Identifier n
12 19 Semicolon
13 9 Identifier k
13 10 Op_assign
13 11 Identifier k
13 12 Op_add
13 13 Integer 2
13 14 Semicolon
14 5 RightBrace
15 5 Keyword_if
15 8 LeftParen
15 9 Identifier p
15 10 RightParen
15 12 LeftBrace
16 9 Keyword_print
16 14 LeftParen
16 15 Identifier n
16 16 Comma
16 18 String " is prime\n"
16 31 RightParen
16 32 Semicolon
17 9 Identifier count
17 15 Op_assign
17 17 Identifier count
17 23 Op_add
17 25 Integer 1
17 26 Semicolon
18 5 RightBrace
19 1 RightBrace
20 1 Keyword_print
20 6 LeftParen
20 7 String "Total primes found: "
20 29 Comma
20 31 Identifier count
20 36 Comma
20 38 String "\n"
20 42 RightParen
20 43 Semicolon
21 1 End_of_input
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier n
Integer 1
Assign
Identifier limit
Integer 100
While
Less
Identifier n
Identifier limit
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier k
Integer 3
Assign
Identifier p
Integer 1
Assign
Identifier n
Add
Identifier n
Integer 2
While
And
LessEqual
Multiply
Identifier k
Identifier k
Identifier n
Identifier p
Sequence
Sequence
;
Assign
Identifier p
NotEqual
Multiply
Divide
Identifier n
Identifier k
Identifier k
Identifier n
Assign
Identifier k
Add
Identifier k
Integer 2
If
Identifier p
If
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier n
;
Prts
String " is prime\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
;
Sequence
Sequence
Sequence
;
Prts
String "Total primes found: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Additional examples
Your solution should pass all the test cases above and the additional tests found Here.
Reference
The C and Python versions can be considered reference implementations.
Related Tasks
Lexical Analyzer task
Code Generator task
Virtual Machine Interpreter task
AST Interpreter task
| #Phix | Phix | --
-- demo\rosetta\Compiler\parse.e
-- =============================
--
-- The reusable part of parse.exw
--
with javascript_semantics
include lex.e
sequence tok
procedure errd(sequence msg, sequence args={})
{tok_line,tok_col} = tok
error(msg,args)
end procedure
global sequence toks
integer next_tok = 1
function get_tok()
sequence tok = toks[next_tok]
next_tok += 1
return tok
end function
procedure expect(string msg, integer s)
integer tk = tok[3]
if tk!=s then
errd("%s: Expecting '%s', found '%s'\n", {msg, tkNames[s], tkNames[tk]})
end if
tok = get_tok()
end procedure
function expr(integer p)
object x = NULL, node
integer op = tok[3]
switch op do
case tk_LeftParen:
tok = get_tok()
x = expr(0)
expect("expr",tk_RightParen)
case tk_sub:
case tk_add:
tok = get_tok()
node = expr(precedences[tk_neg]);
x = iff(op==tk_sub?{tk_neg, node, NULL}:node)
case tk_not:
tok = get_tok();
x = {tk_not, expr(precedences[tk_not]), NULL}
case tk_Identifier:
x = {tk_Identifier, tok[4]}
tok = get_tok();
case tk_Integer:
x = {tk_Integer, tok[4]}
tok = get_tok();
default:
errd("Expecting a primary, found: %s\n", tkNames[op])
end switch
op = tok[3]
while narys[op]=BINARY
and precedences[op]>=p do
tok = get_tok()
x = {op, x, expr(precedences[op]+1)}
op = tok[3]
end while
return x;
end function
function paren_expr(string msg)
expect(msg, tk_LeftParen);
object t = expr(0)
expect(msg, tk_RightParen);
return t
end function
function stmt()
object t = NULL, e, s
switch tok[3] do
case tk_if:
tok = get_tok();
object condition = paren_expr("If-cond");
object ifblock = stmt();
object elseblock = NULL;
if tok[3] == tk_else then
tok = get_tok();
elseblock = stmt();
end if
t = {tk_if, condition, {tk_if, ifblock, elseblock}}
case tk_putc:
tok = get_tok();
e = paren_expr("Prtc")
t = {tk_putc, e, NULL}
expect("Putc", tk_Semicolon);
case tk_print:
tok = get_tok();
expect("Print",tk_LeftParen)
while 1 do
if tok[3] == tk_String then
e = {tk_Prints, {tk_String, tok[4]}, NULL}
tok = get_tok();
else
e = {tk_Printi, expr(0), NULL}
end if
t = {tk_Sequence, t, e}
if tok[3]!=tk_Comma then exit end if
expect("Print", tk_Comma)
end while
expect("Print", tk_RightParen);
expect("Print", tk_Semicolon);
case tk_Semicolon:
tok = get_tok();
case tk_Identifier:
object v
v = {tk_Identifier, tok[4]}
tok = get_tok();
expect("assign", tk_assign);
e = expr(0);
t = {tk_assign, v, e}
expect("assign", tk_Semicolon);
case tk_while:
tok = get_tok();
e = paren_expr("while");
s = stmt();
t = {tk_while, e, s}
case tk_LeftBrace: /* {stmt} */
expect("LeftBrace", tk_LeftBrace)
while not find(tok[3],{tk_RightBrace,tk_EOI}) do
t = {tk_Sequence, t, stmt()}
end while
expect("LeftBrace", tk_RightBrace);
break;
case tk_EOI:
break;
default:
errd("expecting start of statement, found '%s'\n", tkNames[tok[3]]);
end switch
return t
end function
global function parse()
object t = NULL
tok = get_tok()
while 1 do
object s = stmt()
if s=NULL then exit end if
t = {tk_Sequence, t, s}
end while
return t
end function
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Dart | Dart | /**
* States of a cell. A cell is either [ALIVE] or [DEAD].
* The state contains its [symbol] for printing.
*/
class State {
const State(this.symbol);
static final ALIVE = const State('#');
static final DEAD = const State(' ');
final String symbol;
}
/**
* The "business rule" of the game. Depending on the count of neighbours,
* the [cellState] changes.
*/
class Rule {
Rule(this.cellState);
reactToNeighbours(int neighbours) {
if (neighbours == 3) {
cellState = State.ALIVE;
} else if (neighbours != 2) {
cellState = State.DEAD;
}
}
var cellState;
}
/**
* A coordinate on the [Grid].
*/
class Point {
const Point(this.x, this.y);
operator +(other) => new Point(x + other.x, y + other.y);
final int x;
final int y;
}
/**
* List of the relative indices of the 8 cells around a cell.
*/
class Neighbourhood {
List<Point> points() {
return [
new Point(LEFT, UP), new Point(MIDDLE, UP), new Point(RIGHT, UP),
new Point(LEFT, SAME), new Point(RIGHT, SAME),
new Point(LEFT, DOWN), new Point(MIDDLE, DOWN), new Point(RIGHT, DOWN)
];
}
static final LEFT = -1;
static final MIDDLE = 0;
static final RIGHT = 1;
static final UP = -1;
static final SAME = 0;
static final DOWN = 1;
}
/**
* The grid is an endless, two-dimensional [field] of cell [State]s.
*/
class Grid {
Grid(this.xCount, this.yCount) {
_field = new Map();
_neighbours = new Neighbourhood().points();
}
set(point, state) {
_field[_pos(point)] = state;
}
State get(point) {
var state = _field[_pos(point)];
return state != null ? state : State.DEAD;
}
int countLiveNeighbours(point) =>
_neighbours.filter((offset) => get(point + offset) == State.ALIVE).length;
_pos(point) => '${(point.x + xCount) % xCount}:${(point.y + yCount) % yCount}';
print() {
var sb = new StringBuffer();
iterate((point) { sb.add(get(point).symbol); }, (x) { sb.add("\n"); });
return sb.toString();
}
iterate(eachCell, [finishedRow]) {
for (var x = 0; x < xCount; x++) {
for (var y = 0; y < yCount; y++) {
eachCell(new Point(x, y));
}
if(finishedRow != null) {
finishedRow(x);
}
}
}
final xCount, yCount;
List<Point> _neighbours;
Map<String, State> _field;
}
/**
* The game updates the [grid] in each step using the [Rule].
*/
class Game {
Game(this.grid);
tick() {
var newGrid = createNewGrid();
grid.iterate((point) {
var rule = new Rule(grid.get(point));
rule.reactToNeighbours(grid.countLiveNeighbours(point));
newGrid.set(point, rule.cellState);
});
grid = newGrid;
}
createNewGrid() => new Grid(grid.xCount, grid.yCount);
printGrid() => print(grid.print());
Grid grid;
}
main() {
// Run the GoL with a blinker.
runBlinker();
}
runBlinker() {
var game = new Game(createBlinkerGrid());
for(int i = 0; i < 3; i++) {
game.printGrid();
game.tick();
}
game.printGrid();
}
createBlinkerGrid() {
var grid = new Grid(4, 4);
loadBlinker(grid);
return grid;
}
loadBlinker(grid) => blinkerPoints().forEach((point) => grid.set(point, State.ALIVE));
blinkerPoints() => [new Point(0, 1), new Point(1, 1), new Point(2, 1)]; |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Raku | Raku | my @point = 3, 8;
my Int @point = 3, 8; # or constrain to integer elements |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | x= -4.9
y= 1.7
point=x y |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR i=1 TO 1000
20 LET x=RND*31-16
30 LET y=RND*31-16
40 LET r=SQR (x*x+y*y)
50 IF (r>=10) AND (r<=15) THEN PLOT 127+x*2,88+y*2
60 NEXT i |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #BASIC | BASIC | 10 LET A%=1: REM A HAS A VALUE OF TRUE
20 IF A% THEN PRINT "A IS TRUE"
30 WE CAN OF COURSE USE EXPRESSIONS
40 IF A%<>0 THEN PRINT "A IS TRUE"
50 IF NOT(A%) THEN PRINT "A IS FALSE"
60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD
70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.