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/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Sidef | Sidef | class Format(text, width) {
method align(j) {
text.map { |row|
row.range.map { |i|
'%-*s ' % (width[i],
'%*s' % (row[i].len + (width[i]-row[i].len * j/2), row[i]));
}.join("");
}.join("\n") + "\n";
}
}
func Formatter(text) {
var textArr = [];
var widthArr = [];
text.each_line {
var words = .split('$');
textArr.append(words);
words.each_kv { |i, word|
if (i == widthArr.len) {
widthArr.append(word.len);
}
elsif (word.len > widthArr[i]) {
widthArr[i] = word.len;
}
}
}
return Format(textArr, widthArr);
}
enum |left, middle, right|;
const text = <<'EOT';
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
EOT
var f = Formatter(text);
say f.align(left);
say f.align(middle);
say f.align(right); |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
Imports System.Collections.ObjectModel
Module Module1
Dim sWords As New Dictionary(Of String, Collection(Of String))
Sub Main()
Dim oStream As StreamReader = Nothing
Dim sLines() As String = Nothing
Dim sSorted As String = Nothing
Dim iHighCount As Integer = 0
Dim iMaxKeyLength As Integer = 0
Dim sOutput As String = ""
oStream = New StreamReader("unixdict.txt")
sLines = oStream.ReadToEnd.Split(New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
oStream.Close()
For i As Integer = 0 To sLines.GetUpperBound(0)
sSorted = SortCharacters(sLines(i))
If Not sWords.ContainsKey(sSorted) Then sWords.Add(sSorted, New Collection(Of String))
sWords(sSorted).Add(sLines(i))
If sWords(sSorted).Count > iHighCount Then
iHighCount = sWords(sSorted).Count
If sSorted.Length > iMaxKeyLength Then iMaxKeyLength = sSorted.Length
End If
Next
For Each sKey As String In sWords.Keys
If sWords(sKey).Count = iHighCount Then
sOutput &= "[" & sKey.ToUpper & "]" & Space(iMaxKeyLength - sKey.Length + 1) & String.Join(", ", sWords(sKey).ToArray()) & vbCrLf
End If
Next
Console.WriteLine(sOutput)
Console.ReadKey()
End Sub
Private Function SortCharacters(ByVal s As String) As String
Dim sReturn() As Char = s.ToCharArray()
Dim sTemp As Char = Nothing
For i As Integer = 0 To sReturn.GetUpperBound(0) - 1
If (sReturn(i + 1)) < (sReturn(i)) Then
sTemp = sReturn(i)
sReturn(i) = sReturn(i + 1)
sReturn(i + 1) = sTemp
i = -1
End If
Next
Return CStr(sReturn)
End Function
End Module |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Hoon | Hoon |
|= [m=@ud n=@ud]
?: =(m 0)
+(n)
?: =(n 0)
$(n 1, m (dec m))
$(m (dec m), n $(n (dec n)))
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Smalltalk | Smalltalk | text :=
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$''dollar''$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
'.
printSep :=
[:colLengths |
Stdout nextPut:$+.
colLengths do:[:len | Stdout next:len put:$-; nextPut:$+ ].
Stdout cr.
].
printRows :=
[:text :box :justifyEach |
lines := StringCollection fromString:text.
rowSet := lines collect:[:line | line splitBy:$$ ].
maxNumCols := (rowSet collect:[:row | row size]) max.
maxLengths := rowSet
inject:(Array new:maxNumCols withAll:0)
into:[:maxesSoFar :row|
maxesSoFar
with:(row paddedTo:maxNumCols with:'')
collect:[:maxLen :col | maxLen max: col size]].
rowSet do:[:row |
|first|
box ifTrue:[ printSep value:maxLengths ].
first := true.
(box ifTrue:[row paddedTo:maxLengths size with:''] ifFalse:[row])
with: (box ifTrue:[maxLengths] ifFalse:[maxLengths to:row size])
do:[:col :len |
first ifTrue:[ box ifTrue:[Stdout nextPutAll:'|']. first := false.].
Stdout print:(justifyEach value:col value:len).
Stdout nextPutAll:(box ifTrue:'|' ifFalse:' ')
].
Stdout cr.
].
box ifTrue:[ printSep value:maxLengths ].
].
printRightJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col leftPaddedTo:len)]].
printLeftJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col paddedTo:len)]].
printCentered :=
[:text :box | printRows value:text value:box value:[:col :len | col centerPaddedTo:len]].
Stdout printCR:'Left justified:'.
printLeftJustified value:text value:false.
Stdout cr; printCR:'Right justified:'.
printRightJustified value:text value:false.
Stdout cr; printCR:'Centered:'.
printCentered value:text value:false.
Stdout cr; printCR:'Left justified with box:'.
printLeftJustified value:text value:true.
Stdout cr; printCR:'Right justified with box:'.
printRightJustified value:text value:true.
Stdout cr; printCR:'Centered with box:'.
printCentered value:text value:true. |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Vlang | Vlang | import os
fn main(){
words := os.read_lines('unixdict.txt')?
mut m := map[string][]string{}
mut ma := 0
for word in words {
mut letters := word.split('')
letters.sort()
sorted_word := letters.join('')
if sorted_word in m {
m[sorted_word] << word
} else {
m[sorted_word] = [word]
}
if m[sorted_word].len > ma {
ma = m[sorted_word].len
}
}
for _, a in m {
if a.len == ma {
println(a)
}
}
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Icon_and_Unicon | Icon and Unicon | procedure acker(i, j)
static memory
initial {
memory := table()
every memory[0 to 100] := table()
}
if i = 0 then return j + 1
if j = 0 then /memory[i][j] := acker(i - 1, 1)
else /memory[i][j] := acker(i - 1, acker(i, j - 1))
return memory[i][j]
end
procedure main()
every m := 0 to 3 do {
every n := 0 to 8 do {
writes(acker(m, n) || " ")
}
write()
}
end |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Snobol | Snobol | * Since we don't know how much text we'll be reading in,
* we store the words and field widths in tables
Words = TABLE()
Widths = TABLE()
* Match text from start of string to the first dollar sign
WordPat = POS(0) BREAK('$') . Word LEN(1) REM . Rest
* We output the results aligned three different ways; these are the
* labels for those sections of output:
Labels = ARRAY(3)
Labels<1> = "Left-justified"
Labels<2> = "Right-justified"
Labels<3> = "Centered"
* There are built-in functions for left- and right- justification,
* but not necessarily one for centering (depending on
* implementation). So we define one.
DEFINE('CPAD(Word,Width)Z,Left') :(END_CPAD)
CPAD Z = SIZE(Word)
Left = Z + (Width - Z) / 2
CPAD = RPAD(LPAD(Word, Left), Width) :(RETURN)
END_CPAD
* Read in our text a line at a time and split into words on '$'
InLineLoop Line = INPUT :F(DoneReading)
LineCount = LineCount + 1
Column = 0
InWordLoop Column = Column + 1
* Separate Line into Word, Line=Rest at first dollar sign
Line WordPat = Rest :S(CheckMax)
* If there was no '$', the whole line is the next word
Word = Line
Line =
* Keep track of the largest number of columns on any line
CheckMax LE(Column, MaxColumn) :S(StoreWord)
MaxColumn = Column
StoreWord Words<LineCount ',' Column> = Word
* And the size of the longest word in each column
GT(SIZE(Word),Widths<Column>) :F(NoNewMaxWidth)
Widths<Column> = SIZE(Word)
* Loop if the line isn't empty yet
NoNewMaxWidth GT(Size(Line)) :S(InWordLoop) F(InLineLoop)
DoneReading
* Now we print the results out in the three justification styles
Style = 0
StyleLoop Style = Style + 1
GT(Style, 3) :S(END)
OUTPUT =
OUTPUT = Labels<Style> ':'
I = 0
OutLineLoop I = I + 1
GT(I, LineCount) :S(StyleLoop)
* Build up the output line by fields starting with the null string
Line =
J = 0
OutWordLoop J = J + 1
GT(J, MaxColumn) :S(PrintLine)
Word = Words<I ',' J>
GT(SIZE(Word)) :F(PrintLine)
* Place the word within the column according to the pass we're on
EQ(Style, 1) :F(NotLeft)
* Left-justified
Word = RPAD(Word, Widths<J>) :(AddWord)
NotLeft EQ(Style, 2) :F(NotRight)
* Right-justified
Word = LPAD(Word, Widths<J>) :(AddWord)
* Centered
NotRight Word = CPAD(Word, Widths<J>)
* Add word to line and loop
AddWord Line = Line GT(SIZE(Line)) ' '
Line = Line Word :(OutWordLoop)
* Print the line
PrintLine OUTPUT = Line :(OutLineLoop)
END
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Wren | Wren | import "io" for File
import "/sort" for Sort
var words = File.read("unixdict.txt").split("\n").map { |w| w.trim() }
var wordMap = {}
for (word in words) {
var letters = word.toList
Sort.insertion(letters)
var sortedWord = letters.join()
if (wordMap.containsKey(sortedWord)) {
wordMap[sortedWord].add(word)
} else {
wordMap[sortedWord] = [word]
}
}
var most = wordMap.keys.reduce(0) { |max, key| (wordMap[key].count > max) ? wordMap[key].count : max }
for (key in wordMap.keys) {
if (wordMap[key].count == most) System.print(wordMap[key])
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Idris | Idris | A : Nat -> Nat -> Nat
A Z n = S n
A (S m) Z = A m (S Z)
A (S m) (S n) = A m (A (S m) n) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Standard_ML | Standard ML | fun curry f x y = f (x, y)
fun uncurry f (x, y) = f x y
fun maxWidths ([], widths) = widths
| maxWidths (strings, []) = map size strings
| maxWidths (s :: ss, w :: ws) = Int.max (size s, w) :: maxWidths (ss, ws)
val alignL = uncurry (StringCvt.padRight #" ")
and alignR = uncurry (StringCvt.padLeft #" ")
fun alignC (w, s) =
alignL (w, alignR ((w + size s) div 2, s))
fun formatTable tab =
let
val columnWidths = foldl maxWidths [] tab
in
fn f => String.concatWith "\n"
(map (String.concatWith " " o curry (ListPair.map f) columnWidths) tab)
end
val readTable =
map (String.fields (curry op= #"$"))
o String.tokens (curry op= #"\n")
o TextIO.inputAll
(* test stdin with all alignments *)
val () = print (String.concatWith "\n\n"
(map (formatTable (readTable TextIO.stdIn)) [alignL, alignC, alignR]) ^ "\n") |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Yabasic | Yabasic | filename$ = "unixdict.txt"
maxw = 0 : c = 0 : dimens(c)
i = 0
dim p(100)
if (not open(1,filename$)) error "Could not open '"+filename$+"' for reading"
print "Be patient, please ...\n"
while(not eof(1))
line input #1 a$
c = c + 1
p$(c) = a$
po$(c) = sort$(lower$(a$))
count = 0
head = 0
insert(1)
if not(mod(c, 10)) dimens(c)
wend
for n = 1 to i
nw = p(n)
repeat
print p$(nw)," ";
nw = d(nw,2)
until(not nw)
print
next n
print "\n", peek("secondsrunning"), " sec"
sub sort$(a$)
local n, i, t$, c1$, c2$
for n = 1 to len(a$) - 1
for i = n + 1 to len(a$)
c1$ = mid$(a$, n, 1) : c2$ = mid$(a$, i, 1)
if c1$ > c2$ then
t$ = c1$
c1$ = c2$
c2$ = t$
mid$(a$, n, 1) = c1$ : mid$(a$, i, 1) = c2$
end if
next i
next n
return a$
end sub
sub dimens(c)
redim p$(c + 10)
redim po$(c + 10)
redim d(c + 10, 3)
end sub
sub insert(j)
local p
if po$(c) < po$(j) then
p = 1
elseif po$(c) = po$(j) then
p = 2
if count = 0 head = j
count = count + 1
if count > maxw then
i = 1
p(i) = head
maxw = count
elseif count = maxw then
i = i + 1
p(i) = head
end if
else
p = 3
end if
if d(j,p) then
insert(d(j,p))
else
d(j,p) = c
end if
end sub |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Ioke | Ioke | ackermann = method(m,n,
cond(
m zero?, n succ,
n zero?, ackermann(m pred, 1),
ackermann(m pred, ackermann(m, n pred)))
) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Swift | Swift | import Foundation
extension String {
func dropLastIf(_ char: Character) -> String {
if last == char {
return String(dropLast())
} else {
return self
}
}
}
enum Align {
case left, center, right
}
func getLines(input: String) -> [String] {
input
.components(separatedBy: "\n")
.map({ $0.replacingOccurrences(of: " ", with: "").dropLastIf("$") })
}
func getColWidths(from: String) -> [Int] {
var widths = [Int]()
let lines = getLines(input: from)
for line in lines {
let lens = line.components(separatedBy: "$").map({ $0.count })
for (i, len) in lens.enumerated() {
if i < widths.count {
widths[i] = max(widths[i], len)
} else {
widths.append(len)
}
}
}
return widths
}
func alignCols(input: String, align: Align = .left) -> String {
let widths = getColWidths(from: input)
let lines = getLines(input: input)
var res = ""
for line in lines {
for (str, width) in zip(line.components(separatedBy: "$"), widths) {
let blanks = width - str.count
let pre: Int, post: Int
switch align {
case .left:
(pre, post) = (0, blanks)
case .center:
(pre, post) = (blanks / 2, (blanks + 1) / 2)
case .right:
(pre, post) = (blanks, 0)
}
res += String(repeating: " ", count: pre)
res += str
res += String(repeating: " ", count: post)
res += " "
}
res += "\n"
}
return res
}
let input = """
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
"""
print(alignCols(input: input))
print()
print(alignCols(input: input, align: .center))
print()
print(alignCols(input: input, align: .right)) |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #zkl | zkl | File("unixdict.txt").read(*) // dictionary file to blob, copied from web
// blob to dictionary: key is word "fuzzed", values are anagram words
.pump(Void,T(fcn(w,d){
key:=w.split("").sort().concat(); // fuzz word to key
d.appendV(key,w); // add or append w
},d:=Dictionary(0d60_000)));
d.filter(fcn([(k,v)]){ v.len()>3 }) // prune to list of # words > 3
.sort(fcn([(_,v1)],[(_,v2)]){ v1.len()>v2.len() }) // sort by word count
[0,10].pump(Console.println,'wrap([(zz,v)]){ // and print 10 biggest
"%d:%s: %s".fmt(v.len(),zz.strip(),
v.apply("strip").concat(","))
}); |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #J | J | ack=: c1`c1`c2`c3 @. (#.@,&*) M.
c1=: >:@] NB. if 0=x, 1+y
c2=: <:@[ ack 1: NB. if 0=y, (x-1) ack 1
c3=: <:@[ ack [ ack <:@] NB. else, (x-1) ack x ack y-1 |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Tcl | Tcl | package require Tcl 8.5
set text {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.}
array set max {}
foreach line [split $text \n] {
set col 0
set thisline [split $line \$]
lappend words $thisline
foreach word $thisline {
set max([incr col]) [expr {[info exists max($col)]
? max($max($col), [string length $word])
: [string length $word]
}]
}
}
proc justify {word position width} {
switch -exact -- $position {
left {
return [format "%-*s" $width $word]
}
center {
set lpadw [expr {($width - [string length $word])/2}]
return [format "%s%-*s" [string repeat " " $lpadw] [incr width -$lpadw] $word]
}
right {
return [format "%*s" $width $word]
}
}
}
foreach position {left center right} {
foreach thisline $words {
set col 0
set line ""
foreach word $thisline {
append line [justify $word $position $max([incr col])] " "
}
puts [string trimright $line]
}
puts ""
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Java | Java | import java.math.BigInteger;
public static BigInteger ack(BigInteger m, BigInteger n) {
return m.equals(BigInteger.ZERO)
? n.add(BigInteger.ONE)
: ack(m.subtract(BigInteger.ONE),
n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE)));
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Transd | Transd | #lang transd
MainModule : {
txt:
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.",
tabl: Table(),
n: 0,
colWidths: Vector<Int>(),
print: (λ centered Bool(false)
(for n in Seq(0 (num-rows tabl)) do
(with row (get-row tabl n)
(for m in Seq(0 (num-cols tabl)) do
(with wid (+ 1.0 (get colWidths @idx))
word (get row m) wl 0.0 lef 0
(if centered (= wl (size String(word))) (= lef (/ (- wid wl) 2.0))
(textout width: lef "" width: wl word width: (- wid (+ wl lef)) "")
else
(textout width: wid (get row m)))))
(lout ""))
)
),
_start: (λ
(load-table tabl txt fieldSep: "$" :emptyEls)
(for i in Seq(0 (num-cols tabl)) do (= n 0)
(tsd-query tabl
reduce: [i]
as: [[String()]]
using: (λ (set n (max (size (get @row 0)) n))))
(append colWidths n)
)
(textout :right "") (print)
(lout :left "") (print)
(lout "") (print true)
)
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #JavaScript | JavaScript | function ack(m, n) {
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #TSE_SAL | TSE SAL |
INTEGER PROC FNBlockChangeColumnAlignLeftB( INTEGER columnTotalI, INTEGER spaceTotalI, INTEGER buffer1I )
INTEGER B = FALSE
INTEGER downB = TRUE
INTEGER minI = 1
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
INTEGER L = 0
INTEGER buffer2I = 0
STRING s[255] = ""
INTEGER wordRightB = FALSE
STRING s1[255] = Query( WordSet )
IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block" ) B = FALSE RETURN( B ) ENDIF // return from the current procedure if no block is marked
Set( BREAK, ON )
PushPosition()
PushBlock()
Set( WordSet, ChrSet( "a-zA-Z0-9_,." ) )
PushPosition()
buffer2I = CreateTempBuffer()
PopPosition()
PushPosition()
PushBlock()
DO 100 TIMES
AddLine( "", buffer2I )
ENDDO
PopBlock()
PopPosition()
GotoBlockBegin()
I = minI - 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
ENDIF
J = Length( s )
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
//
IF ( CurrLineLen() == 0 )
BegLine()
InsertText( Format( Str( J ), " " ), _INSERT_ )
ELSE
K = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
IF ( J > K )
BegLine()
DelToEol()
BegLine()
InsertText( Str( J ), _INSERT_ )
ENDIF
ENDIF
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
downB = Down()
ENDWHILE
GotoBlockBegin()
I = minI - 1
L = 1
K = 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
B = FALSE
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
K = 1
L = L + 1
ENDIF
//
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
J = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
PopPosition()
PopBlock()
PushPosition()
PushBlock()
GotoBufferId( buffer1I )
GotoLine( L )
GotoColumn( K )
InsertText( s, _INSERT_ )
K = K + J + spaceTotalI
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
AddLine( "", buffer1I )
downB = Down()
ENDWHILE
OneWindow()
VWindow()
GotoWindow( 1 )
GotoBufferId( buffer2I )
GotoWindow( 2 )
GotoBufferId( buffer1I )
B = TRUE
Set( WordSet, s1 )
PopPosition()
PopBlock()
RETURN( B )
END
//
PROC Main()
STRING s1[255] = "12" // change this
STRING s2[255] = "2" // change this
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
IF ( NOT ( Ask( "block: change: column: align: left: columnTotalI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
IF ( NOT ( Ask( "block: change: column: align: left: spaceTotalI = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
Message( FNBlockChangeColumnAlignLeftB( Val( s1 ), Val( s2 ), bufferI ) ) // gives e.g. TRUE
GotoBufferId( bufferI )
END
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Joy | Joy | DEFINE ack == [ [ [pop null] popd succ ]
[ [null] pop pred 1 ack ]
[ [dup pred swap] dip pred ack ack ] ]
cond. |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
MODE DATA
$$ SET exampletext=*
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
$$ MODE TUSCRIPT
SET nix=SPLIT (exampletext,":$:",c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12)
LOOP l1=1,12
SET colum=CONCAT ("c",l1)
SET newcolum=CONCAT ("new",l1)
SET @newcolum="", length=MAX LENGTH (@colum), space=length+2
LOOP n,l2=@colum
SET newcell=CENTER (l2,space)
SET @newcolum=APPEND (@newcolum,"~",newcell)
ENDLOOP
SET @newcolum=SPLIT (@newcolum,":~:")
ENDLOOP
SET exampletext=JOIN(new1,"$",new2,new3,new4,new5,new6,new7,new8,new9,new10,new11,new12)
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #jq | jq | # input: [m,n]
def ack:
.[0] as $m | .[1] as $n
| if $m == 0 then $n + 1
elif $n == 0 then [$m-1, 1] | ack
else [$m-1, ([$m, $n-1 ] | ack)] | ack
end ; |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #TXR | TXR | @(collect)
@ (coll)@{item /[^$]+/}@(end)
@(end)
@; nc = number of columns
@; pi = padded items (data with row lengths equalized with empty strings)
@; cw = vector of max column widths
@; ce = center padding
@(bind nc @[apply max [mapcar length item]])
@(bind pi @(mapcar (op append @1 (repeat '("") (- nc (length @1)))) item))
@(bind cw @(vector-list
(mapcar (op apply max [mapcar length @1])
;; matrix transpose trick cols become rows:
[apply mapcar [cons list pi]])))
@(bind ns "")
@(output)
@ (repeat)
@ (rep :counter i)@{pi @[cw i]} @(end)
@ (end)
@ (repeat)
@ (rep :counter i)@{pi @(- [cw i])} @(end)
@ (end)
@ (repeat)
@ (rep :counter i)@\
@{ns @(trunc (- [cw i] (length pi)) 2)}@\
@{pi @(- [cw i] (trunc (- [cw i] (length pi)) 2))} @(end)
@ (end)
@(end) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Jsish | Jsish | /* Ackermann function, in Jsish */
function ack(m, n) {
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
}
if (Interp.conf('unitTest')) {
Interp.conf({maxDepth:4096});
; ack(1,3);
; ack(2,3);
; ack(3,3);
; ack(1,5);
; ack(2,5);
; ack(3,5);
}
/*
=!EXPECTSTART!=
ack(1,3) ==> 5
ack(2,3) ==> 9
ack(3,3) ==> 61
ack(1,5) ==> 7
ack(2,5) ==> 13
ack(3,5) ==> 253
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #UNIX_Shell | UNIX Shell |
cat <<EOF_OUTER > just-nocenter.sh
#!/bin/sh
td() {
cat <<'EOF'
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
EOF
}
rows=$( td | wc -l )
# get the number of fields
fields=$(td | rs -c'$' -g1 -h | awk '{print $2}')
# get the max of the value widths
cwidth=$(td | rs -c'$' -g1 -w1 2>/dev/null | awk 'BEGIN{w=0}{if(length>w){w=length}}END{print w}')
# compute the minimum line width for the columns
lwidth=$(( (1 + cwidth) * fields ))
# left adjusted columns
td | rs -c'$' -g1 -zn -w$lwidth
echo ""
# right adjusted columns
td | rs -c'$' -g1 -znj -w$lwidth
echo ""
exit
EOF_OUTER
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Julia | Julia | function ack(m,n)
if m == 0
return n + 1
elseif n == 0
return ack(m-1,1)
else
return ack(m-1,ack(m,n-1))
end
end |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Ursala | Ursala | #import std
text =
-[Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.]-
pad = sep`$*; @FS ~&rSSSK7+ (zipp` ^*D\~& leql$^)*rSSK7+ zipp0^*D/leql$^ ~&
just_left = mat` *+ pad
just_right = mat` *+ pad; ==` ~-rlT**
just_center = mat` *+ pad; ==` ~-rK30PlrK31PTT**
#show+
main = mat0 <.just_left,just_center,just_right> text |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #K | K | ack:{:[0=x;y+1;0=y;_f[x-1;1];_f[x-1;_f[x;y-1]]]}
ack[2;2] |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #VBA | VBA |
Public Sub TestSplit(Optional align As String = "left", Optional spacing As Integer = 1)
Dim word() As String
Dim colwidth() As Integer
Dim ncols As Integer
Dim lines(6) As String
Dim nlines As Integer
'check arguments
If Not (align = "left" Or align = "right" Or align = "center") Then
MsgBox "TestSplit: wrong argument 'align': " & align
Exit Sub
End If
If spacing < 0 Then
MsgBox "TestSplit: wrong argument: 'spacing' cannot be negative."
Exit Sub
End If
' Sample Input (should be from a file)
nlines = 6
lines(1) = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
lines(2) = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
lines(3) = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
lines(4) = "column$are$separated$by$at$least$one$space."
lines(5) = "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
lines(6) = "justified,$right$justified,$or$center$justified$within$its$column."
'first pass: count columns and column widths
'the words are not kept in memory
ncols = -1
For l = 1 To nlines
word = Split(RTrim(lines(l)), "$")
If UBound(word) > ncols Then
ncols = UBound(word)
ReDim Preserve colwidth(ncols)
End If
For i = 0 To UBound(word)
If Len(word(i)) > colwidth(i) Then colwidth(i) = Len(word(i))
Next i
Next l
'discard possibly empty columns at the right
'(this assumes there is at least one non-empty column)
While colwidth(ncols) = 0
ncols = ncols - 1
Wend
'second pass: print in columns
For l = 1 To nlines
word = Split(RTrim(lines(l)), "$")
For i = 0 To UBound(word)
a = word(i)
w = colwidth(i)
If align = "left" Then
Debug.Print a + String$(w - Len(a), " ");
ElseIf align = "right" Then
Debug.Print String$(w - Len(a), " ") + a;
ElseIf align = "center" Then
d = Int((w - Len(a)) / 2)
Debug.Print String$(d, " ") + a + String$(w - (d + Len(a)), " ");
End If
If i < ncols Then Debug.Print Spc(spacing);
Next i
Debug.Print
Next l
End Sub
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Kdf9_Usercode | Kdf9 Usercode | V6; W0;
YS26000;
RESTART; J999; J999;
PROGRAM; (main program);
V1 = B1212121212121212; (radix 10 for FRB);
V2 = B2020202020202020; (high bits for decimal digits);
V3 = B0741062107230637; ("A[3," in Flexowriter code);
V4 = B0727062200250007; ("7] = " in Flexowriter code);
V5 = B7777777777777777;
ZERO; NOT; =M1; (Q1 := 0/0/-1);
SETAYS0; =M2; I2=2; (Q2 := 0/2/AYS0: M2 is the stack pointer);
SET 3; =RC7; (Q7 := 3/1/0: C7 = m);
SET 7; =RC8; (Q8 := 7/1/0: C8 = n);
JSP1; (call Ackermann function);
V1; REV; FRB; (convert result to base 10);
V2; OR; (convert decimal digits to characters);
V5; REV;
SHLD+24; =V5; ERASE; (eliminate leading zeros);
SETAV5; =RM9;
SETAV3; =I9;
POAQ9; (write result to Flexowriter);
999; ZERO; OUT; (terminate run);
P1; (To compute A[m, n]);
99;
J1C7NZ; (to 1 if m ± 0);
I8; =+C8; (n := n + 1);
C8; (result to NEST);
EXIT 1; (return);
*1;
J2C8NZ; (to 2 if n ± 0);
I8; =C8; (n := 1);
DC7; (m := m - 1);
J99; (tail recursion for A[m-1, 1]);
*2;
LINK; =M0M2; (push return address);
C7; =M0M2QN; (push m);
DC8; (n := n - 1);
JSP1; (full recursion for A[m, n-1]);
=C8; (n := A[m, n-1]);
M1M2; =C7; (m := top of stack);
DC7; (m := m - 1);
M-I2; (pop stack);
M0M2; =LINK; (return address := top of stack);
J99; (tail recursion for A[m-1, A[m, n-1]]);
FINISH; |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #VBScript | VBScript | ' Align columns - RC - VBScript
Const nr=16, nc=16
ReDim d(nc),t(nr), wor(nr,nc)
i=i+1: t(i) = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
i=i+1: t(i) = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
i=i+1: t(i) = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
i=i+1: t(i) = "column$are$separated$by$at$least$one$space."
i=i+1: t(i) = "Further,$allow$for$each$word$in$a$column$To$be$either$left$"
i=i+1: t(i) = "justified,$right$justified,$or$center$justified$within$its$column."
For r=1 to nr
If t(r)="" Then Exit For
w=xRTrim(t(r),"$")
m=Split(w,"$")
For c=1 To UBound(m)+1
wor(r,c)=m(c-1)
If Len(wor(r,c))>d(c) Then d(c)=Len(wor(r,c))
Next 'c
If c>cols Then cols=c
Next 'r
rows=r-1
tt=Array("Left","Right","Center")
For n=1 To 3
Wscript.Echo
Wscript.Echo "*****" & tt(n-1) & "*****"
For r=1 To rows
w=""
For c=1 To cols
x=wor(r,c): s=Space(d(c))
Select Case n
Case 1: w=w &" "& Left (x & s,d(c))
Case 2: w=w &" "& Right (s & x,d(c))
Case 3: w=w &" "& xCentre(x,d(c)," ")
End Select 'n
Next 'c
Wscript.Echo Mid(w,2)
Next 'r
Next 'n
Function xCentre(c, n, Pad)
Dim j
If n > Len(c) Then
j = (n - Len(c)) \ 2
If (n - Len(c)) Mod 2 <> 0 Then j = j + 1
xCentre = Mid(String(j, Pad) & c & String(j, Pad), 1, n)
Else
xCentre = c
End If
End Function 'xCentre
Function xRTrim(c, Pad)
Dim i2, l, cc
cc = "": l = Len(c)
If l > 0 Then
i2 = l
Do While (Mid(c, i2, 1) = Pad And i2 > 1)
i2 = i2 - 1
Loop
If i2 = 1 And Mid(c, i2, 1) = Pad Then i2 = 0
If i2 > 0 Then cc = Mid(c, 1, i2)
End If
xRTrim = cc
End Function 'xRTrim
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Klingphix | Klingphix | :ack
%n !n %m !m
$m 0 ==
( [$n 1 +]
[$n 0 ==
( [$m 1 - 1 ack]
[$m 1 - $m $n 1 - ack ack]
) if
]
) if
;
3 6 ack print nl
msec print
" " input |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Vedit_macro_language | Vedit macro language | RS(10, "$") // Field separator
#11 = 1 // Align: 1 = left, 2 = center, 3 = right
// Reset column widths. Max 50 columns
for (#1=40; #1<90; #1++) { #@1 = 0 }
// Find max width of each column
BOF
Repeat(ALL) {
for (#1=40; #1<90; #1++) {
Match(@10, ADVANCE) // skip field separator if any
#2 = Cur_Pos
Search("|{|@(10),|N}", NOERR) // field separator or end of line
#3 = Cur_Pos - #2 // width of text
if (#3 > #@1) { #@1 = #3 }
if (At_EOL) { Break }
}
Line(1, ERRBREAK)
}
// Convert lines
BOF
Repeat(ALL) {
for (#1=40; #1<90; #1++) {
#2 = Cur_Pos
Search("|{|@(10),|N}", NOERR)
if (At_EOL==0) { Del_Char(Chars_Matched) }
#3 = #@1 - Cur_Pos + #2 // number of spaces to insert
#4 = 0
if (#11 == 2) { #4 = #3/2; #3 -= #4 } // Center
if (#11 == 3) { #4 = #3; #3 = 0 } // Right justify
Set_Marker(1, Cur_Pos)
Goto_Pos(#2)
Ins_Char(' ', COUNT, #4) // add spaces before the word
Goto_Pos(Marker(1))
Ins_Char(' ', COUNT, #3+1) // add spaces after the word
if (At_EOL) { Break }
}
Line(1, ERRBREAK)
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Klong | Klong |
ack::{:[0=x;y+1:|0=y;.f(x-1;1);.f(x-1;.f(x;y-1))]}
ack(2;2) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Visual_Basic | Visual Basic | Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1)
Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)
For j = 0 To UBound(W)
W(j) = Split(Lines(j), Sep)
If UBound(W(j)) > UBound(C) Then ReDim Preserve C(UBound(W(j)))
For i = 0 To UBound(W(j)): If Len(W(j)(i)) > C(i) Then C(i) = Len(W(j)(i))
Next i, j
For j = 0 To UBound(W): For i = 0 To UBound(W(j))
D = C(i) - Len(W(j)(i))
L = Choose(Align + 1, 0, D, D \ 2)
R = Choose(Align + 1, D, 0, D - L) + Sp
Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
Next i, j
End Sub |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Kotlin | Kotlin |
tailrec fun A(m: Long, n: Long): Long {
require(m >= 0L) { "m must not be negative" }
require(n >= 0L) { "n must not be negative" }
if (m == 0L) {
return n + 1L
}
if (n == 0L) {
return A(m - 1L, 1L)
}
return A(m - 1L, A(m, n - 1L))
}
inline fun<T> tryOrNull(block: () -> T): T? = try { block() } catch (e: Throwable) { null }
const val N = 10L
const val M = 4L
fun main() {
(0..M)
.map { it to 0..N }
.map { (m, Ns) -> (m to Ns) to Ns.map { n -> tryOrNull { A(m, n) } } }
.map { (input, output) -> "A(${input.first}, ${input.second})" to output.map { it?.toString() ?: "?" } }
.map { (input, output) -> "$input = $output" }
.forEach(::println)
}
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Private Delegate Function Justification(s As String, width As Integer) As String
Private Function AlignColumns(lines As String(), justification As Justification) As String()
Const Separator As Char = "$"c
' build input container table and calculate columns count
Dim containerTbl As String()() = New String(lines.Length - 1)() {}
Dim columns As Integer = 0
For i As Integer = 0 To lines.Length - 1
Dim row As String() = lines(i).TrimEnd(Separator).Split(Separator)
If columns < row.Length Then
columns = row.Length
End If
containerTbl(i) = row
Next
' create formatted container table
Dim formattedTable As String()() = New String(containerTbl.Length - 1)() {}
For i As Integer = 0 To formattedTable.Length - 1
formattedTable(i) = New String(columns - 1) {}
Next
For j As Integer = 0 To columns - 1
' get max column width
Dim columnWidth As Integer = 0
For i As Integer = 0 To containerTbl.Length - 1
If j < containerTbl(i).Length AndAlso columnWidth < containerTbl(i)(j).Length Then
columnWidth = containerTbl(i)(j).Length
End If
Next
' justify column cells
For i As Integer = 0 To formattedTable.Length - 1
If j < containerTbl(i).Length Then
formattedTable(i)(j) = justification(containerTbl(i)(j), columnWidth)
Else
formattedTable(i)(j) = New [String](" "c, columnWidth)
End If
Next
Next
' create result
Dim result As String() = New String(formattedTable.Length - 1) {}
For i As Integer = 0 To result.Length - 1
result(i) = [String].Join(" ", formattedTable(i))
Next
Return result
End Function
Private Function JustifyLeft(s As String, width As Integer) As String
Return s.PadRight(width)
End Function
Private Function JustifyRight(s As String, width As Integer) As String
Return s.PadLeft(width)
End Function
Private Function JustifyCenter(s As String, width As Integer) As String
Return s.PadLeft((width + s.Length) / 2).PadRight(width)
End Function
Sub Main()
Dim input As String() = {"Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column."}
For Each line As String In AlignColumns(input, AddressOf JustifyLeft)
Console.WriteLine(line)
Next
Console.ReadLine()
End Sub
End Module |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Lambdatalk | Lambdatalk |
{def ack
{lambda {:m :n}
{if {= :m 0}
then {+ :n 1}
else {if {= :n 0}
then {ack {- :m 1} 1}
else {ack {- :m 1} {ack :m {- :n 1}}}}}}}
-> ack
{S.map {ack 0} {S.serie 0 300000}} // 2090ms
{S.map {ack 1} {S.serie 0 500}} // 2038ms
{S.map {ack 2} {S.serie 0 70}} // 2100ms
{S.map {ack 3} {S.serie 0 6}} // 1800ms
{ack 2 700} // 8900ms
-> 1403
{ack 3 7} // 6000ms
-> 1021
{ack 4 1} // too much
-> ???
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Vlang | Vlang |
const text = "Given\$a\$text\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
column\$are\$separated\$by\$at\$least\$one\$space.
Further,\$allow\$for\$each\$word\$in\$a\$column\$to\$be\$either\$left\$
justified,\$right\$justified,\$or\$center\$justified\$within\$its\$column."
struct Formatter {
mut:
text [][]string
width []int
}
fn new_formatter(text string) Formatter {
mut f := Formatter{}
for line in text.split_into_lines() {
mut words := line.split("\$")
for words[words.len-1] == "" {
words = words[..words.len-1]
}
f.text << words
for i, word in words {
if i == f.width.len {
f.width << word.len
} else if word.len > f.width[i] {
f.width[i] = word.len
}
}
}
return f
}
enum Justify {
left = 0
middle
right
}
fn (f Formatter) print(j Justify) {
for line in f.text {
for i, word in line {
match j {
.left {
print('$word${' '.repeat(f.width[i]-word.len)} ')
}
.middle {
mut extra := 0
if (f.width[i]%2==1 && word.len%2==0) || (f.width[i]%2==0 && word.len%2==1) {
extra++
}
print('${' '.repeat((f.width[i]-word.len)/2)}$word${' '.repeat((f.width[i]-word.len)/2+extra)} ')
}
.right {
print('${' '.repeat(f.width[i]-word.len)}$word ')
}
}
}
println("")
}
println("")
}
fn main() {
f := new_formatter(text)
f.print(Justify.left)
f.print(Justify.middle)
f.print(Justify.right)
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Lasso | Lasso | #!/usr/bin/lasso9
define ackermann(m::integer, n::integer) => {
if(#m == 0) => {
return ++#n
else(#n == 0)
return ackermann(--#m, 1)
else
return ackermann(#m-1, ackermann(#m, --#n))
}
}
with x in generateSeries(1,3),
y in generateSeries(0,8,2)
do stdoutnl(#x+', '#y+': ' + ackermann(#x, #y))
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Wren | Wren | import "io" for File
import "/fmt" for Fmt
var LEFT = 0
var RIGHT = 1
var CENTER = 2
var justStrs = ["LEFT", "RIGHT", "CENTER"]
// Gets a list of lines in the file with each line split into fields.
var getLines = Fn.new { |fileName|
var contents = File.read(fileName)
var lines = contents.split("\n") // use "\r\n" on Windows
for (i in 0...lines.count) {
lines[i] = lines[i].trim().trimEnd("$")
if (lines[i] == "") { // get rid of final blank line, if any
lines = lines[0..-2]
break
}
lines[i] = lines[i].split("$")
}
return lines
}
var alignCols = Fn.new { |lines, just|
// find maximum number of columns
var nCols = lines.reduce(0) { |acc, line| (line.count > acc) ? line.count : acc }
// find maximum width for each column
var maxWids = List.filled(nCols, 0)
for (line in lines) {
for (i in 0...line.count) {
var width = line[i].count
if (width > maxWids[i]) maxWids[i] = width
}
}
System.print("With %(justStrs[just]) justification:")
for (line in lines) {
for (i in 0...line.count) {
var width = maxWids[i] + 1
if (just == LEFT) {
System.write(Fmt.s(-width, line[i]))
} else if (just == RIGHT) {
System.write(Fmt.s(width, line[i]))
} else if (just == CENTER) {
System.write(Fmt.m(width, line[i]))
}
}
System.print()
}
System.print()
}
var fileName = "align_cols.txt"
var lines = getLines.call(fileName)
for (i in 0..2) alignCols.call(lines, i) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #LFE | LFE | (defun ackermann
((0 n) (+ n 1))
((m 0) (ackermann (- m 1) 1))
((m n) (ackermann (- m 1) (ackermann m (- n 1))))) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #Yabasic | Yabasic | theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
theString$ = theString$ + "are$delineated$by$a$single$'dollar'$character,$write$a$program"
theString$ = theString$ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
theString$ = theString$ + "column$are$separated$by$at$least$one$space."
theString$ = theString$ + "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
theString$ = theString$ + "justified,$right$justified,$or$center$justified$within$its$column."
x = shoTable(theString$, "left", 6)
x = shoTable(theString$, "right", 6)
x = shoTable(theString$, "center", 6)
end
sub word$(sr$, wn, delim$)
local i, j, n, sd, sl, sl2
local s$, res$, d$
d$ = delim$
j = wn
if j = 0 j = j+1
res$ = "" : s$ = sr$
if d$ = "" d$ = " "
sd = len(d$) : sl = len(s$)
do
n = instr(s$,d$)
j = j - 1
if j = 0 then
if n = 0 then res$ = s$ else res$ = mid$(s$, 1, n-1) : fi
return res$
fi
if n = 0 return res$
if n = sl-sd then res$ = "" : return res$ : fi
sl2 = sl-n
s$ = mid$(s$, n+1, sl2)
sl = sl2
loop
return res$
end sub
sub shoTable(theString$, align$, across)
local i, a$, b$
print "------------ align:", align$, " -- across:", across, " ------------"
dim siz(across)
b$ = " "
while word$(theString$, i+1, "$") <> ""
siz(mod(i, across)) = max(siz(mod(i, across)), len(word$(theString$, i+1, "$")))
i = i+1
wend
for i = 0 to across - 1
siz(i) = siz(i)+1
if siz(i) and 1 siz(i) = siz(i)+1
next i
i = 0
a$ = word$(theString$, i+1, "$")
while a$ <> ""
s = siz(mod(i, across)) - len(a$)
if align$ = "right" a$ = left$(b$, s) + a$
if align$ = "left" a$ = a$ + left$(b$, s)
if align$ = "center" a$ = left$(b$, int(s / 2)) + a$ + left$(b$, int(s / 2) + (s and 1))
print "|", a$;
i = i + 1
if mod(i, across) = 0 print "|"
a$ = word$(theString$, i+1, "$")
wend
print
end sub |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Liberty_BASIC | Liberty BASIC | Print Ackermann(1, 2)
Function Ackermann(m, n)
Select Case
Case (m < 0) Or (n < 0)
Exit Function
Case (m = 0)
Ackermann = (n + 1)
Case (m > 0) And (n = 0)
Ackermann = Ackermann((m - 1), 1)
Case (m > 0) And (n > 0)
Ackermann = Ackermann((m - 1), Ackermann(m, (n - 1)))
End Select
End Function |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #zkl | zkl | fcn format(text,how){
words:=text.split("$").apply("split").flatten();
max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0);
wordsPerCol:=80/(max+1);
fmt:=(switch(how){
case(-1){ "%%-%ds ".fmt(max).fmt }
case(0) { fcn(max,w){
a:=(max-w.len())/2; b:=max-w.len() - a; String(" "*a,w," "*b);
}.fp(max)
}
case(1){ "%%%ds ".fmt(max).fmt }
});
w:=words.walker(); d:=Data(0,Int);
do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd);
d.text;
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #LiveCode | LiveCode | function ackermann m,n
switch
Case m = 0
return n + 1
Case (m > 0 And n = 0)
return ackermann((m - 1), 1)
Case (m > 0 And n > 0)
return ackermann((m - 1), ackermann(m, (n - 1)))
end switch
end ackermann |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 5 BORDER 2
10 DATA 6
20 DATA "The$problem$of$Speccy$"
30 DATA "is$the$screen.$"
40 DATA "Need$adapt$text$sample$"
50 DATA "for$show$the$result$"
60 DATA "without$problem$,right?$"
70 DATA "But$see$the$code.$"
80 REM First find the maximum length of a 'word'
90 LET max=0: LET d$="$"
100 READ nlines
110 FOR l=1 TO nlines
120 READ t$
130 GO SUB 1000
150 NEXT l
155 LET s$=" "( TO max)
160 REM Now display the aligned text:
170 LET m$="l": GO SUB 2000: PRINT
180 LET m$="r": GO SUB 2000: PRINT
190 LET m$="c": GO SUB 2000
200 STOP
1000 REM Maximum length of a word
1010 LET lt=LEN t$: LET p=1: LET lw=0
1020 FOR i=1 TO lt
1030 IF t$(i)=d$ THEN LET lw=i-p: LET p=i: IF lw>max THEN LET max=lw
1040 NEXT i
1050 RETURN
2000 REM Show aligned text
2010 RESTORE 20
2020 FOR l=1 TO nlines
2030 READ t$
2040 GO SUB 3000
2050 NEXT l
2060 RETURN
3000 REM Show words
3010 LET lt=LEN t$: LET p=1: LET lw=0
3020 FOR i=1 TO lt
3030 IF t$(i)<>d$ THEN GO TO 3090
3035 LET lw=i-p
3040 LET p$=t$(p TO i-1): LET p=i+1: LET z$=s$
3050 IF m$="l" THEN LET z$( TO lw)=p$
3060 IF m$="r" THEN LET z$(max-lw+1 TO )=p$
3070 IF m$="c" THEN LET z$((max/2)-(lw/2) TO )=p$
3080 PRINT z$;
3090 NEXT i
3095 PRINT
3100 RETURN |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Logo | Logo | to ack :i :j
if :i = 0 [output :j+1]
if :j = 0 [output ack :i-1 1]
output ack :i-1 ack :i :j-1
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Logtalk | Logtalk | ack(0, N, V) :-
!,
V is N + 1.
ack(M, 0, V) :-
!,
M2 is M - 1,
ack(M2, 1, V).
ack(M, N, V) :-
M2 is M - 1,
N2 is N - 1,
ack(M, N2, V2),
ack(M2, V2, V). |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I ackermann YR m AN YR n
NOT m, O RLY?
YA RLY, FOUND YR SUM OF n AN 1
OIC
NOT n, O RLY?
YA RLY, FOUND YR I IZ ackermann YR DIFF OF m AN 1 AN YR 1 MKAY
OIC
FOUND YR I IZ ackermann YR DIFF OF m AN 1 AN YR...
I IZ ackermann YR m AN YR DIFF OF n AN 1 MKAY MKAY
IF U SAY SO
IM IN YR outer UPPIN YR m TIL BOTH SAEM m AN 5
IM IN YR inner UPPIN YR n TIL BOTH SAEM n AN DIFF OF 6 AN m
VISIBLE "A(" m ", " n ") = " I IZ ackermann YR m AN YR n MKAY
IM OUTTA YR inner
IM OUTTA YR outer
KTHXBYE |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Lua | Lua | function ack(M,N)
if M == 0 then return N + 1 end
if N == 0 then return ack(M-1,1) end
return ack(M-1,ack(M, N-1))
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Lucid | Lucid | ack(m,n)
where
ack(m,n) = if m eq 0 then n+1
else if n eq 0 then ack(m-1,1)
else ack(m-1, ack(m, n-1)) fi
fi;
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Luck | Luck | function ackermann(m: int, n: int): int = (
if m==0 then n+1
else if n==0 then ackermann(m-1,1)
else ackermann(m-1,ackermann(m,n-1))
) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Def ackermann(m,n) =If(m=0-> n+1, If(n=0-> ackermann(m-1,1), ackermann(m-1,ackermann(m,n-1))))
For m = 0 to 3 {For n = 0 to 4 {Print m;" ";n;" ";ackermann(m,n)}}
}
Checkit
Module Checkit {
Module Inner (ack) {
For m = 0 to 3 {For n = 0 to 4 {Print m;" ";n;" ";ack(m,n)}}
}
Inner lambda (m,n) ->If(m=0-> n+1, If(n=0-> lambda(m-1,1),lambda(m-1,lambda(m,n-1))))
}
Checkit
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #M4 | M4 | define(`ack',`ifelse($1,0,`incr($2)',`ifelse($2,0,`ack(decr($1),1)',`ack(decr($1),ack($1,decr($2)))')')')dnl
ack(3,3) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION LIST(3000)
SET LIST TO LIST
INTERNAL FUNCTION(DUMMY)
ENTRY TO ACKH.
LOOP WHENEVER M.E.0
FUNCTION RETURN N+1
OR WHENEVER N.E.0
M=M-1
N=1
TRANSFER TO LOOP
OTHERWISE
SAVE RETURN
SAVE DATA M
N=N-1
N=ACKH.(0)
RESTORE DATA M
RESTORE RETURN
M=M-1
TRANSFER TO LOOP
END OF CONDITIONAL
ERROR RETURN
END OF FUNCTION
INTERNAL FUNCTION(MM,NN)
ENTRY TO ACK.
M=MM
N=NN
FUNCTION RETURN ACKH.(0)
END OF FUNCTION
THROUGH SHOW, FOR I=0, 1, I.G.3
THROUGH SHOW, FOR J=0, 1, J.G.8
SHOW PRINT FORMAT ACKF,I,J,ACK.(I,J)
VECTOR VALUES ACKF = $4HACK(,I1,1H,,I1,4H) = ,I4*$
END OF PROGRAM
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Maple | Maple |
Ackermann := proc( m :: nonnegint, n :: nonnegint )
option remember; # optional automatic memoization
if m = 0 then
n + 1
elif n = 0 then
thisproc( m - 1, 1 )
else
thisproc( m - 1, thisproc( m, n - 1 ) )
end if
end proc:
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Mathcad | Mathcad | A(m,n):=if(m=0,n+1,if(n=0,A(m-1,1),A(m-1,A(m,n-1)))) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | $RecursionLimit=Infinity
Ackermann1[m_,n_]:=
If[m==0,n+1,
If[ n==0,Ackermann1[m-1,1],
Ackermann1[m-1,Ackermann1[m,n-1]]
]
]
Ackermann2[0,n_]:=n+1;
Ackermann2[m_,0]:=Ackermann1[m-1,1];
Ackermann2[m_,n_]:=Ackermann1[m-1,Ackermann1[m,n-1]] |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #MATLAB | MATLAB | function A = ackermannFunction(m,n)
if m == 0
A = n+1;
elseif (m > 0) && (n == 0)
A = ackermannFunction(m-1,1);
else
A = ackermannFunction( m-1,ackermannFunction(m,n-1) );
end
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Maxima | Maxima | ackermann(m, n) := if integerp(m) and integerp(n) then ackermann[m, n] else 'ackermann(m, n)$
ackermann[m, n] := if m = 0 then n + 1
elseif m = 1 then 2 + (n + 3) - 3
elseif m = 2 then 2 * (n + 3) - 3
elseif m = 3 then 2^(n + 3) - 3
elseif n = 0 then ackermann[m - 1, 1]
else ackermann[m - 1, ackermann[m, n - 1]]$
tetration(a, n) := if integerp(n) then block([b: a], for i from 2 thru n do b: a^b, b) else 'tetration(a, n)$
/* this should evaluate to zero */
ackermann(4, n) - (tetration(2, n + 3) - 3);
subst(n = 2, %);
ev(%, nouns); |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #MAXScript | MAXScript | fn ackermann m n =
(
if m == 0 then
(
return n + 1
)
else if n == 0 then
(
ackermann (m-1) 1
)
else
(
ackermann (m-1) (ackermann m (n-1))
)
) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Mercury | Mercury | :- func ack(integer, integer) = integer.
ack(M, N) = R :- ack(M, N, R).
:- pred ack(integer::in, integer::in, integer::out) is det.
ack(M, N, R) :-
( ( M < integer(0)
; N < integer(0) ) -> throw(bounds_error)
; M = integer(0) -> R = N + integer(1)
; N = integer(0) -> ack(M - integer(1), integer(1), R)
; ack(M - integer(1), ack(M, N - integer(1)), R) ). |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #min | min | (
:n :m
(
((m 0 ==) (n 1 +))
((n 0 ==) (m 1 - 1 ackermann))
((true) (m 1 - m n 1 - ackermann ackermann))
) case
) :ackermann |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #MiniScript | MiniScript | ackermann = function(m, n)
if m == 0 then return n+1
if n == 0 then return ackermann(m - 1, 1)
return ackermann(m - 1, ackermann(m, n - 1))
end function
for m in range(0, 3)
for n in range(0, 4)
print "(" + m + ", " + n + "): " + ackermann(m, n)
end for
end for |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П1 <-> П0 ПП 06 С/П ИП0 x=0 13 ИП1
1 + В/О ИП1 x=0 24 ИП0 1 П1 -
П0 ПП 06 В/О ИП0 П2 ИП1 1 - П1
ПП 06 П1 ИП2 1 - П0 ПП 06 В/О |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" Ackermann function
"" Will overflow when it reaches implementation-defined signed integer limit
MCSKIP MT,<>
MCINS %.
MCDEF ACK WITHS ( , )
AS <MCSET T1=%A1.
MCSET T2=%A2.
MCGO L1 UNLESS T1 EN 0
%%T2.+1.MCGO L0
%L1.MCGO L2 UNLESS T2 EN 0
ACK(%%T1.-1.,1)MCGO L0
%L2.ACK(%%T1.-1.,ACK(%T1.,%%T2.-1.))>
"" Macro ACK now defined, so try it out
a(0,0) => ACK(0,0)
a(0,1) => ACK(0,1)
a(0,2) => ACK(0,2)
a(0,3) => ACK(0,3)
a(0,4) => ACK(0,4)
a(0,5) => ACK(0,5)
a(1,0) => ACK(1,0)
a(1,1) => ACK(1,1)
a(1,2) => ACK(1,2)
a(1,3) => ACK(1,3)
a(1,4) => ACK(1,4)
a(2,0) => ACK(2,0)
a(2,1) => ACK(2,1)
a(2,2) => ACK(2,2)
a(2,3) => ACK(2,3)
a(3,0) => ACK(3,0)
a(3,1) => ACK(3,1)
a(3,2) => ACK(3,2)
a(4,0) => ACK(4,0) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #mLite | mLite | fun ackermann( 0, n ) = n + 1
| ( m, 0 ) = ackermann( m - 1, 1 )
| ( m, n ) = ackermann( m - 1, ackermann(m, n - 1) ) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Modula-2 | Modula-2 | MODULE ackerman;
IMPORT ASCII, NumConv, InOut;
VAR m, n : LONGCARD;
string : ARRAY [0..19] OF CHAR;
OK : BOOLEAN;
PROCEDURE Ackerman (x, y : LONGCARD) : LONGCARD;
BEGIN
IF x = 0 THEN RETURN y + 1
ELSIF y = 0 THEN RETURN Ackerman (x - 1 , 1)
ELSE
RETURN Ackerman (x - 1 , Ackerman (x , y - 1))
END
END Ackerman;
BEGIN
FOR m := 0 TO 3 DO
FOR n := 0 TO 6 DO
NumConv.Num2Str (Ackerman (m, n), 10, string, OK);
IF OK THEN
InOut.WriteString (string)
ELSE
InOut.WriteString ("* Error in number * ")
END;
InOut.Write (ASCII.HT)
END;
InOut.WriteLn
END;
InOut.WriteLn
END ackerman. |
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #11l | 11l | V command_table_text =
|‘add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1’
V user_words = ‘riG rePEAT copies put mo rest types fup. 6 poweRin’
F find_abbreviations_length(command_table_text)
‘ find the minimal abbreviation length for each word.
a word that does not have minimum abbreviation length specified
gets it's full lengths as the minimum.
’
[String = Int] command_table
V input_list = command_table_text.split((‘ ’, "\n"), group_delimiters' 1B)
V i = 0
V word = ‘’
L i < input_list.len | word != ‘’
I word == ‘’
word = input_list[i++]
V abbr_len = I i < input_list.len {input_list[i++]} E String(word.len)
X.try
command_table[word] = Int(abbr_len)
word = ‘’
X.catch ValueError
command_table[word] = word.len
word = abbr_len
R command_table
F find_abbreviations(command_table)
‘ for each command insert all possible abbreviations’
[String = String] abbreviations
L(command, min_abbr_len) command_table
L(l) min_abbr_len .. command.len
V abbr = command[0 .< l].lowercase()
abbreviations[abbr] = command.uppercase()
R abbreviations
F parse_user_string(user_string, abbreviations)
V user_words = user_string.split(‘ ’, group_delimiters' 1B).map(word -> word.lowercase())
V commands = user_words.map(user_word -> @abbreviations.get(user_word, ‘*error*’))
R commands.join(‘ ’)
V command_table = find_abbreviations_length(command_table_text)
V abbreviations_table = find_abbreviations(command_table)
V full_words = parse_user_string(user_words, abbreviations_table)
print(‘user words: ’user_words)
print(‘full words: ’full_words) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Modula-3 | Modula-3 | MODULE Ack EXPORTS Main;
FROM IO IMPORT Put;
FROM Fmt IMPORT Int;
PROCEDURE Ackermann(m, n: CARDINAL): CARDINAL =
BEGIN
IF m = 0 THEN
RETURN n + 1;
ELSIF n = 0 THEN
RETURN Ackermann(m - 1, 1);
ELSE
RETURN Ackermann(m - 1, Ackermann(m, n - 1));
END;
END Ackermann;
BEGIN
FOR m := 0 TO 3 DO
FOR n := 0 TO 6 DO
Put(Int(Ackermann(m, n)) & " ");
END;
Put("\n");
END;
END Ack. |
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program abbrSimple64.s */
/* store list of command in a file commandSimple.txt */
/* and run the program abbrSimple64 commandSimple.txt */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 1000
.equ NBMAXIELEMENTS, 100
/*******************************************/
/* Structures */
/********************************************/
/* command structure */
.struct 0
command_name_address: // name
.struct command_name_address + 8
command_min: // minimum letters
.struct command_min + 8
command_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre: .asciz "Nom du fichier : "
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Error detected.\n"
szMessErrBuffer: .asciz "buffer size too less !!"
szMessCtrlCom: .asciz "Command : @ minimum : @ \n"
szMessErrorAbr: .asciz "*error*"
szMessInput: .asciz "Enter command (or <ctrl-c> to stop) : "
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
sZoneConv: .skip 24
qAdrFicName: .skip 8
iTabAdrCmd: .skip command_end * NBMAXIELEMENTS
sBufferCmd: .skip BUFFERSIZE
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // INFO: main
mov x0,sp // stack address for load parameter
bl traitFic // read file and store value in array
cmp x0,#-1
beq 100f // error ?
ldr x0,qAdriTabAdrCmd
bl controlLoad
1:
ldr x0,qAdrszMessInput // display input message
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8, #READ // request to read datas
svc 0 // call system
sub x0,x0,#1
mov x2,#0
strb w2,[x1,x0] // replace character 0xA by zéro final
cbnz x0,2f // null string ?
mov x0,x1
b 3f
2:
ldr x0,qAdrsBuffer
ldr x1,qAdriTabAdrCmd
bl controlCommand // control text command
3:
mov x2,x0 // display result
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
b 1b // loop
99:
ldr x0,qAdrszMessErrBuffer
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessErrBuffer: .quad szMessErrBuffer
qAdrsZoneConv: .quad sZoneConv
qAdrszMessInput: .quad szMessInput
/******************************************************************/
/* control abbrevation command */
/******************************************************************/
/* x0 contains string input command */
/* x1 contains address table string command */
controlCommand: // INFO: controlCommand
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x8,x0
mov x9,x1
mov x10,#command_end // length item
bl computeLength // length input command
mov x4,x0 // save length input
mov x2,#0 // indice
mov x3,#0 // find counter
1:
mov x0,x8
madd x6,x2,x10,x9 // compute address
ldr x1,[x6,#command_name_address] // load a item
cbz x1,5f // end ?
bl comparStringSpe //
cbz x0,4f // no found other search
ldr x5,[x6,#command_min]
cmp x5,#0 // minimum = zéro ?
ble 2f
cmp x4,x5 // input < command capital letters
blt 4f // no correct
add x3,x3,#1 // else increment counter
mov x7,x1 // and save address command
b 4f
2:
mov x0,x1
bl computeLength // length table command
cmp x0,x4 // length input commant <> lenght table command
bne 4f // no correct
add x3,x3,#1 // else increment counter
mov x7,x1 // and save address command
4:
add x2,x2,#1 // increment indice
b 1b // and loop
5:
cmp x3,#1 // no find or multiple find ?
bne 99f // error
// one find
mov x0,x7 // length command table
bl computeLength
cmp x4,x0 // length input > command ?
bgt 99f // error
mov x4,#0x20 // 5 bit to 1
mov x2,#0
6:
ldrb w3,[x7,x2]
cbz w3,7f
bic x3,x3,x4 // convert to capital letter
strb w3,[x8,x2]
add x2,x2,#1
b 6b
7:
strb w3,[x8,x2]
mov x0,x8 // return string input address
b 100f
99:
ldr x0,qAdrszMessErrorAbr // return string "error"
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessErreur: .quad szMessErreur
qAdrszMessErrorAbr: .quad szMessErrorAbr
/******************************************************************/
/* comparaison first letters String */
/******************************************************************/
/* x0 contains first String */
/* x1 contains second string */
/* x0 return 0 if not find else returns number letters OK */
comparStringSpe:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x2,#0
1:
ldrb w3,[x0,x2] // input
orr w4,w3,#0x20 // convert capital letter
ldrb w5,[x1,x2] // table
orr w6,w5,#0x20 // convert capital letter
cmp w4,w6
bne 2f
cbz w3,3f // end strings ?
add x2,x2,#1
b 1b
2:
cbz w3,3f // fist letters Ok
mov x0,#0 // no ok
b 100f
3:
mov x0,x2
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* compute length String */
/******************************************************************/
/* x0 contains String */
/* x0 return length */
computeLength: // INFO: functionFN
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x1,#0
1:
ldrb w2,[x0,x1]
cbz w2,2f // end ?
add x1,x1,#1
b 1b
2:
mov x0,x1 // return length in x0
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* read file */
/******************************************************************/
/* x0 contains address stack begin */
traitFic: // INFO: traitFic
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,fp,[sp,-16]! // save registres
mov fp,x0 // fp <- start address
ldr x4,[fp] // number of Command line arguments
cmp x4,#1
ble 99f
add x5,fp,#16 // second parameter address
ldr x5,[x5]
ldr x0,qAdrqAdrFicName
str x5,[x0]
ldr x0,qAdrszMessTitre
bl affichageMess // display string
mov x0,x5
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess // display carriage return
mov x0,AT_FDCWD
mov x1,x5 // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8, #OPEN // call system OPEN
svc 0
cmp x0,#0 // error ?
ble 99f
mov x7,x0 // File Descriptor
ldr x1,qAdrsBufferCmd // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,#READ // read file
svc #0
cmp x0,#0 // error ?
blt 99f
// extraction datas
ldr x1,qAdrsBufferCmd // buffer address
add x1,x1,x0
mov x0,#0 // store zéro final
strb w0,[x1]
ldr x0,qAdriTabAdrCmd // key string command table
ldr x1,qAdrsBufferCmd // buffer address
bl extracDatas
// close file
mov x0,x7
mov x8, #CLOSE
svc 0
mov x0,#0
b 100f
99: // error
ldr x0,qAdrszMessErreur // error message
bl affichageMess
mov x0,#-1
100:
ldp x8,fp,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrqAdrFicName: .quad qAdrFicName
qAdrszMessTitre: .quad szMessTitre
qAdrsBuffer: .quad sBuffer
qAdrsBufferCmd: .quad sBufferCmd
qAdriTabAdrCmd: .quad iTabAdrCmd
/******************************************************************/
/* extrac digit file buffer */
/******************************************************************/
/* x0 contains strings address */
/* x1 contains buffer address */
extracDatas: // INFO: extracDatas
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,fp,[sp,-16]! // save registres
mov x7,x0
mov x6,x1
mov x8,#0 // top command name
mov x2,#0 // string buffer indice
mov x4,x1 // start string
mov x5,#0 // string index
1:
ldrb w3,[x6,x2]
cbz w3,4f // end
cmp x3,#0xA
beq 2f
cmp x3,#' ' // end string
beq 3f
add x2,x2,#1
b 1b
2:
mov x3,#0
strb w3,[x6,x2]
ldrb w3,[x6,x2]
cmp w3,#0xD
bne 21f
add x2,x2,#2
b 4f
21:
add x2,x2,#1
b 4f
3:
mov x3,#0
strb w3,[x6,x2]
add x2,x2,#1
4:
mov x0,x4
ldrb w1,[x0] // load first byte
cmp w1,#'0' // it is à digit ?
blt 5f
cmp w1,#'9'
bgt 5f
mov x1,#command_end
madd x1,x5,x1,x7 // compute address to store
mov x0,x4
bl conversionAtoD // conversion ascii digit
str x0,[x1,#command_min] // and store in minimum
mov x8,#0 // line command ok
add x5,x5,#1 // increment indice
b 7f
5:
cmp x8,#0 // other name ?
beq 6f
mov x0,#0 // yes store zéro in minimum in prec
mov x1,#command_end
madd x1,x5,x1,x7
add x1,x1,#command_min
str x0,[x1]
add x5,x5,#1 // and increment indice
6:
mov x8,#1 // load name
mov x1,#command_end
madd x1,x5,x1,x7 // store name in table
str x4,[x1,#command_name_address]
7: // loop suppress spaces
ldrb w3,[x6,x2]
cmp w3,#0
beq 100f
cmp w3,#' '
cinc x2,x2,eq
beq 7b
add x4,x6,x2 // new start address
b 1b
100:
ldp x8,fp,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* control load */
/******************************************************************/
/* x0 contains string table */
controlLoad:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x5,x0
mov x6,#0
mov x2,#command_end
1:
madd x3,x6,x2,x5 // compute item address
ldr x1,[x3,#command_name_address]
cbz x1,100f
ldr x0,qAdrszMessCtrlCom
bl strInsertAtCharInc
mov x4,x0
ldr x0,[x3,#command_min]
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
mov x0,x4
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
add x6,x6,#1
b 1b
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessCtrlCom: .quad szMessCtrlCom
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #MUMPS | MUMPS | Ackermann(m,n) ;
If m=0 Quit n+1
If m>0,n=0 Quit $$Ackermann(m-1,1)
If m>0,n>0 Quit $$Ackermann(m-1,$$Ackermann(m,n-1))
Set $Ecode=",U13-Invalid parameter for Ackermann: m="_m_", n="_n_","
Write $$Ackermann(1,8) ; 10
Write $$Ackermann(2,8) ; 19
Write $$Ackermann(3,5) ; 253 |
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #11l | 11l | V grid = [[0] * 10] * 10
grid[5][5] = 64
print(‘Before:’)
L(row) grid
print(row.map(c -> ‘#3’.format(c)).join(‘’))
F simulate(&grid)
L
V changed = 0B
L(arr) grid
V ii = L.index
L(val) arr
V jj = L.index
I val > 3
grid[ii][jj] -= 4
I ii > 0
grid[ii - 1][jj]++
I ii < grid.len - 1
grid[ii + 1][jj]++
I jj > 0
grid[ii][jj - 1]++
I jj < grid.len - 1
grid[ii][jj + 1]++
changed = 1B
I !changed
L.break
simulate(&grid)
print("\nAfter:")
L(row) grid
print(row.map(c -> ‘#3’.format(c)).join(‘’))
grid = [[0] * 65] * 65
grid[32][32] = 64 * 64
simulate(&grid)
V ppm = File(‘sand_pile.ppm’, ‘w’)
ppm.write_bytes(("P6\n#. #.\n255\n".format(grid.len, grid.len)).encode())
V colors = [[Byte(0), 0, 0],
[Byte(255), 0, 0],
[Byte(0), 255, 0],
[Byte(0), 0, 255]]
L(row) grid
L(c) row
ppm.write_bytes(colors[c]) |
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #Ada | Ada | with Ada.Characters.Handling;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
procedure Abbreviations_Simple is
use Ada.Strings.Unbounded;
subtype Ustring is Unbounded_String;
type Word_Entry is record
Word : Ustring;
Min : Natural;
end record;
package Command_Vectors
is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Word_Entry);
Commands : Command_Vectors.Vector;
Last_Word : Ustring;
Last_Was_Word : Boolean := False;
procedure Append (Word_List : String) is
use Ada.Strings;
function Is_Word (Item : String) return Boolean
is (Fixed.Count (Item, Maps.Constants.Letter_Set) /= 0);
procedure Process (Token : String) is
begin
if Is_Word (Token) then
if Last_Was_Word then
Commands.Append ((Word => Last_Word,
Min => Length (Last_Word)));
end if;
Last_Word := To_Unbounded_String (Token);
Last_Was_Word := True;
else -- Token is expected to be decimal
Commands.Append ((Word => Last_Word,
Min => Natural'Value (Token)));
Last_Was_Word := False;
end if;
end Process;
Token_First : Positive := Word_List'First;
Token_Last : Natural;
begin
while Token_First in Word_List'Range loop
Fixed.Find_Token (Word_List, Maps.Constants.Alphanumeric_Set,
Token_First, Inside,
Token_First, Token_Last);
exit when Token_Last = 0;
Process (Word_List (Token_First .. Token_Last));
Token_First := Token_Last + 1;
end loop;
end Append;
function Match (Word : String) return String is
use Ada.Characters.Handling;
use Ada.Strings.Fixed;
Result : Ustring := To_Unbounded_String ("*error*");
Min : Natural := 0;
Upper_Word : constant String := To_Upper (Word);
begin
if Upper_Word = "" then
return "";
end if;
for Candidate of Commands loop
declare
Upper_Cand : constant String := To_Upper (To_String (Candidate.Word));
Length : constant Natural := Natural'Max (Candidate.Min,
Upper_Word'Length);
Upper_Abbrev_Cand : constant String := Head (Upper_Cand, Length);
Upper_Abbrev_Word : constant String := Head (Upper_Word, Length);
begin
if Upper_Word = Upper_Cand
and then Upper_Word'Length > Min
then
Result := To_Unbounded_String (Upper_Cand);
Min := Upper_Word'Length;
elsif Upper_Abbrev_Word = Upper_Abbrev_Cand
and then Upper_Abbrev_Word'Length > Min
then
Result := To_Unbounded_String (Upper_Cand);
Min := Upper_Abbrev_Word'Length;
end if;
end;
end loop;
return To_String (Result);
end Match;
procedure Put_Match (To : String) is
use Ada.Text_IO;
begin
Put ("Match to '"); Put (To);
Put ("' is '"); Put (Match (To));
Put_Line ("'");
end Put_Match;
procedure A (Item : String) renames Append;
begin
A ("add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3");
A ("compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate");
A ("3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2");
A ("forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load");
A ("locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2");
A ("msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3");
A ("refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left");
A ("2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1");
Put_Match ("riG");
Put_Match ("rePEAT");
Put_Match ("copies");
Put_Match ("put");
Put_Match ("mo");
Put_Match ("rest");
Put_Match ("types");
Put_Match ("fup.");
Put_Match ("6");
Put_Match ("poweRin");
Put_Match ("");
end Abbreviations_Simple; |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #11l | 11l | V command_table_text =
|‘Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up’
V user_words = ‘riG rePEAT copies put mo rest types fup. 6 poweRin’
F find_abbreviations_length(command_table_text)
‘ find the minimal abbreviation length for each word by counting capital letters.
a word that does not have capital letters gets it's full length as the minimum.
’
[String = Int] command_table
L(word) command_table_text.split((‘ ’, "\n"), group_delimiters' 1B)
V abbr_len = sum(word.filter(c -> c.is_uppercase()).map(c -> 1))
I abbr_len == 0
abbr_len = word.len
command_table[word] = abbr_len
R command_table
F find_abbreviations(command_table)
‘ for each command insert all possible abbreviations’
[String = String] abbreviations
L(command, min_abbr_len) command_table
L(l) min_abbr_len .. command.len
V abbr = command[0 .< l].lowercase()
abbreviations[abbr] = command.uppercase()
R abbreviations
F parse_user_string(user_string, abbreviations)
V user_words = user_string.split(‘ ’, group_delimiters' 1B).map(word -> word.lowercase())
V commands = user_words.map(user_word -> @abbreviations.get(user_word, ‘*error*’))
R commands.join(‘ ’)
V command_table = find_abbreviations_length(command_table_text)
V abbreviations_table = find_abbreviations(command_table)
V full_words = parse_user_string(user_words, abbreviations_table)
print(‘user words: ’user_words)
print(‘full words: ’full_words) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Neko | Neko | /**
Ackermann recursion, in Neko
Tectonics:
nekoc ackermann.neko
neko ackermann 4 0
*/
ack = function(x,y) {
if (x == 0) return y+1;
if (y == 0) return ack(x-1,1);
return ack(x-1, ack(x,y-1));
};
var arg1 = $int($loader.args[0]);
var arg2 = $int($loader.args[1]);
/* If not given, or negative, default to Ackermann(3,4) */
if (arg1 == null || arg1 < 0) arg1 = 3;
if (arg2 == null || arg2 < 0) arg2 = 4;
try
$print("Ackermann(", arg1, ",", arg2, "): ", ack(arg1,arg2), "\n")
catch problem
$print("Ackermann(", arg1, ",", arg2, "): ", problem, "\n") |
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program abelian64.s */
/* run : abelian 256 12 12 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessValue: .asciz "@ "
szMessErrParam: .asciz "error : command line = abelian size posx posy \n"
szMessFin: .asciz "End display :\n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
iSandPile: .skip 8 * MAXI * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov fp,sp
ldr x4,[fp] // load number of parameters command line
cmp x4,#3 // < 4 -> error
ble 99f
add x0,fp,#32 // load address param 4 = pos y
ldr x0,[x0]
bl conversionAtoD // conversion ascii -> numeric
mov x3,x0
add x0,fp,#24 // load address param 3 = pos x
ldr x0,[x0]
bl conversionAtoD
mov x2,x0
add x0,fp,#16 // load address param 2 = size begin pile
ldr x0,[x0]
bl conversionAtoD
ldr x4,qAdriSandPile
mov x5,#MAXI
madd x5,x3,x5,x2 // compute offset = maxi * y + x
str x0,[x4,x5,lsl #3] // and store size in pos x,y
//mov x0,x4 // display start position
//bl displaySandPile
mov x0,x4 // sandpile address
mov x1,x2 // pos x to start
mov x2,x3 // pos y to start
bl addSand
ldr x0,qAdrszMessFin
bl affichageMess
mov x0,x4
bl displaySandPile
b 100f
99: // line command error
ldr x0,qAdrszMessErrParam
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessErrParam: .quad szMessErrParam
qAdrszMessFin: .quad szMessFin
qAdriSandPile: .quad iSandPile
/***************************************************/
/* display sandpile */
/***************************************************/
// x0 contains address to sandpile
displaySandPile:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x6,x0
mov x3,#0 // indice y
mov x4,#MAXI
1:
mov x2,#0 // indice x
2:
madd x5,x3,x4,x2 // compute offset
ldr x0,[x6,x5,lsl #3] // load value at pos x,y
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
add x1,x1,1
mov x7,#0
strb w7,[x1,x0]
ldr x0,qAdrszMessValue
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
bl affichageMess
add x2,x2,1
cmp x2,MAXI
blt 2b
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x3,x3,1
cmp x3,MAXI
blt 1b
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessValue: .quad szMessValue
/***************************************************/
/* display sandpile */
/***************************************************/
// x0 contains address to sanspile
// x1 contains position x
// x2 contains position y
addSand:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x3,#MAXI
madd x4,x3,x2,x1 // compute offset
ldr x5,[x0,x4,lsl #3]
1:
cmp x5,#4 // 4 grains ?
blt 100f
sub x5,x5,4 // yes sustract
str x5,[x0,x4,lsl #3]
cmp x1,MAXI-1 // right position ok ?
beq 2f
add x1,x1,1 // yes
bl add1Sand // add 1 grain
bl addSand // and compute new pile
sub x1,x1,1
2:
cmp x1,0 // left position ok ?
beq 3f
sub x1,x1,1
bl add1Sand
bl addSand
add x1,x1,1
3:
cmp x2,0 // higt position ok ?
beq 4f
sub x2,x2,1
bl add1Sand
bl addSand
add x2,x2,1
4:
cmp x2,MAXI-1 // low position ok ?
beq 5f
add x2,x2,1
bl add1Sand
bl addSand
sub x2,x2,1
5:
ldr x5,[x0,x4,lsl #3] // reload value
b 1b // and loop
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* add 1 grain of sand */
/***************************************************/
// x0 contains address to sanspile
// x1 contains position x
// x2 contains position y
add1Sand:
stp x3,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x3,#MAXI
madd x4,x3,x2,x1 // compute offset
ldr x5,[x0,x4,lsl #3] // load value at pos x,y
add x5,x5,1
str x5,[x0,x4,lsl #3] // and store
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x3,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program abelian.s */
/* run : abelian 256 12 12 */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessValue: .asciz "@ "
szMessErrParam: .asciz "error : command line = abelian size posx posy \n"
szMessFin: .asciz "End display :\n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
iSandPile: .skip 4 * MAXI * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov fp,sp
ldr r4,[fp] @ load number of parameters commend line
cmp r4,#3 @ < 4 -> error
ble 99f
add r0,fp,#16 @ load address param 4 = pos y
ldr r0,[r0]
bl conversionAtoD @ conversion ascii -> numeric
mov r3,r0
add r0,fp,#12 @ load address param 3 = pos x
ldr r0,[r0]
bl conversionAtoD
mov r2,r0
add r0,fp,#8 @ load address param 2 = size begin pile
ldr r0,[r0]
bl conversionAtoD
ldr r4,iAdriSandPile
mov r5,#MAXI
mul r5,r3,r5 @ compute offset = maxi * y
add r5,r2 @ + x
str r0,[r4,r5,lsl #2] @ and store size in pos x,y
//mov r0,r4 @ display start position
//bl displaySandPile
mov r0,r4 @ sandpile address
mov r1,r2 @ pos x to start
mov r2,r3 @ pos y to start
bl addSand
ldr r0,iAdrszMessFin
bl affichageMess
mov r0,r4
bl displaySandPile
b 100f
99: @ line command error
ldr r0,iAdrszMessErrParam
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessErrParam: .int szMessErrParam
iAdrszMessFin: .int szMessFin
iAdriSandPile: .int iSandPile
/***************************************************/
/* display sandpile */
/***************************************************/
// r0 contains address to sandpile
displaySandPile:
push {r1-r6,lr} @ save registers
mov r6,r0
mov r3,#0 @ indice y
mov r4,#MAXI
1:
mov r2,#0 @ indice x
2:
mul r5,r3,r4
add r5,r2 @ compute offset
ldr r0,[r6,r5,lsl #2] @ load value at pos x,y
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
add r1,#1
mov r7,#0
strb r7,[r1,r0]
ldr r0,iAdrszMessValue
ldr r1,iAdrsZoneConv @ insert value conversion in message
bl strInsertAtCharInc
bl affichageMess
add r2,#1
cmp r2,#MAXI
blt 2b
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r3,#1
cmp r3,#MAXI
blt 1b
100:
pop {r1-r6,lr} @ restaur registers
bx lr @ return
iAdrszMessValue: .int szMessValue
/***************************************************/
/* display sandpile */
/***************************************************/
// r0 contains address to sanspile
// r1 contains position x
// r2 contains position y
addSand:
push {r1-r5,lr} @ save registers
mov r3,#MAXI
mul r4,r3,r2
add r4,r1
ldr r5,[r0,r4,lsl #2]
1:
cmp r5,#4 @ 4 grains ?
blt 100f
sub r5,#4 @ yes sustract
str r5,[r0,r4,lsl #2]
cmp r1,#MAXI-1 @ right position ok ?
beq 2f
add r1,#1 @ yes
bl add1Sand @ add 1 grain
bl addSand @ and compute new pile
sub r1,#1
2:
cmp r1,#0 @ left position ok ?
beq 3f
sub r1,#1
bl add1Sand
bl addSand
add r1,#1
3:
cmp r2,#0 @ higt position ok ?
beq 4f
sub r2,#1
bl add1Sand
bl addSand
add r2,#1
4:
cmp r2,#MAXI-1 @ low position ok ?
beq 5f
add r2,#1
bl add1Sand
bl addSand
sub r2,#1
5:
ldr r5,[r0,r4,lsl #2] @ reload value
b 1b @ and loop
100:
pop {r1-r5,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* add 1 grain of sand */
/***************************************************/
// r0 contains address to sanspile
// r1 contains position x
// r2 contains position y
add1Sand:
push {r3-r5,lr} @ save registers
mov r3,#MAXI
mul r4,r3,r2
add r4,r1 @ compute offset
ldr r5,[r0,r4,lsl #2] @ load value at pos x,y
add r5,#1
str r5,[r0,r4,lsl #2] @ and store
100:
pop {r3-r5,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #ALGOL_68 | ALGOL 68 | # "Simple" abbreviations #
# returns the next word from text, updating pos #
PRIO NEXTWORD = 1;
OP NEXTWORD = ( REF INT pos, STRING text )STRING:
BEGIN
# skip spaces #
WHILE IF pos > UPB text THEN FALSE ELSE text[ pos ] = " " FI DO pos +:= 1 OD;
# get the word #
STRING word := "";
WHILE IF pos > UPB text THEN FALSE ELSE text[ pos ] /= " " FI DO
word +:= text[ pos ];
pos +:= 1
OD;
word
END # NEXTWORD # ;
# returns text converted to upper case #
OP TOUPPER = ( STRING text )STRING:
BEGIN
STRING result := text;
FOR ch pos FROM LWB result TO UPB result DO
IF is lower( result[ ch pos ] ) THEN result[ ch pos ] := to upper( result[ ch pos ] ) FI
OD;
result
END # TOUPPER # ;
# returns text converted to an INT or -1 if text is not a number #
OP TOINT = ( STRING text )INT:
BEGIN
INT result := 0;
BOOL is numeric := TRUE;
FOR ch pos FROM UPB text BY -1 TO LWB text WHILE is numeric DO
CHAR c = text[ ch pos ];
is numeric := ( c >= "0" AND c <= "9" );
IF is numeric THEN ( result *:= 10 ) +:= ABS c - ABS "0" FI
OD;
IF is numeric THEN result ELSE -1 FI
END # TOINT # ;
# returns the length of word #
OP LENGTH = ( STRING word )INT: 1 + ( UPB word - LWB word );
# counts the number of commands in commands #
PROC count commands = ( STRING commands )INT:
BEGIN
INT result := 0;
INT pos := LWB commands;
WHILE STRING command := pos NEXTWORD commands; command /= "" DO
IF TOINT command < 0 THEN
# not an abbreviation length #
result +:= 1
FI
OD;
result
END # count commands # ;
# list of "commands" - the words are optionally followed by the minimum #
# length of abbreviation - if there isn't a number #
# the command can only appear in full #
STRING commands
= "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
+ "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
+ "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
+ "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
+ "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
+ "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
+ "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
+ "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
;
# build the tables of the commands and their minimum lengths #
PROC load commands = ( STRING commands )VOID:
BEGIN
INT cmd pos := 0;
INT pos := LWB command table;
WHILE STRING command := pos NEXTWORD commands; command /= "" DO
INT len := TOINT command;
IF len >= 0 THEN
# have an abbreviation length #
IF cmd pos > 0 THEN min abbreviation[ cmd pos ] := len FI
ELSE
# new command #
cmd pos +:= 1;
command table[ cmd pos ] := TOUPPER command;
min abbreviation[ cmd pos ] := LENGTH command
FI
OD
END # load commands # ;
# searches for word in command table and returns the full command #
# matching the possible abbreviation or *error* if there is no match #
OP EXPAND = ( STRING word )STRING:
IF word = ""
THEN # empty word #
""
ELSE # non-empty word #
INT word len = LENGTH word;
STRING upper word := TOUPPER word;
STRING result := "*error*";
FOR cmd pos FROM LWB command table TO UPB command table
WHILE STRING command := command table[ cmd pos ];
IF word len < min abbreviation[ cmd pos ] OR word len > LENGTH command
THEN # word is too short or too long - try the next command #
TRUE
ELIF upper word = command[ LWB command : ( LWB command - 1 ) + word len ]
THEN # found the command #
result := command;
FALSE
ELSE # word doexn't match - try the next command #
TRUE
FI
DO SKIP OD;
result
FI # EXPAND # ;
# tests the EXPAND operator #
PROC test expand = ( STRING words )VOID:
BEGIN
STRING results := "", separator := "";
INT pos := LWB words;
WHILE STRING word = pos NEXTWORD words; word /= "" DO
results +:= separator + EXPAND word;
separator := " "
OD;
print( ( "Input: ", words, newline ) );
print( ( "Output: ", results, newline ) )
END # test expand # ;
# build the command table #
[ 1 : count commands( commands ) ]STRING command table;
[ 1 : UPB command table ]INT min abbreviation;
load commands( commands );
# task test cases #
test expand( "riG rePEAT copies put mo rest types fup. 6 poweRin" ) |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program abbrEasy64.s */
/* store list of command in a file */
/* and run the program abbrEasy64 command.file */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 1000
.equ NBMAXIELEMENTS, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre: .asciz "Nom du fichier : "
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Error detected.\n"
szMessErrBuffer: .asciz "buffer size too less !!"
szMessErrorAbr: .asciz "*error*"
szMessInput: .asciz "Enter command (or quit to stop) : "
szCmdQuit: .asciz "QUIT"
szValTest1: .asciz "Quit"
szValTest2: .asciz "Rep"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
sZoneConv: .skip 24
qAdrFicName: .skip 8
iTabAdrCmd: .skip 8 * NBMAXIELEMENTS
sBufferCmd: .skip BUFFERSIZE
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // INFO: main
mov x0,sp // stack address for load parameter
bl traitFic // read file and store value in array
cmp x0,#-1
beq 100f // error ?
ldr x0,qAdriTabAdrCmd
bl controlLoad
1:
ldr x0,qAdrszMessInput // display input message
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8, #READ // request to read datas
svc 0 // call system
sub x0,x0,#1
mov x2,#0
strb w2,[x1,x0] // replace character 0xA by zéro final
ldr x0,qAdrsBuffer
ldr x1,qAdriTabAdrCmd
bl controlCommand // control text command
mov x2,x0
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
ldr x1,qAdrszCmdQuit // command quit ?
bl comparStrings
cmp x0,#0
beq 100f // yes -> end
b 1b // else loop
99:
ldr x0,qAdrszMessErrBuffer
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessErrBuffer: .quad szMessErrBuffer
qAdrsZoneConv: .quad sZoneConv
qAdrszMessInput: .quad szMessInput
qAdrszCmdQuit: .quad szCmdQuit
/******************************************************************/
/* control abbrevation command */
/******************************************************************/
/* x0 contains string input command */
/* x1 contains address table string command */
controlCommand: // INFO: controlCommand
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x8,x0
mov x9,x1
bl computeLength // length input command
mov x4,x0 // save length input
mov x2,#0 // indice
mov x3,#0 // find counter
1: // loop search command in table
ldr x1,[x9,x2,lsl #3] // load a item
cmp x1,#0 // end ?
beq 5f
mov x0,x8
bl comparStringSpe //
cmp x0,#0 // no found other search
beq 4f
mov x6,#0
mov x5,#0
2: // loop count capital letters
ldrb w0,[x1,x6]
cmp x0,#0
beq 3f
tst x0,#0x20 // capital letter ?
cinc x5,x5,eq
add x6,x6,#1
b 2b
3:
cmp x4,x5 // input < command capital letters
blt 4f // no correct
add x3,x3,#1 // else increment counter
mov x7,x1 // and save address command
4:
add x2,x2,#1 // increment indice
b 1b // and loop
5:
cmp x3,#1 // no find or multiple find ?
bne 99f // error
// one find
mov x0,x7 // length command table
bl computeLength
cmp x4,x0 // length input > command ?
bgt 99f // error
// OK
mov x4,#0x20 // 5 bit to 1
mov x2,#0
6:
ldrb w3,[x7,x2]
cmp x3,#0
beq 7f
bic x3,x3,x4 // convert to capital letter
strb w3,[x8,x2]
add x2,x2,#1
b 6b
7:
strb w3,[x8,x2] // store zéro final
mov x0,x8 // return string input address
b 100f
99:
ldr x0,qAdrszMessErrorAbr // return string "error"
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessErreur: .quad szMessErreur
qAdrszMessErrorAbr: .quad szMessErrorAbr
/******************************************************************/
/* comparaison first letters String */
/******************************************************************/
/* x0 contains first String */
/* x1 contains second string */
/* x0 return 0 if not find else returns number letters OK */
comparStringSpe:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x2,#0
1:
ldrb w3,[x0,x2] // input
orr x4,x3,#0x20 // convert capital letter
ldrb w5,[x1,x2] // table
orr x6,x5,#0x20 // convert capital letter
cmp x4,x6
bne 2f
cmp x3,#0
beq 3f
add x2,x2,#1
b 1b
2:
cmp x3,#0 // fist letters Ok
beq 3f
mov x0,#0 // no ok
b 100f
3:
mov x0,x2
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* compute length String */
/******************************************************************/
/* x0 contains String */
/* x0 return length */
computeLength:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x1,#0
1:
ldrb w2,[x0,x1]
cmp x2,#0 // end ?
beq 2f
add x1,x1,#1
b 1b
2:
mov x0,x1 // return length in x0
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* read file */
/******************************************************************/
/* x0 contains address stack begin */
traitFic: // INFO: traitFic
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,fp,[sp,-16]! // save registres
mov fp,x0 // fp <- start address
ldr x4,[fp] // number of Command line arguments
cmp x4,#1
ble 99f
add x5,fp,#16 // second parameter address
ldr x5,[x5]
ldr x0,qAdrqAdrFicName
str x5,[x0]
ldr x0,qAdrszMessTitre
bl affichageMess // display string
mov x0,x5
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess // display carriage return
mov x0,AT_FDCWD
mov x1,x5 // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8, #OPEN // call system OPEN
svc 0
cmp x0,#0 // error ?
ble 99f
mov x7,x0 // File Descriptor
ldr x1,qAdrsBufferCmd // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,#READ // read file
svc #0
cmp x0,#0 // error ?
blt 99f
// extraction datas
ldr x1,qAdrsBufferCmd // buffer address
add x1,x1,x0
mov x0,#0 // store zéro final
strb w0,[x1]
ldr x0,qAdriTabAdrCmd // key string command table
ldr x1,qAdrsBufferCmd // buffer address
bl extracDatas
// close file
mov x0,x7
mov x8, #CLOSE
svc 0
mov x0,#0
b 100f
99: // error
ldr x0,qAdrszMessErreur // error message
bl affichageMess
mov x0,#-1
100:
ldp x8,fp,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrqAdrFicName: .quad qAdrFicName
qAdrszMessTitre: .quad szMessTitre
qAdrsBuffer: .quad sBuffer
qAdrsBufferCmd: .quad sBufferCmd
qAdriTabAdrCmd: .quad iTabAdrCmd
/******************************************************************/
/* extrac digit file buffer */
/******************************************************************/
/* x0 contains strings address */
/* x1 contains buffer address */
extracDatas: // INFO: extracDatas
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,fp,[sp,-16]! // save registres
mov x7,x0
mov x6,x1
mov x2,#0 // string buffer indice
mov x4,x1 // start string
mov x5,#0 // string index
//vidregtit debextrac
1:
ldrb w3,[x6,x2]
cmp x3,#0
beq 4f // end
cmp x3,#0xA
beq 2f
cmp x3,#' ' // end string
beq 3f
add x2,x2,#1
b 1b
2:
mov x3,#0
strb w3,[x6,x2]
ldrb w3,[x6,x2]
cmp x3,#0xD
bne 21f
add x2,x2,#2
b 4f
21:
add x2,x2,#1
b 4f
3:
mov x3,#0
strb w3,[x6,x2]
add x2,x2,#1
4:
mov x0,x4
str x4,[x7,x5,lsl #3]
add x5,x5,#1
5:
ldrb w3,[x6,x2]
cmp x3,#0
beq 100f
cmp x3,#' '
cinc x2,x2,eq
//addeq x2,x2,#1
beq 5b
add x4,x6,x2 // new start address
b 1b
100:
ldp x8,fp,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* control load */
/******************************************************************/
/* x0 contains string table */
controlLoad:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
mov x1,#0
1:
ldr x0,[x2,x1,lsl #3]
cmp x0,#0
beq 100f
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x1,x1,#1
b 1b
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* x0 et x1 contains the address of strings */
/* return 0 in x0 if equals */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparStrings:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x2,#0 // counter
1:
ldrb w3,[x0,x2] // byte string 1
ldrb w4,[x1,x2] // byte string 2
cmp x3,x4
blt 2f
bgt 3f
cmp x3,#0 // 0 end string
beq 4f // end string
add x2,x2,#1 // else add 1 in counter
b 1b // and loop
2:
mov x0,#-1 // small
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #Ada | Ada | with Ada.Characters.Handling;
with Ada.Containers.Indefinite_Vectors;
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;
with Ada.Text_IO;
procedure Abbreviations_Easy is
package Command_Vectors
is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => String);
use Command_Vectors;
Commands : Vector;
procedure Append (Word_List : String) is
use Ada.Strings;
First : Positive := Word_List'First;
Last : Natural;
begin
loop
Fixed.Find_Token (Word_List,
Set => Maps.Constants.Letter_Set,
From => First,
Test => Inside,
First => First,
Last => Last);
exit when Last = 0;
Commands.Append (Word_List (First .. Last));
exit when Last = Word_List'Last;
First := Last + 1;
end loop;
end Append;
function Match (Word : String) return String is
use Ada.Strings;
use Ada.Characters.Handling;
Upper_Word : constant String := To_Upper (Word);
Prefix_First : Positive;
Prefix_Last : Natural;
begin
if Word = "" then
return "";
end if;
for Command of Commands loop
Fixed.Find_Token (Command, Maps.Constants.Upper_Set, Inside,
Prefix_First, Prefix_Last);
declare
Upper_Prefix : constant String := Command (Prefix_First .. Prefix_Last);
Upper_Command : constant String := To_Upper (Command);
Valid_Length : constant Boolean := Word'Length >= Upper_Prefix'Length;
Match_Length : constant Natural := Natural'Min (Word'Length,
Command'Length);
Valid_Match : constant Boolean
:= Fixed.Head (Upper_Word, Upper_Word'Length)
= Fixed.Head (Upper_Command, Upper_Word'Length);
begin
if Valid_Length and Valid_Match then
return Upper_Command;
end if;
end;
end loop;
return "*error*";
end Match;
procedure Put_Match (To : String) is
use Ada.Text_IO;
M : constant String := Match (To);
begin
Put ("Match to '"); Put (To);
Put ("' is '"); Put (M);
Put_Line ("'");
end Put_Match;
procedure A (Item : String) renames Append;
begin
A ("Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy");
A ("COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find");
A ("NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput");
A ("Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO");
A ("MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT");
A ("READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT");
A ("RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up");
Put_Match ("riG");
Put_Match ("rePEAT");
Put_Match ("copies");
Put_Match ("put");
Put_Match ("mo");
Put_Match ("rest");
Put_Match ("types");
Put_Match ("fup.");
Put_Match ("6");
Put_Match ("poweRin");
Put_Match ("");
Put_Match ("o");
end Abbreviations_Easy; |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Nemerle | Nemerle |
using System;
using Nemerle.IO;
def ackermann(m, n) {
def A = ackermann;
match(m, n) {
| (0, n) => n + 1
| (m, 0) when m > 0 => A(m - 1, 1)
| (m, n) when m > 0 && n > 0 => A(m - 1, A(m, n - 1))
| _ => throw Exception("invalid inputs");
}
}
for(mutable m = 0; m < 4; m++) {
for(mutable n = 0; n < 5; n++) {
print("ackermann($m, $n) = $(ackermann(m, n))\n");
}
}
|
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int main(int argc, char** argv)
{
int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;
int** sandPile;
char* fileName;
static unsigned char colour[3];
if(argc!=3){
printf("Usage: %s <Sand pile side> <Center pile height>",argv[0]);
return 0;
}
sandPileEdge = atoi(argv[1]);
centerPileHeight = atoi(argv[2]);
if(sandPileEdge<=0 || centerPileHeight<=0){
printf("Sand pile and center pile dimensions must be positive integers.");
return 0;
}
sandPile = (int**)malloc(sandPileEdge * sizeof(int*));
for(i=0;i<sandPileEdge;i++){
sandPile[i] = (int*)calloc(sandPileEdge,sizeof(int));
}
sandPile[sandPileEdge/2][sandPileEdge/2] = centerPileHeight;
printf("Initial sand pile :\n\n");
for(i=0;i<sandPileEdge;i++){
for(j=0;j<sandPileEdge;j++){
printf("%3d",sandPile[i][j]);
}
printf("\n");
}
while(processAgain == 1){
processAgain = 0;
top = 0;
down = 0;
left = 0;
right = 0;
for(i=0;i<sandPileEdge;i++){
for(j=0;j<sandPileEdge;j++){
if(sandPile[i][j]>=4){
if(i-1>=0){
top = 1;
sandPile[i-1][j]+=1;
if(sandPile[i-1][j]>=4)
processAgain = 1;
}
if(i+1<sandPileEdge){
down = 1;
sandPile[i+1][j]+=1;
if(sandPile[i+1][j]>=4)
processAgain = 1;
}
if(j-1>=0){
left = 1;
sandPile[i][j-1]+=1;
if(sandPile[i][j-1]>=4)
processAgain = 1;
}
if(j+1<sandPileEdge){
right = 1;
sandPile[i][j+1]+=1;
if(sandPile[i][j+1]>=4)
processAgain = 1;
}
sandPile[i][j] -= (top + down + left + right);
if(sandPile[i][j]>=4)
processAgain = 1;
}
}
}
}
printf("Final sand pile : \n\n");
for(i=0;i<sandPileEdge;i++){
for(j=0;j<sandPileEdge;j++){
printf("%3d",sandPile[i][j]);
}
printf("\n");
}
fileName = (char*)malloc((strlen(argv[1]) + strlen(argv[2]) + 23)*sizeof(char));
strcpy(fileName,"Final_Sand_Pile_");
strcat(fileName,argv[1]);
strcat(fileName,"_");
strcat(fileName,argv[2]);
strcat(fileName,".ppm");
FILE *fp = fopen(fileName,"wb");
fprintf(fp,"P6\n%d %d\n255\n",sandPileEdge,sandPileEdge);
for(i=0;i<sandPileEdge;i++){
for(j=0;j<sandPileEdge;j++){
colour[0] = (sandPile[i][j] + i)%256;
colour[1] = (sandPile[i][j] + j)%256;
colour[2] = (sandPile[i][j] + i*j)%256;
fwrite(colour,1,3,fp);
}
}
fclose(fp);
printf("\nImage file written to %s\n",fileName);
return 0;
}
|
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #ARM_Assembly | ARM Assembly | Ok correction le 17/11/2020 16H |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #ALGOL_68 | ALGOL 68 | # "Easy" abbreviations #
# table of "commands" - upper-case indicates the mminimum abbreviation #
STRING command table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
+ "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
+ "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
+ "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
+ "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
+ "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
+ "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
# returns the next word from text, updating pos #
PRIO NEXTWORD = 1;
OP NEXTWORD = ( REF INT pos, STRING text )STRING:
BEGIN
# skip spaces #
WHILE IF pos > UPB text THEN FALSE ELSE text[ pos ] = " " FI DO pos +:= 1 OD;
# get the word #
STRING word := "";
WHILE IF pos > UPB text THEN FALSE ELSE text[ pos ] /= " " FI DO
word +:= text[ pos ];
pos +:= 1
OD;
word
END # NEXTWORD # ;
# returns text converted to upper case #
OP TOUPPER = ( STRING text )STRING:
BEGIN
STRING result := text;
FOR ch pos FROM LWB result TO UPB result DO
IF is lower( result[ ch pos ] ) THEN result[ ch pos ] := to upper( result[ ch pos ] ) FI
OD;
result
END # TOUPPER # ;
# returns the minimum abbreviation length of command #
OP MINABLENGTH = ( STRING command )INT:
BEGIN
INT ab min := LWB command;
WHILE IF ab min > UPB command THEN FALSE ELSE is upper( command[ ab min ] ) FI DO ab min +:= 1 OD;
ab min - LWB command
END # MINABLENGTH # ;
# searches for word in command table and returns the full command #
# matching the possible abbreviation or *error* if there is no match #
PRIO EXPAND = 1;
OP EXPAND = ( STRING command table, word )STRING:
IF word = ""
THEN # empty word #
""
ELSE # non-empty word #
INT word len = ( UPB word + 1 ) - LWB word;
STRING upper word := TOUPPER word;
STRING result := "*error*";
INT pos := LWB command table;
WHILE STRING command := pos NEXTWORD command table;
IF command = ""
THEN # end of command table #
FALSE
ELIF word len < MINABLENGTH command OR word len > ( ( UPB command + 1 ) - LWB command )
THEN # word is too short or too long - try the next command #
TRUE
ELIF upper word = TOUPPER command[ LWB command : ( LWB command - 1 ) + word len ]
THEN # found the command #
result := TOUPPER command;
FALSE
ELSE # word doexn't match - try the next command #
TRUE
FI
DO SKIP OD;
result
FI # EXPAND # ;
# tests the EXPAND operator #
PROC test expand = ( STRING words, command table )VOID:
BEGIN
STRING results := "", separator := "";
INT pos := LWB words;
WHILE STRING word = pos NEXTWORD words; word /= "" DO
results +:= separator + ( command table EXPAND word );
separator := " "
OD;
print( ( "Input: ", words, newline ) );
print( ( "Output: ", results, newline ) )
END # test expand # ;
# task test cases #
test expand( "riG rePEAT copies put mo rest types fup. 6 poweRin", command table );
test expand( "", command table ) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
numeric digits 66
parse arg j_ k_ .
if j_ = '' | j_ = '.' | \j_.datatype('w') then j_ = 3
if k_ = '' | k_ = '.' | \k_.datatype('w') then k_ = 5
loop m_ = 0 to j_
say
loop n_ = 0 to k_
say 'ackermann('m_','n_') =' ackermann(m_, n_).right(5)
end n_
end m_
return
method ackermann(m, n) public static
select
when m = 0 then rval = n + 1
when n = 0 then rval = ackermann(m - 1, 1)
otherwise rval = ackermann(m - 1, ackermann(m, n - 1))
end
return rval
|
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #C.2B.2B | C++ | #include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor-io/ximage.hpp"
xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim)
{
xt::xarray<int>::shape_type shape = { x_dim, y_dim };
xt::xarray<int> grid(shape);
grid(x_dim/2, y_dim/2) = 64000;
return grid;
}
int print_grid(xt::xarray<int>& grid)
{
// for output to the terminal uncomment next line
// only makes sense for small grid < 32x32;
// std::cout << grid << std::endl << std::endl;
// output result to an image
xt::dump_image("grid.jpg", grid);
return 0;
}
bool iterate_grid(xt::xarray<int>& grid, const unsigned long& x_dim, const unsigned long& y_dim)
{
bool changed = false;
for (unsigned long i=0; i < x_dim; ++i)
{
for (unsigned long j=0; j < y_dim; ++j)
{
if ( grid(i, j) >= 4 )
{
grid(i, j) -= 4;
changed = true;
try
{
grid.at(i-1, j) += 1;
grid.at(i+1, j) += 1;
grid.at(i, j-1) += 1;
grid.at(i, j+1) += 1;
}
catch (const std::out_of_range& oor)
{
}
}
}
}
return changed;
}
int main(int argc, char* argv[])
{
const unsigned long x_dim { 200 };
const unsigned long y_dim { 200 };
xt::xarray<int> grid = init_grid(x_dim, y_dim);
bool changed { true };
iterate_grid(grid, x_dim, y_dim);
while (changed == true)
{
changed = iterate_grid(grid, x_dim, y_dim);
}
print_grid(grid);
return 0;
} |
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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 <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
// str is assumed to be all uppercase
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
// convert string to uppercase
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = word_len;
new_cmd->cmd = uppercase(word, word_len);
if (i + 1 < count) {
char* eptr = 0;
unsigned long min_len = strtoul(words[i + 1], &eptr, 10);
if (min_len > 0 && *eptr == 0) {
free(words[i + 1]);
new_cmd->min_len = min_len;
++i;
}
}
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
} |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #ARM_Assembly | ARM Assembly | Correction program 15/11/2020 |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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
| #AutoHotkey | AutoHotkey | ; Setting up command table as one string
str =
(
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
)
str := StrReplace(str,"`n")
; comTable turns the command table string into an array
; comTableCapsCount creates an array with the count of capital values for each word
comTable := StrSplit(RegExReplace(str, "\s+", " "), " ")
comTableCapsCount := []
for cmds in comTable
comTableCapsCount.push(StrLen(RegExReplace(comTable[cmds], "[a-z]")))
; Take and process user input into an array of abbreviations
InputBox, abbrev, Command, Type in your command(s).`n If you have several commands`, leave spaces between them.
abbrev := Trim(abbrev)
StringLower, lowerCaseAbbrev, abbrev
abbrev := StrSplit(RegExReplace(abbrev, "\s+", " "), " ")
; Double loop compares abbreviations to commands in command table
Loop % abbrev.MaxIndex() {
count := A_Index
found := false
for cmds in comTable {
command := SubStr(comTable[cmds], 1, StrLen(abbrev[count]))
StringLower, lowerCaseCommand, command
if (lowerCaseCommand = abbrev[count]) and (StrLen(abbrev[count]) >= comTableCapsCount[cmds]) {
StringUpper, foundCmd, % comTable[cmds]
found := true
}
}
if (found)
result .= " " foundCmd
else
result .= " *error*"
}
MsgBox % Trim(result)
|
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity | Abelian sandpile model/Identity | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by adding numbers in corresponding grid areas,
so for the above:
1 2 0 2 1 3 3 3 3
s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2
0 1 3 0 1 0 0 2 3
If the addition would result in more than 3 "grains of sand" in any area then
those areas cause the whole sandpile to become "unstable" and the sandpile
areas are "toppled" in an "avalanche" until the "stable" result is obtained.
Any unstable area (with a number >= 4), is "toppled" by loosing one grain of
sand to each of its four horizontal or vertical neighbours. Grains are lost
at the edge of the grid, but otherwise increase the number in neighbouring
cells by one, whilst decreasing the count in the toppled cell by four in each
toppling.
A toppling may give an adjacent area more than four grains of sand leading to
a chain of topplings called an "avalanche".
E.g.
4 3 3 0 4 3 1 0 4 1 1 0 2 1 0
3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3
0 2 3 0 2 3 0 2 3 0 2 3 1 2 3
The final result is the stable sandpile on the right.
Note: The order in which cells are toppled does not affect the final result.
Task
Create a class or datastructure and functions to represent and operate on sandpiles.
Confirm the result of the avalanche of topplings shown above
Confirm that s1 + s2 == s2 + s1 # Show the stable results
If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:
2 1 2
1 0 1
2 1 2
Show that s3 + s3_id == s3
Show that s3_id + s3_id == s3_id
Show confirming output here, with your examples.
References
https://www.youtube.com/watch?v=1MtEUErz7Gg
https://en.wikipedia.org/wiki/Abelian_sandpile_model
| #11l | 11l | T Sandpile
DefaultDict[(Int, Int), Int] grid
F (gridtext)
V array = gridtext.split_py().map(x -> Int(x))
L(x) array
.grid[(L.index I/ 3, L.index % 3)] = x
Set[(Int, Int)] _border = Set(cart_product(-1 .< 4, -1 .< 4).filter((r, c) -> !(r C 0..2) | !(c C 0..2)))
_cell_coords = cart_product(0.<3, 0.<3)
F topple()
V& g = .grid
L(r, c) ._cell_coords
I g[(r, c)] >= 4
g[(r - 1, c)]++
g[(r + 1, c)]++
g[(r, c - 1)]++
g[(r, c + 1)]++
g[(r, c)] -= 4
R 1B
R 0B
F stabilise()
L .topple() {}
L(row_col) ._border.intersection(Set(.grid.keys()))
.grid.pop(row_col)
F ==(other)
R all(._cell_coords.map(row_col -> @.grid[row_col] == @other.grid[row_col]))
F +(other)
V ans = Sandpile(‘’)
L(row_col) ._cell_coords
ans.grid[row_col] = .grid[row_col] + other.grid[row_col]
ans.stabilise()
R ans
F String()
[String] txt
L(row) 3
txt.append((0.<3).map(col -> String(@.grid[(@row, col)])).join(‘ ’))
R txt.join("\n")
V unstable = Sandpile(‘4 3 3
3 1 2
0 2 3’)
V s1 = Sandpile(‘1 2 0
2 1 1
0 1 3’)
V s2 = Sandpile(‘2 1 3
1 0 1
0 1 0’)
V s3 = Sandpile(‘3 3 3 3 3 3 3 3 3’)
V s3_id = Sandpile(‘2 1 2 1 0 1 2 1 2’)
print(unstable)
print()
unstable.stabilise()
print(unstable)
print()
print(s1 + s2)
print()
print(s2 + s1)
print()
print(s1 + s2 == s2 + s1)
print()
print(s3 + s3_id)
print()
print(s3 + s3_id == s3)
print()
print(s3_id + s3_id)
print()
print(s3_id + s3_id == s3_id) |
http://rosettacode.org/wiki/Abstract_type | Abstract type | Abstract type is a type without instances or without definition.
For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called interfaces. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).
The term abstract datatype also may denote a type, with an implementation provided by the programmer rather than directly by the language (a built-in or an inferred type). Here the word abstract means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.
It is important not to confuse this abstractness (of implementation) with one of the abstract type. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.
In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have abstract types that are not OO related and are not an abstractness too. These are pure abstract types without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.
Task: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.
| #11l | 11l | T AbstractQueue
F.virtual.abstract enqueue(Int item) -> N
T PrintQueue(AbstractQueue)
F.virtual.assign enqueue(Int item) -> N
print(item) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #NewLISP | NewLISP |
#! /usr/local/bin/newlisp
(define (ackermann m n)
(cond ((zero? m) (inc n))
((zero? n) (ackermann (dec m) 1))
(true (ackermann (- m 1) (ackermann m (dec n))))))
|
http://rosettacode.org/wiki/Abelian_sandpile_model | Abelian sandpile model |
This page uses content from Wikipedia. The original article was at Abelian sandpile model. 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)
Implement the Abelian sandpile model also known as Bak–Tang–Wiesenfeld model. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it collapses, resulting in four particles being subtracted from the pile and distributed among its neighbors.
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
Examples:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| #Delphi | Delphi |
program Abelian_sandpile_model;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Vcl.Graphics,
System.Classes;
type
TGrid = array of array of Integer;
function Iterate(var Grid: TGrid): Boolean;
var
changed: Boolean;
i: Integer;
j: Integer;
val: Integer;
Alength: Integer;
begin
Alength := length(Grid);
changed := False;
for i := 0 to High(Grid) do
for j := 0 to High(Grid[0]) do
begin
val := Grid[i, j];
if val > 3 then
begin
Grid[i, j] := Grid[i, j] - 4;
if i > 0 then
Grid[i - 1, j] := Grid[i - 1, j] + 1;
if i < Alength - 1 then
Grid[i + 1, j] := Grid[i + 1, j] + 1;
if j > 0 then
Grid[i, j - 1] := Grid[i, j - 1] + 1;
if j < Alength - 1 then
Grid[i, j + 1] := Grid[i, j + 1] + 1;
changed := True;
end;
end;
Result := changed;
end;
procedure Simulate(var Grid: TGrid);
var
changed: Boolean;
begin
while Iterate(Grid) do
;
end;
procedure Zeros(var Grid: TGrid; Size: Integer);
var
i, j: Integer;
begin
SetLength(Grid, Size, Size);
for i := 0 to Size - 1 do
for j := 0 to Size - 1 do
Grid[i, j] := 0;
end;
procedure Println(Grid: TGrid);
var
i, j: Integer;
begin
for i := 0 to High(Grid) do
begin
Writeln;
for j := 0 to High(Grid[0]) do
Write(Format('%3d', [Grid[i, j]]));
end;
Writeln;
end;
function Grid2Bmp(Grid: TGrid): TBitmap;
const
Colors: array[0..2] of TColor = (clRed, clLime, clBlue);
var
Alength: Integer;
i: Integer;
j: Integer;
begin
Alength := Length(Grid);
Result := TBitmap.Create;
Result.SetSize(Alength, Alength);
for i := 0 to Alength - 1 do
for j := 0 to Alength - 1 do
begin
Result.Canvas.Pixels[i, j] := Colors[Grid[i, j]];
end;
end;
procedure Grid2P6(Grid: TGrid; FileName: TFileName);
var
f: text;
i, j, Alength: Integer;
ppm: TFileStream;
Header: AnsiString;
const
COLORS: array[0..3] of array[0..2] of byte =
// R, G, B
((0 , 0, 0),
(255 , 0, 0),
(0 , 255, 0),
(0 , 0, 255));
begin
Alength := Length(Grid);
ppm := TFileStream.Create(FileName, fmCreate);
Header := Format('P6'#10'%d %d'#10'255'#10, [Alength, Alength]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
for i := 0 to Alength - 1 do
for j := 0 to Alength - 1 do
begin
ppm.Write(COLORS[Grid[i, j]], 3);
end;
ppm.Free;
end;
const
DIMENSION = 10;
var
Grid: TGrid;
bmp: TBitmap;
begin
Zeros(Grid, DIMENSION);
Grid[4, 4] := 64;
Writeln('Before:');
Println(Grid);
Simulate(Grid);
Writeln(#10'After:');
Println(Grid);
// Output bmp
with Grid2Bmp(Grid) do
begin
SaveToFile('output.bmp');
free;
end;
// Output ppm
Grid2P6(Grid, 'output.ppm');
Readln;
end.
|
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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 <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
// cmd is assumed to be all uppercase
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
// str is assumed to be all uppercase
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
// convert string to uppercase
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
// if there's an integer following this word, it specifies the minimum
// length for the command, otherwise the minimum length is the length
// of the command string
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
} |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
A valid abbreviation is a word that has:
at least the minimum length of the number of capital letters of the word in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTer
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTer
The number of capital letters in ALTer indicates that any abbreviation for ALTer must be at least three letters
Any word longer than five characters can't be an abbreviation for ALTer
o, ov, oVe, over, overL, overla are all acceptable abbreviations for Overlay
if there isn't any lowercase letters in the word in the command table, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
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 | #!/usr/bin/awk -f
BEGIN {
FS=" ";
split(" Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy" \
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find" \
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput" \
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO" \
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT" \
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT" \
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up" \
, CMD);
for (k=1; k <= length(CMD); k++) {
cmd[k] = CMD[k];
sub(/[a-z]*$/,"",cmd[k]);
# print "0: ",CMD[k],"\t",cmd[k];
}
}
function GET_ABBR(input) {
for (k2=1; k2<=length(CMD); k2++) {
if (index(toupper(CMD[k2]),input)==1) {
if (index(input,toupper(cmd[k2]))==1) {
return toupper(CMD[k2]);
}
}
}
return "*error*";
}
{
R="";
for (k1=1; k1 <= NF; k1++) {
R=R" "GET_ABBR(toupper($k1))
}
print R;
}
|
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity | Abelian sandpile model/Identity | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by adding numbers in corresponding grid areas,
so for the above:
1 2 0 2 1 3 3 3 3
s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2
0 1 3 0 1 0 0 2 3
If the addition would result in more than 3 "grains of sand" in any area then
those areas cause the whole sandpile to become "unstable" and the sandpile
areas are "toppled" in an "avalanche" until the "stable" result is obtained.
Any unstable area (with a number >= 4), is "toppled" by loosing one grain of
sand to each of its four horizontal or vertical neighbours. Grains are lost
at the edge of the grid, but otherwise increase the number in neighbouring
cells by one, whilst decreasing the count in the toppled cell by four in each
toppling.
A toppling may give an adjacent area more than four grains of sand leading to
a chain of topplings called an "avalanche".
E.g.
4 3 3 0 4 3 1 0 4 1 1 0 2 1 0
3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3
0 2 3 0 2 3 0 2 3 0 2 3 1 2 3
The final result is the stable sandpile on the right.
Note: The order in which cells are toppled does not affect the final result.
Task
Create a class or datastructure and functions to represent and operate on sandpiles.
Confirm the result of the avalanche of topplings shown above
Confirm that s1 + s2 == s2 + s1 # Show the stable results
If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:
2 1 2
1 0 1
2 1 2
Show that s3 + s3_id == s3
Show that s3_id + s3_id == s3_id
Show confirming output here, with your examples.
References
https://www.youtube.com/watch?v=1MtEUErz7Gg
https://en.wikipedia.org/wiki/Abelian_sandpile_model
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program abelianSum64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 3
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessValue: .asciz "@ "
szMessAdd1: .asciz "Add sandpile 1 to sandpile 2 \n"
szMessAdd2: .asciz "Add sandpile 2 to sandpile 1 \n"
szMessAdd2A: .asciz "Add sandpile 2A to sandpile result \n"
szMessAdd3: .asciz "Add sandpile 3 to sandpile 3ID \n"
szMessAdd3ID: .asciz "Add sandpile 3ID to sandpile 3ID \n"
szCarriageReturn: .asciz "\n"
qSandPile1: .quad 1,2,0
.quad 2,1,1
.quad 0,1,3
qSandPile2: .quad 2,1,3
.quad 1,0,1
.quad 0,1,0
qSandPile2A: .quad 1,0,0
.quad 0,0,0
.quad 0,0,0
qSandPile3: .quad 3,3,3
.quad 3,3,3
.quad 3,3,3
qSandPile3ID: .quad 2,1,2
.quad 1,0,1
.quad 2,1,2
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
qSandPilex1: .skip 8 * MAXI * MAXI
qSandPilex2: .skip 8 * MAXI * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrqSandPile1 // sandpile1 address
ldr x1,qAdrqSandPile2 // sandpile2 address
ldr x2,qAdrqSandPilex1 // sandpile result address
bl addSandPile
ldr x0,qAdrszMessAdd1 // display message
bl affichageMess
ldr x0,qAdrqSandPilex1 // display sandpile
bl displaySandPile
ldr x0,qAdrqSandPile2 // sandpile2 address
ldr x1,qAdrqSandPile1 // sandpile1 address
ldr x2,qAdrqSandPilex1 // sandpile result address
bl addSandPile
ldr x0,qAdrszMessAdd2
bl affichageMess
ldr x0,qAdrqSandPilex1
bl displaySandPile
ldr x0,qAdrqSandPilex1 // sandpile1 address
ldr x1,qAdrqSandPile2A // sandpile2A address
ldr x2,qAdrqSandPilex2 // sandpile result address
bl addSandPile
ldr x0,qAdrszMessAdd2A
bl affichageMess
ldr x0,qAdrqSandPilex2
bl displaySandPile
ldr x0,qAdrqSandPile3 // sandpile3 address
ldr x1,qAdrqSandPile3ID // sandpile3ID address
ldr x2,qAdrqSandPilex2 // sandpile result address
bl addSandPile
ldr x0,qAdrszMessAdd3
bl affichageMess
ldr x0,qAdrqSandPilex2
bl displaySandPile
ldr x0,qAdrqSandPile3ID // sandpile3 address
ldr x1,qAdrqSandPile3ID // sandpile3ID address
ldr x2,qAdrqSandPilex2 // sandpile result address
bl addSandPile
ldr x0,qAdrszMessAdd3ID
bl affichageMess
ldr x0,qAdrqSandPilex2
bl displaySandPile
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessAdd1: .quad szMessAdd1
qAdrszMessAdd2: .quad szMessAdd2
qAdrszMessAdd2A: .quad szMessAdd2A
qAdrszMessAdd3: .quad szMessAdd3
qAdrszMessAdd3ID: .quad szMessAdd3ID
qAdrqSandPile1: .quad qSandPile1
qAdrqSandPilex1: .quad qSandPilex1
qAdrqSandPilex2: .quad qSandPilex2
qAdrqSandPile2: .quad qSandPile2
qAdrqSandPile2A: .quad qSandPile2A
qAdrqSandPile3: .quad qSandPile3
qAdrqSandPile3ID: .quad qSandPile3ID
/***************************************************/
/* add two sandpile */
/***************************************************/
// x0 contains address to sandpile 1
// x1 contains address to sandpile 2
// x2 contains address to sandpile result
addSandPile:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x6,x1 // save addresse sandpile2
mov x1,x2 // and copy sandpile 1 to sandpile result
bl copySandPile
mov x0,x2 // sanspile result
mov x2,#0 // indice y
mov x4,#MAXI
1:
mov x1,#0 // indice x
2:
madd x5,x2,x4,x1 // compute offset
ldr x7,[x0,x5,lsl #3] // load value at pos x,y sanspile result
ldr x3,[x6,x5,lsl #3] // load value at pos x,y sandpile 2
add x7,x7,x3
str x7,[x0,x5,lsl #3] // store sum on sandpile result
bl avalancheRisk
add x1,x1,#1
cmp x1,#MAXI
blt 2b
add x2,x2,#1
cmp x2,#MAXI
blt 1b
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* copy sandpile */
/***************************************************/
// x0 contains address to sandpile
// x1 contains address to sandpile result
copySandPile:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x2,#0 // indice y
mov x3,#MAXI
1:
mov x4,#0 // indice x
2:
madd x5,x2,x3,x4 // compute offset
ldr x6,[x0,x5,lsl #3] // load value at pos x,y sanspile
str x6,[x1,x5,lsl #3] // store value at pos x,y sandpile result
add x4,x4,#1
cmp x4,#MAXI
blt 2b
add x2,x2,#1
cmp x2,#MAXI
blt 1b
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* display sandpile */
/***************************************************/
// x0 contains address to sandpile
displaySandPile:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x6,x0
mov x3,#0 // indice y
mov x4,#MAXI
1:
mov x2,#0 // indice x
2:
madd x5,x3,x4,x2 // compute offset
ldr x0,[x6,x5,lsl #3] // load value at pos x,y
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
add x1,x1,#1
mov x7,#0
strb w7,[x1,x0]
ldr x0,qAdrszMessValue
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
bl affichageMess
add x2,x2,#1
cmp x2,#MAXI
blt 2b
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x3,x3,#1
cmp x3,#MAXI
blt 1b
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessValue: .quad szMessValue
/***************************************************/
/* avalanche risk */
/***************************************************/
// x0 contains address to sanspile
// x1 contains position x
// x2 contains position y
avalancheRisk:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x3,#MAXI
madd x4,x3,x2,x1
ldr x5,[x0,x4,lsl #3]
1:
cmp x5,#4 // 4 grains ?
blt 100f
sub x5,x5,#4 // yes sustract
str x5,[x0,x4,lsl #3]
cmp x1,#MAXI-1 // right position ok ?
beq 2f
add x1,x1,#1 // yes
bl add1Sand // add 1 grain
bl avalancheRisk // and compute new pile
sub x1,x1,#1
2:
cmp x1,#0 // left position ok ?
beq 3f
sub x1,x1,#1
bl add1Sand
bl avalancheRisk
add x1,x1,#1
3:
cmp x2,#0 // higt position ok ?
beq 4f
sub x2,x2,#1
bl add1Sand
bl avalancheRisk
add x2,x2,#1
4:
cmp x2,#MAXI-1 // low position ok ?
beq 5f
add x2,x2,#1
bl add1Sand
bl avalancheRisk
sub x2,x2,#1
5:
ldr x5,[x0,x4,lsl #3] // reload value
b 1b // and loop
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* add 1 grain of sand */
/***************************************************/
// x0 contains address to sanspile
// x1 contains position x
// x2 contains position y
add1Sand:
stp x3,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x3,#MAXI
madd x4,x3,x2,x1
ldr x5,[x0,x4,lsl #3] // load value at pos x,y
add x5,x5,#1
str x5,[x0,x4,lsl #3] // and store
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x3,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Abstract_type | Abstract type | Abstract type is a type without instances or without definition.
For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called interfaces. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).
The term abstract datatype also may denote a type, with an implementation provided by the programmer rather than directly by the language (a built-in or an inferred type). Here the word abstract means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.
It is important not to confuse this abstractness (of implementation) with one of the abstract type. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.
In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have abstract types that are not OO related and are not an abstractness too. These are pure abstract types without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.
Task: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.
| #AArch64_Assembly | AArch64 Assembly | class abs definition abstract.
public section.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
protected section.
methods method2 abstract importing iv_name type string exporting ev_ret type i.
methods add importing iv_a type i iv_b type i exporting ev_ret type i.
endclass.
class abs implementation.
method add.
ev_ret = iv_a + iv_b.
endmethod.
endclass. |
Subsets and Splits