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/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.
| #Nim | Nim | from strutils import parseInt
proc ackermann(m, n: int64): int64 =
if m == 0:
result = n + 1
elif n == 0:
result = ackermann(m - 1, 1)
else:
result = ackermann(m - 1, ackermann(m, n - 1))
proc getNumber(): int =
try:
result = stdin.readLine.parseInt
except ValueError:
echo "An integer, please!"
result = getNumber()
if result < 0:
echo "Please Enter a non-negative Integer: "
result = getNumber()
echo "First non-negative Integer please: "
let first = getNumber()
echo "Second non-negative Integer please: "
let second = getNumber()
echo "Result: ", $ackermann(first, second)
|
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
| #Forth | Forth | #! /usr/bin/gforth -d 20M
\ Abelian Sandpile Model
0 assert-level !
\ command-line
: parse-number s>number? invert throw drop ;
: parse-size ." size : " next-arg parse-number dup . cr ;
: parse-height ." height: " next-arg parse-number dup . cr ;
: parse-args cr parse-size parse-height ;
parse-args constant HEIGHT constant SIZE
: allot-erase create here >r dup allot r> swap erase ;
: size^2 SIZE dup * cells ;
: 2cells [ 2 cells ] literal ;
: -2cells [ 2cells negate ] literal ;
size^2 allot-erase arr
\ array processing
: ix swap SIZE * + cells arr + ;
: center SIZE 2/ dup ;
: write-cell ix @ u. ;
: write-row SIZE 0 ?do dup i write-cell loop drop cr ;
: arr. SIZE 0 ?do i write-row loop ;
\ stack processing
: stack-empty? dup -1 = ;
: stack-full? stack-empty? invert ;
\ pgm-handling
: concat { a1 l1 a2 l2 } l1 l2 + allocate throw dup dup a1 swap l1 cmove a2 swap l1 + l2 cmove l1 l2 + ;
: write-pgm ." P2" cr SIZE u. SIZE u. cr ." 3" cr arr. ;
: u>s 0 <# #s #> ;
: filename s" sandpile-" SIZE u>s concat s" -" concat HEIGHT u>s concat s" .pgm" concat ;
: to-pgm filename w/o create-file throw ['] write-pgm over outfile-execute close-file throw ;
\ sandpile
: prep-arr HEIGHT center ix ! ;
: prep-stack -1 HEIGHT 4 u>= if center then ;
: prepare prep-arr prep-stack ;
: ensure if else 2drop 0 2rdrop exit then ;
: col>=0 dup 0>= ensure ;
: col<SIZE dup SIZE < ensure ;
: row>=0 over 0>= ensure ;
: row<SIZE over SIZE < ensure ;
: legal? col>=0 col<SIZE row>=0 row<SIZE 2drop true ;
: north 1. d- ;
: east 1+ ;
: south 1. d+ ;
: west 1- ;
: reduce 2dup ix dup -4 swap +! @ 4 < if 2drop then ;
: increase 2dup legal? if 2dup ix dup 1 swap +! @ 4 = if 2swap else 2drop then else 2drop then ;
: inc-north 2dup north increase ;
: inc-east 2dup east increase ;
: inc-south 2dup south increase ;
: inc-west 2dup west increase ;
: inc-all inc-north inc-east inc-south inc-west 2drop ;
: simulate prepare begin stack-full? while 2dup 2>r reduce 2r> inc-all repeat drop to-pgm ." written to " filename type cr ;
simulate bye |
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
| #Fortran | Fortran | module abelian_sandpile_m
implicit none
private
public :: pile
type :: pile
!! usage:
!! 1) init
!! 2) run
integer, allocatable :: grid(:,:)
integer :: n(2)
contains
procedure :: init
procedure :: run
procedure, private :: process_node
procedure, private :: inside
end type
contains
logical function inside(this, i)
class(pile), intent(in) :: this
integer, intent(in) :: i(2)
inside = ((i(1) > 0) .and. (i(1) <= this%n(1)) .and. (i(2) > 0) .and. (i(2) <= this%n(2)) )
end function
recursive subroutine process_node(this, i)
!! start process
class(pile), intent(inout) :: this
integer, intent(in) :: i(2)
!! node coordinates to process
integer :: i0(2,2), j(2), d, k
! if node has more than 4 grains -> redistribute
if (this%grid(i(1),i(2)) >= 4) then
! unit vectors: help shift only one dimension (see below)
i0 = reshape([1,0,0,1], [2,2])
! subtract 4 grains
this%grid(i(1),i(2)) = this%grid(i(1),i(2))-4
! add one grain to neighbor if not out of bound
do d = 1, 2 ! loop dimensions
do k = -1, 1, 2 ! loop +-1 step in direction d
j = i+k*i0(:,d) ! j = i, but one element is shifted by +-1
if (this%inside(j)) this%grid(j(1),j(2)) = this%grid(j(1),j(2)) + 1
end do
end do
! check neighbor nodes
do d = 1, 2 ! loop dimensions
do k = -1, 1, 2 ! loop +-1 step in direction d
j = i+k*i0(:,d) ! j = i, but one element is shifted by +-1
if (this%inside(j)) call this%process_node(j)
end do
end do
! check itself
call this%process_node(i)
end if
end subroutine
subroutine run(this)
!! start process
class(pile), intent(inout) :: this
! only node that could be unstable is inital node
call this%process_node(this%n/2)
end subroutine
subroutine init(this, nx, ny, h)
class(pile), intent(out) :: this
integer, intent(in) :: nx, ny
!! grid dimensions
integer, intent(in) :: h
!! height of and grains in middle of grid
this%n = [nx, ny]
allocate (this%grid(nx,ny), source=0)
this%grid(nx/2, ny/2) = h
end subroutine
end module |
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
| #Clojure | Clojure |
(defn words
"Split string into words"
[^String str]
(.split (.stripLeading str) "\\s+"))
(defn join-words
"Join words into a single string"
^String [strings]
(String/join " " strings))
;; SOURCE: https://www.stackoverflow.com/a/38947571/12947681
(defn starts-with-ignore-case
"Does string start with prefix (ignoring case)?"
^Boolean [^String string, ^String prefix]
(.regionMatches string true 0 prefix 0 (count prefix)))
(defrecord CommandWord [^String word, ^long min-abbr-size])
(defn parse-cmd-table
"Parse list of strings in command table into list of words and numbers
If number is missing for any word, then the word is not included"
([cmd-table]
(parse-cmd-table cmd-table 0 []))
([cmd-table i ans]
(let [cmd-count (count cmd-table)]
(if (= i cmd-count)
ans
(let [word (nth cmd-table i),
[i num] (try [(+ i 2)
(Integer/parseInt ^String (nth cmd-table (inc i)))]
(catch NumberFormatException _
[(inc i) 0]))]
(recur cmd-table i (conj ans (CommandWord. word num))))))))
;; cmd-table is a list of objects of type CommandWord (defined above)
(def cmd-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"
words
parse-cmd-table))
(defn abbr?
"Is abbr a valid abbreviation of this command?"
^Boolean [^String abbr, ^CommandWord cmd]
(let [{:keys [word min-abbr-size]} cmd]
(and (<= min-abbr-size (count abbr) (count word))
(starts-with-ignore-case word abbr))))
(defn solution
"Find word matching each abbreviation in input (or *error* if not found),
and join results into a string"
^String [^String str]
(join-words (for [abbr (words str)]
(if-let [{:keys [word]} (first (filter #(abbr? abbr %) cmd-table))]
(.toUpperCase ^String word)
"*error*"))))
;; Print solution for given test case
(println (solution "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
| #C | C | #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* 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";
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;
}
size_t get_min_length(const char* str, size_t n) {
size_t len = 0;
while (len < n && isupper((unsigned char)str[len]))
++len;
return len;
}
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 = get_min_length(word, word_len);
new_cmd->cmd = uppercase(word, word_len);
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/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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program abelianSum.s */
/* 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, 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"
szMessFin: .asciz "End display :\n"
szCarriageReturn: .asciz "\n"
iSandPile1: .int 1,2,0
.int 2,1,1
.int 0,1,3
iSandPile2: .int 2,1,3
.int 1,0,1
.int 0,1,0
iSandPile2A: .int 1,0,0
.int 0,0,0
.int 0,0,0
iSandPile3: .int 3,3,3
.int 3,3,3
.int 3,3,3
iSandPile3ID: .int 2,1,2
.int 1,0,1
.int 2,1,2
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
iSandPileR1: .skip 4 * MAXI * MAXI
iSandPileR2: .skip 4 * MAXI * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdriSandPile1 @ sandpile1 address
ldr r1,iAdriSandPile2 @ sandpile2 address
ldr r2,iAdriSandPileR1 @ sandpile result address
bl addSandPile
ldr r0,iAdrszMessAdd1 @ display message
bl affichageMess
ldr r0,iAdriSandPileR1 @ display sandpile
bl displaySandPile
ldr r0,iAdriSandPile2 @ sandpile2 address
ldr r1,iAdriSandPile1 @ sandpile1 address
ldr r2,iAdriSandPileR1 @ sandpile result address
bl addSandPile
ldr r0,iAdrszMessAdd2
bl affichageMess
ldr r0,iAdriSandPileR1
bl displaySandPile
ldr r0,iAdriSandPileR1 @ sandpile1 address
ldr r1,iAdriSandPile2A @ sandpile2A address
ldr r2,iAdriSandPileR2 @ sandpile result address
bl addSandPile
ldr r0,iAdrszMessAdd2A
bl affichageMess
ldr r0,iAdriSandPileR2
bl displaySandPile
ldr r0,iAdriSandPile3 @ sandpile3 address
ldr r1,iAdriSandPile3ID @ sandpile3ID address
ldr r2,iAdriSandPileR2 @ sandpile result address
bl addSandPile
ldr r0,iAdrszMessAdd3
bl affichageMess
ldr r0,iAdriSandPileR2
bl displaySandPile
ldr r0,iAdriSandPile3ID @ sandpile3 address
ldr r1,iAdriSandPile3ID @ sandpile3ID address
ldr r2,iAdriSandPileR2 @ sandpile result address
bl addSandPile
ldr r0,iAdrszMessAdd3ID
bl affichageMess
ldr r0,iAdriSandPileR2
bl displaySandPile
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
iAdrszMessFin: .int szMessFin
iAdrszMessAdd1: .int szMessAdd1
iAdrszMessAdd2: .int szMessAdd2
iAdrszMessAdd2A: .int szMessAdd2A
iAdrszMessAdd3: .int szMessAdd3
iAdrszMessAdd3ID: .int szMessAdd3ID
iAdriSandPile1: .int iSandPile1
iAdriSandPileR1: .int iSandPileR1
iAdriSandPileR2: .int iSandPileR2
iAdriSandPile2: .int iSandPile2
iAdriSandPile2A: .int iSandPile2A
iAdriSandPile3: .int iSandPile3
iAdriSandPile3ID: .int iSandPile3ID
/***************************************************/
/* add two sandpile */
/***************************************************/
// r0 contains address to sandpile 1
// r1 contains address to sandpile 2
// r2 contains address to sandpile result
addSandPile:
push {r1-r7,lr} @ save registers
mov r6,r1 @ save addresse sandpile2
mov r1,r2 @ and copy sandpile 1 to sandpile result
bl copySandPile
mov r0,r2 @ sanspile result
mov r2,#0 @ indice y
mov r4,#MAXI
1:
mov r1,#0 @ indice x
2:
mla r5,r2,r4,r1 @ compute offset
ldr r7,[r0,r5,lsl #2] @ load value at pos x,y sanspile result
ldr r3,[r6,r5,lsl #2] @ load value at pos x,y sandpile 2
add r7,r3
str r7,[r0,r5,lsl #2] @ store sum on sandpile result
bl avalancheRisk
add r1,r1,#1
cmp r1,#MAXI
blt 2b
add r2,r2,#1
cmp r2,#MAXI
blt 1b
100:
pop {r1-r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* copy sandpile */
/***************************************************/
// r0 contains address to sandpile
// r1 contains address to sandpile result
copySandPile:
push {r1-r6,lr} @ save registers
mov r2,#0 @ indice y
mov r3,#MAXI
1:
mov r4,#0 @ indice x
2:
mla r5,r2,r3,r4 @ compute offset
ldr r6,[r0,r5,lsl #2] @ load value at pos x,y sanspile
str r6,[r1,r5,lsl #2] @ store value at pos x,y sandpile result
add r4,r4,#1
cmp r4,#MAXI
blt 2b
add r2,r2,#1
cmp r2,#MAXI
blt 1b
100:
pop {r1-r6,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* 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
/***************************************************/
/* avalanche risk */
/***************************************************/
// r0 contains address to sanspile
// r1 contains position x
// r2 contains position y
avalancheRisk:
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 avalancheRisk @ and compute new pile
sub r1,#1
2:
cmp r1,#0 @ left position ok ?
beq 3f
sub r1,#1
bl add1Sand
bl avalancheRisk
add r1,#1
3:
cmp r2,#0 @ higt position ok ?
beq 4f
sub r2,#1
bl add1Sand
bl avalancheRisk
add r2,#1
4:
cmp r2,#MAXI-1 @ low position ok ?
beq 5f
add r2,#1
bl add1Sand
bl avalancheRisk
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/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.
| #ABAP | ABAP | 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. |
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.
| #Nit | Nit | # Task: Ackermann function
#
# A simple straightforward recursive implementation.
module ackermann_function
fun ack(m, n: Int): Int
do
if m == 0 then return n + 1
if n == 0 then return ack(m-1,1)
return ack(m-1, ack(m, n-1))
end
for m in [0..3] do
for n in [0..6] do
print ack(m,n)
end
print ""
end |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
// Abelian sandpile model. Nigel Galloway: July 20th., 2020
type Sandpile(x,y,N:int[])=
member private this.x=x
member private this.y=y
member private this.i=let rec topple n=match Array.tryFindIndex(fun n->n>3)n with
None->n
|Some g->let i=n.[g]/4
n.[g]<-n.[g]%4
match g%x,g/x with
(0,0)->n.[x]<-n.[x]+i;n.[1]<-n.[1]+i;topple n
|(α,0) when α=x-1->n.[g+x]<-n.[g+x]+i;n.[g-1]<-n.[g-1]+i;topple n
|(_,0)->n.[g-1]<-n.[g-1]+i;n.[g+1]<-n.[g+1]+i;n.[g+x]<-n.[g+x]+i;topple n
|(0,β) when β=y-1->n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;topple n
|(0,β)->n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;n.[g+x]<-n.[g+x]+i;topple n
|(α,β) when α=x-1 && β=y-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;topple n
|(α,_) when α=x-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+x]<-n.[g+x]+i;topple n
|(_,β) when β=y-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;topple n
|_->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+x]<-n.[g+x]+i;n.[g+1]<-n.[g+1]+i;topple n
topple N
static member (+) (n:Sandpile, g:Sandpile)=Sandpile(n.x,n.y,Array.map2(fun n g->n+g) n.i g.i)
member this.toS=sprintf "%A" (this.i|>Array.chunkBySize x|>array2D)
printfn "%s\n" (Sandpile(3,3,[|4;3;3;3;1;2;0;2;3|])).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-4; printfn "%s\n" (Sandpile(5,5,e1)).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-6; printfn "%s\n" (Sandpile(5,5,e1)).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-16; printfn "%s\n" (Sandpile(5,5,e1)).toS
|
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
| #Crystal | Crystal | 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"
def parse_command_table(input : String)
cmds = {} of String => String
table = input.strip.split
word = table[0].upcase
table.each do |item|
if /[0-9]+/.match(item)
abbreviation_length = item.to_i
(0..word.size-abbreviation_length).each do |i|
cmds[word[(0..abbreviation_length-1+i)]] = word
end
else
word = item.upcase
cmds[word] = word
end
end
return cmds
end
def parse_user_input(input : String?, commands)
output = ""
unless input.nil?
user_commands = input.strip.split
user_commands.each do |command|
command = command.upcase
if commands.has_key?(command)
output += commands[command]
else
output += "*error*"
end
output += " "
end
end
return output
end
cmds = parse_command_table(COMMAND_TABLE)
puts "Input:"
user_input = gets
puts "Output:"
puts parse_user_input(user_input, cmds)
|
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
| #C.2B.2B | C++ | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* 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";
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;
}
// 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); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
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::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
// count leading uppercase characters
size_t len = get_min_length(word);
// then convert to uppercase
uppercase(word);
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/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
| #Ada | Ada | -- Works with Ada 2012
package Abelian_Sandpile is
Limit : constant Integer := 4;
type Sandpile is array (0 .. 2, 0 .. 2) of Natural with
Default_Component_Value => 0;
procedure Stabalize (Pile : in out Sandpile);
function Is_Stable (Pile : in Sandpile) return Boolean;
procedure Topple (Pile : in out Sandpile);
function "+" (Left, Right : Sandpile) return Sandpile;
procedure Print(PIle : in Sandpile);
end Abelian_Sandpile;
|
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.
| #ActionScript | ActionScript | package
{
public interface IInterface
{
function method1():void;
function method2(arg1:Array, arg2:Boolean):uint;
}
} |
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.
| #Ada | Ada | type Queue is limited interface;
procedure Enqueue (Lounge : in out Queue; Item : in out Element) is abstract;
procedure Dequeue (Lounge : in out Queue; Item : in out Element) is abstract; |
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.
| #Oberon-2 | Oberon-2 | MODULE ackerman;
IMPORT Out;
VAR m, n : INTEGER;
PROCEDURE Ackerman (x, y : INTEGER) : INTEGER;
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
Out.Int (Ackerman (m, n), 10);
Out.Char (9X)
END;
Out.Ln
END;
Out.Ln
END ackerman. |
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
| #F.23 | F# |
// Abelian sandpile model. Nigel Galloway: July 20th., 2020
type Sandpile(x,y,N:int[])=
member private this.x=x
member private this.y=y
member private this.i=let rec topple n=match Array.tryFindIndex(fun n->n>3)n with
None->n
|Some g->let i=n.[g]/4
n.[g]<-n.[g]%4
match g%x,g/x with
(0,0)->n.[x]<-n.[x]+i;n.[1]<-n.[1]+i;topple n
|(α,0) when α=x-1->n.[g+x]<-n.[g+x]+i;n.[g-1]<-n.[g-1]+i;topple n
|(_,0)->n.[g-1]<-n.[g-1]+i;n.[g+1]<-n.[g+1]+i;n.[g+x]<-n.[g+x]+i;topple n
|(0,β) when β=y-1->n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;topple n
|(0,β)->n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;n.[g+x]<-n.[g+x]+i;topple n
|(α,β) when α=x-1 && β=y-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;topple n
|(α,_) when α=x-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+x]<-n.[g+x]+i;topple n
|(_,β) when β=y-1->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+1]<-n.[g+1]+i;topple n
|_->n.[g-1]<-n.[g-1]+i;n.[g-x]<-n.[g-x]+i;n.[g+x]<-n.[g+x]+i;n.[g+1]<-n.[g+1]+i;topple n
topple N
static member (+) (n:Sandpile, g:Sandpile)=Sandpile(n.x,n.y,Array.map2(fun n g->n+g) n.i g.i)
member this.toS=sprintf "%A" (this.i|>Array.chunkBySize x|>array2D)
printfn "%s\n" (Sandpile(3,3,[|4;3;3;3;1;2;0;2;3|])).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-4; printfn "%s\n" (Sandpile(5,5,e1)).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-6; printfn "%s\n" (Sandpile(5,5,e1)).toS
let e1=Array.zeroCreate<int> 25 in e1.[12]<-16; printfn "%s\n" (Sandpile(5,5,e1)).toS
|
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
| #D | D | class Abbreviations
{
import std.array: split, join;
import std.uni:toUpper;
string[string] replaces;
this(string table)
{
import std.ascii;
import std.conv:parse;
string saved;
auto add = (string word){ if(word.length) replaces[word] = word; };
foreach(word; table.toUpper.split)
if(isDigit(word[0]))
{
for(int length=parse!int(word); length<=saved.length; ++length)
replaces[saved[0..length]] = saved;
} else
{
add(saved);
saved = word;
}
add(saved);
}
string expand(string input) // pre-filled hashtable is used
{
import std.algorithm: map;
return input.toUpper.split.map!(word => word in replaces ? replaces[word] : "*error*").join(" ");
}
}
string 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";
string input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
string expected = "RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT";
unittest // 'dmd -unittest ...' to activate it
{
auto expander = new Abbreviations(table);
assert(expander.expand(input) == expected);
assert(expander.expand("") == "");
assert(expander.expand("addadd") == "*error*");
}
void main()
{
import std.stdio:writeln;
writeln("Input : ", input);
writeln("Output: ", new Abbreviations(table).expand(input));
}
|
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
| #Clojure | Clojure |
(defn words [str]
"Split string into words"
(.split str "\\s+"))
(defn join-words [strings]
"Join words into a single string"
(clojure.string/join " " strings))
(def cmd-table
"Command Table - List of words to match against"
(words
"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"))
; TODO - cache word properties
(defn abbr-valid?
"Is abbr abbreviation of word?"
[abbr word]
(and (.startsWith (.toLowerCase word) (.toLowerCase abbr))
(<= (count (filter #(Character/isUpperCase %) word))
(count abbr)
(count word))))
(defn find-word-for-abbr
"Find first word matching abbreviation, or nil if not found"
[abbr]
(first (filter #(abbr-valid? abbr %) cmd-table)))
(defn solution
"Find word matching each abbreviation in input (or *error* if not found),
and join results into a string"
[str]
(join-words (for [abbr (words str)]
(if-let [word (find-word-for-abbr abbr)]
(.toUpperCase word)
"*error*"))))
;; Example Input
(print (solution "riG rePEAT copies put mo rest types fup. 6 poweRin"))
|
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
| #ALGOL_68 | ALGOL 68 | BEGIN # model Abelian sandpiles #
# represents a sandpile #
INT elements = 3;
MODE SANDPILE = [ 1 : elements, 1 : elements ]INT;
# returns TRUE if the sandpiles a and b have the same values, FALSE otherwise #
OP = = ( SANDPILE a, b )BOOL:
BEGIN
BOOL result := TRUE;
FOR i TO elements WHILE result DO
FOR j TO elements WHILE ( result := a[ i, j ] = b[ i, j ] ) DO SKIP OD
OD;
result
END # = # ;
# returns TRUE if the sandpile s is stable, FALSE otherwise #
OP STABLE = ( SANDPILE s )BOOL:
BEGIN
BOOL result := TRUE;
FOR i TO elements WHILE result DO
FOR j TO elements WHILE result := s[ i, j ] < 4 DO SKIP OD
OD;
result
END # STABLE # ;
# returns the sandpile s after avalanches #
OP AVALANCHE = ( SANDPILE s )SANDPILE:
BEGIN
SANDPILE result := s;
WHILE BOOL had avalanche := FALSE;
FOR i TO elements DO
FOR j TO elements DO
IF result[ i, j ] >= 4 THEN
# unstable pile #
had avalanche := TRUE;
result[ i, j ] -:= 4;
IF i > 1 THEN result[ i - 1, j ] +:= 1 FI;
IF i < elements THEN result[ i + 1, j ] +:= 1 FI;
IF j > 1 THEN result[ i, j - 1 ] +:= 1 FI;
IF j < elements THEN result[ i, j + 1 ] +:= 1 FI
FI
OD
OD;
had avalanche
DO SKIP OD;
result
END # AVALANCHE # ;
# returns the result of adding the sandpile b to a, handling avalanches #
OP + = ( SANDPILE a, b )SANDPILE:
BEGIN
SANDPILE result;
FOR i TO elements DO
FOR j TO elements DO result[ i, j ] := a[ i, j ] + b[ i, j ] OD
OD;
# handle avalanches #
AVALANCHE result
END # + # ;
# prints the sandpile s #
PROC show sandpile = ( STRING title, SANDPILE s )VOID:
BEGIN
print( ( title, newline ) );
FOR i TO elements DO
FOR j TO elements DO
print( ( " ", whole( s[ i, j ], 0 ) ) )
OD;
print( ( newline ) )
OD
END # show sandpile # ;
# task test cases #
SANDPILE us = ( ( 4, 3, 3 )
, ( 3, 1, 2 )
, ( 0, 2, 3 )
);
SANDPILE s1 = ( ( 1, 2, 0 )
, ( 2, 1, 1 )
, ( 0, 1, 3 )
);
SANDPILE s2 = ( ( 2, 1, 3 )
, ( 1, 0, 1 )
, ( 0, 1, 0 )
);
SANDPILE s3 = ( ( 3, 3, 3 )
, ( 3, 3, 3 )
, ( 3, 3, 3 )
);
SANDPILE s3_id = ( ( 2, 1, 2 )
, ( 1, 0, 1 )
, ( 2, 1, 2 )
);
SANDPILE t := us;
WHILE NOT STABLE t DO
show sandpile( "unstable:", t );
t := AVALANCHE t
OD;
show sandpile( "stable: ", t );
print( ( newline ) );
show sandpile( "s1:", s1 );
show sandpile( "s2:", s2 );
show sandpile( "s1 + s2:", s1 + s2 );
show sandpile( "s2 + s1:", s2 + s1 );
print( ( newline ) );
show sandpile( "s3:", s3 );
show sandpile( "s3_id:", s3_id );
print( ( newline ) );
print( ( "s3 + s3_id = s3 is ", IF s3 + s3_id = s3 THEN "TRUE" ELSE "FALSE" FI, newline ) );
show sandpile( "s3 + s3_id", s3 + s3_id );
print( ( "s3_id + s3 = s3 is ", IF s3 + s3_id = s3 THEN "TRUE" ELSE "FALSE" FI, newline ) );
show sandpile( "s3_id + s3", s3_id + s3 );
show sandpile( "s3_id + s3_id:", s3_id + s3_id )
END |
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.
| #Agda | Agda | module AbstractInterfaceExample where
open import Function
open import Data.Bool
open import Data.String
-- * One-parameter interface for the type `a' with only one method.
record VoiceInterface (a : Set) : Set where
constructor voice-interface
field say-method-of : a → String
open VoiceInterface
-- * An overloaded method.
say : {a : Set} → ⦃ _ : VoiceInterface a ⦄ → a → String
say ⦃ instance ⦄ = say-method-of instance
-- * Some data types.
data Cat : Set where
cat : Bool → Cat
crazy! = true
plain-cat = false
-- | This cat is crazy?
crazy? : Cat → Bool
crazy? (cat x) = x
-- | A 'plain' dog.
data Dog : Set where
dog : Dog
-- * Implementation of the interface (and method).
instance-for-cat : VoiceInterface Cat
instance-for-cat = voice-interface case where
case : Cat → String
case x with crazy? x
... | true = "meeeoooowwwww!!!"
... | false = "meow!"
instance-for-dog : VoiceInterface Dog
instance-for-dog = voice-interface $ const "woof!"
-- * and then:
--
-- say dog => "woof!"
-- say (cat crazy!) => "meeeoooowwwww!!!"
-- say (cat plain-cat) => "meow!"
-- |
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.
| #Aikido | Aikido | class Abs {
public function method1...
public function method2...
} |
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.
| #Objeck | Objeck | class Ackermann {
function : Main(args : String[]) ~ Nil {
for(m := 0; m <= 3; ++m;) {
for(n := 0; n <= 4; ++n;) {
a := Ackermann(m, n);
if(a > 0) {
"Ackermann({$m}, {$n}) = {$a}"->PrintLine();
};
};
};
}
function : Ackermann(m : Int, n : Int) ~ Int {
if(m > 0) {
if (n > 0) {
return Ackermann(m - 1, Ackermann(m, n - 1));
}
else if (n = 0) {
return Ackermann(m - 1, 1);
};
}
else if(m = 0) {
if(n >= 0) {
return n + 1;
};
};
return -1;
}
} |
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
| #FreeBASIC | FreeBASIC | ScreenRes 320, 200, 8
WindowTitle "Abelian sandpile model"
Dim As Long dimen = 220
Dim As Long pila1(dimen*dimen), pila2(dimen*dimen)
Dim As Long i, x, y
Dim As Long partic = 400000
Dim As Double t0 = Timer
Do
i = 0
For y = 0 To dimen-1
For x = 0 To dimen-1
If x = dimen/2 And y = dimen/2 Then
partic -= 4
pila1(i) += 4
End If
If pila1(i) >= 4 Then
pila1(i) -= 4
pila2(i-1) += 1
pila2(i+1) += 1
pila2(i-dimen) += 1
pila2(i+dimen) += 1
End If
Pset(x, y), (pila1(i)*2)
i += 1
Swap pila1(i), pila2(i)
Next x
Next y
Loop Until partic < 4
Bsave "abelian_sandpile.bmp",0
Sleep |
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
| #Delphi | Delphi |
program Abraviation_simple;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TCommand = record
value: string;
len: integer;
end;
function ReadTable(table: string): TArray<TCommand>;
begin
var fields := table.Split([' '], TStringSplitOptions.ExcludeEmpty);
var i := 0;
var max := Length(fields);
while i < max do
begin
var cmd := fields[i];
var cmdLen := cmd.Length;
inc(i);
if i < max then
begin
var num: Integer;
if TryStrToInt(fields[i], num) and (1 <= num) and (num < cmdLen) then
begin
cmdLen := num;
inc(i);
end;
end;
SetLength(result, Length(result) + 1);
with result[High(result)] do
begin
value := cmd;
len := cmdLen;
end;
end;
end;
function ValidateCommands(Commands: TArray<TCommand>; Words: TArray<string>):
TArray<string>;
begin
SetLength(result, 0);
for var wd in Words do
begin
var matchFound := false;
var wLen := wd.Length;
for var i := 0 to High(Commands) do
begin
var command := Commands[i];
if (command.len = 0) or (wLen < command.len) or (wLen > command.value.Length) then
Continue;
var c := command.value.ToUpper;
var w := wd.ToUpper;
if c.StartsWith(w) then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := c;
matchFound := true;
Break;
end;
end;
if not matchFound then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := '*error*';
end;
end;
end;
procedure PrintResults(words, results: TArray<string>);
begin
Writeln('user words:');
for var w in words do
write(^I, w);
Writeln(#10, 'full words:'^I, string.join(^I, results));
end;
const
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 ';
const
SENTENCE = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
begin
var Commands := ReadTable(table);
var Words := SENTENCE.Split([' '], TStringSplitOptions.ExcludeEmpty);
var results := ValidateCommands(Commands, Words);
PrintResults(Words, results);
Readln;
end. |
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
| #Delphi | Delphi |
program Abbreviations_Easy;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
_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 ';
function validate(commands, words: TArray<string>; minLens: TArray<Integer>):
TArray<string>;
begin
SetLength(result, 0);
if Length(words) = 0 then
exit;
for var wd in words do
begin
var matchFound := false;
var wlen := wd.Length;
for var i := 0 to High(commands) do
begin
var command := commands[i];
if (minLens[i] = 0) or (wlen < minLens[i]) or (wlen > length(command)) then
continue;
var c := command.ToUpper;
var w := wd.ToUpper;
if c.StartsWith(w) then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := c;
matchFound := True;
Break;
end;
end;
if not matchFound then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := 'error*';
end;
end;
end;
begin
var table := _TABLE_.Trim;
var commands := table.Split([' '], TStringSplitOptions.ExcludeEmpty);
var clen := Length(commands);
var minLens: TArray<integer>;
SetLength(minLens, clen);
for var i := 0 to clen - 1 do
begin
var count := 0;
for var c in commands[i] do
begin
if (c >= 'A') and (c <= 'Z') then
inc(count);
end;
minLens[i] := count;
end;
var sentence := 'riG rePEAT copies put mo rest types fup. 6 poweRin';
var words := sentence.Split([' '], TStringSplitOptions.ExcludeEmpty);
var results := validate(commands, words, minLens);
Write('user words: ');
for var j := 0 to Length(words) - 1 do
Write(words[j].PadRight(1 + length(results[j])));
Write(#10, 'full words: ');
Writeln(string.Join(' ', results));
Readln;
end. |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
} |
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.
| #AmigaE | AmigaE |
OBJECT fruit
ENDOBJECT
PROC color OF fruit IS EMPTY
OBJECT apple OF fruit
ENDOBJECT
PROC color OF apple IS WriteF('red ')
OBJECT orange OF fruit
ENDOBJECT
PROC color OF orange IS WriteF('orange ')
PROC main()
DEF a:PTR TO apple,o:PTR TO orange,x:PTR TO fruit
FORALL({x},[NEW a, NEW o],`x.color())
ENDPROC
|
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.
| #Apex | Apex |
// Interface
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}
// Abstract Class
public abstract class AbstractExampleClass {
protected abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class Class1 extends AbstractExampleClass {
public override Integer abstractMethod() { return 5; }
}
|
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.
| #OCaml | OCaml | let rec a m n =
if m=0 then (n+1) else
if n=0 then (a (m-1) 1) else
(a (m-1) (a m (n-1))) |
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
| #Go | Go | package main
import (
"fmt"
"log"
"os"
"strings"
)
const dim = 16 // image size
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
// Outputs the result to the terminal using UTF-8 block characters.
func drawPile(pile [][]uint) {
chars:= []rune(" ░▓█")
for _, row := range pile {
line := make([]rune, len(row))
for i, elem := range row {
if elem > 3 { // only possible when algorithm not yet completed.
elem = 3
}
line[i] = chars[elem]
}
fmt.Println(string(line))
}
}
// Creates a .ppm file in the current directory, which contains
// a colored image of the pile.
func writePile(pile [][]uint) {
file, err := os.Create("output.ppm")
check(err)
defer file.Close()
// Write the signature, image dimensions and maximum color value to the file.
fmt.Fprintf(file, "P3\n%d %d\n255\n", dim, dim)
bcolors := []string{"125 0 25 ", "125 80 0 ", "186 118 0 ", "224 142 0 "}
var line strings.Builder
for _, row := range pile {
for _, elem := range row {
line.WriteString(bcolors[elem])
}
file.WriteString(line.String() + "\n")
line.Reset()
}
}
// Main part of the algorithm, a simple, recursive implementation of the model.
func handlePile(x, y uint, pile [][]uint) {
if pile[y][x] >= 4 {
pile[y][x] -= 4
// Check each neighbor, whether they have enough "sand" to collapse and if they do,
// recursively call handlePile on them.
if y > 0 {
pile[y-1][x]++
if pile[y-1][x] >= 4 {
handlePile(x, y-1, pile)
}
}
if x > 0 {
pile[y][x-1]++
if pile[y][x-1] >= 4 {
handlePile(x-1, y, pile)
}
}
if y < dim-1 {
pile[y+1][x]++
if pile[y+1][x] >= 4 {
handlePile(x, y+1, pile)
}
}
if x < dim-1 {
pile[y][x+1]++
if pile[y][x+1] >= 4 {
handlePile(x+1, y, pile)
}
}
// Uncomment this line to show every iteration of the program.
// Not recommended with large input values.
// drawPile(pile)
// Finally call the function on the current cell again,
// in case it had more than 4 particles.
handlePile(x, y, pile)
}
}
func main() {
// Create 2D grid and set size using the 'dim' constant.
pile := make([][]uint, dim)
for i := 0; i < dim; i++ {
pile[i] = make([]uint, dim)
}
// Place some sand particles in the center of the grid and start the algorithm.
hdim := uint(dim/2 - 1)
pile[hdim][hdim] = 16
handlePile(hdim, hdim, pile)
drawPile(pile)
// Uncomment this to save the final image to a file
// after the recursive algorithm has ended.
// writePile(pile)
} |
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
| #Factor | Factor | USING: arrays assocs combinators formatting fry grouping.extras
kernel literals math math.parser multiline sequences
splitting.extras unicode ;
IN: rosetta-code.abbr-simple
CONSTANT: input $[
"riG rePEAT copies put mo rest types fup. 6 "
"poweRin" append
]
<< ! Make the following two words available at parse time.
: abbr-pair ( first second -- seq/f )
{
{ [ 2dup drop [ digit? ] all? ] [ 2drop f ] }
{
[ 2dup nip [ Letter? ] all? ]
[ drop >upper 0 2array ]
}
[ [ >upper ] [ string>number ] bi* 2array ]
} cond ;
: parse-commands ( seq -- seq )
" \n" split-harvest [ abbr-pair ] 2clump-map sift ;
>>
CONSTANT: commands $[
HEREDOC: END
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
END
parse-commands
]
: valid-abbrevs ( assoc seq -- assoc )
dup '[ [ _ head? ] [ _ length <= ] bi* and ] assoc-filter ;
: find-command ( seq -- seq )
>upper [ commands ] dip valid-abbrevs
[ "*error*" ] [ first first ] if-empty ;
: (find-commands) ( seq -- seq )
" " split-harvest [ find-command ] map " " join ;
: find-commands ( seq -- seq )
dup empty? not [ (find-commands) ] when ;
: show-commands ( seq -- )
dup find-commands " Input: \"%s\"\nOutput: \"%s\"\n" printf
;
: main ( -- ) input "" [ show-commands ] bi@ ;
MAIN: main |
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
| #Euphoria | Euphoria |
include std/text.e -- for upper conversion
include std/console.e -- for display
include std/sequence.e
sequence ct = """
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
"""
ct = upper(split(join(split(ct,"\n")," ")," "))
object input = remove_all("\n",upper(remove_all("",split(gets(0)))))
display(validate(input))
-------------------------------
function validate(object words)
-------------------------------
object results = repeat("*error*",length(words)) -- build an output list;
integer x
for i = 1 to length(words) do
words[i] = remove_all('\n',words[i]) -- final word in input line (may) have \n, get rid of it;
for j = 1 to length(ct) do
x = match(words[i],ct[j])
if x = 1 then
results[i] = ct[j] -- replace this slot in the output list with the "found" word;
exit -- and don't look further into the list;
end if
end for
end for
return flatten(join(results," ")) -- convert sequence of strings into one string, words separated by a single space;
end function
|
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
| #F.23 | F# |
let s1=Sandpile(3,3,[|1;2;0;2;1;1;0;1;3|])
let s2=Sandpile(3,3,[|2;1;3;1;0;1;0;1;0|])
printfn "%s\n" ((s1+s2).toS)
printfn "%s\n" ((s2+s1).toS);;
printfn "%s\n" ((s1+s1).toS)
printfn "%s\n" ((s2+s2).toS);;
printfn "%s\n" (Sandpile(3,3,[|4;3;3;3;1;2;0;2;3|])).toS;;
let s3=Sandpile(3,3,(Array.create 9 3))
let s3_id=Sandpile(3,3,[|2;1;2;1;0;1;2;1;2|])
printfn "%s\n" (s3+s3_id).toS
printfn "%s\n" (s3_id+s3_id).toS
//Add together 2 5x5 Sandpiles
let e1=Array.zeroCreate<int> 25 in e1.[12]<-6
let e2=Array.zeroCreate<int> 25 in e2.[12]<-16
printfn "%s\n" ((Sandpile(5,5,e1)+Sandpile(5,5,e2)).toS)
|
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.
| #Argile | Argile | use std
(: abstract class :)
class Abs
text name
AbsIface iface
class AbsIface
function(Abs)(int)->int method
let Abs_Iface = Cdata AbsIface@ {.method = nil}
.: new Abs :. -> Abs {let a = new(Abs); a.iface = Abs_Iface; a}
=: <Abs self>.method <int i> := -> int
(self.iface.method is nil) ? 0 , (call self.iface.method with self i)
(: implementation :)
class Sub <- Abs { int value }
let Sub_Iface = Cdata AbsIface@ {.method = (code of (nil the Sub).method 0)}
.: new Sub (<int value = -1>) :. -> Sub
let s = new (Sub)
s.iface = Sub_Iface
s.value = value
s
.: <Sub this>.method <int i> :. -> int {this.value + i}
(: example use :)
.:foobar<Abs a>:. {print a.method 12 ; del a}
foobar (new Sub 34) (: prints 46 :)
foobar (new Sub) (: prints 11 :)
foobar (new Abs) (: prints 0 :) |
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.
| #AutoHotkey | AutoHotkey | color(r, g, b){
static color
If !color
color := Object("base", Object("R", r, "G", g, "B", b
,"GetRGB", "Color_GetRGB"))
return Object("base", Color)
}
Color_GetRGB(clr) {
return "not implemented"
}
waterColor(r, g, b){
static waterColor
If !waterColor
waterColor := Object("base", color(r, g, b),"GetRGB", "WaterColor_GetRGB")
return Object("base", WaterColor)
}
WaterColor_GetRGB(clr){
return clr.R << 16 | clr.G << 8 | clr.B
}
test:
blue := color(0, 0, 255)
msgbox % blue.GetRGB() ; displays "not implemented"
blue := waterColor(0, 0, 255)
msgbox % blue.GetRGB() ; displays 255
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.
| #Octave | Octave | function r = ackerman(m, n)
if ( m == 0 )
r = n + 1;
elseif ( n == 0 )
r = ackerman(m-1, 1);
else
r = ackerman(m-1, ackerman(m, n-1));
endif
endfunction
for i = 0:3
disp(ackerman(i, 4));
endfor |
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
| #Haskell | Haskell | {-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Rosetta.AbelianSandpileModel.ST
( simulate
, test
, toPGM
) where
import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT)
import Control.Monad.ST (runST, ST)
import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when)
import Data.Array.ST (freeze, readArray, STUArray, thaw, writeArray)
import Data.Array.Unboxed (array, assocs, bounds, UArray, (!))
import Data.Word (Word32)
import System.IO (hPutStr, hPutStrLn, IOMode (WriteMode), withFile)
import Text.Printf (printf)
type Point = (Int, Int)
type ArrayST s = STUArray s Point Word32
type ArrayU = UArray Point Word32
newtype M s a = M (ReaderT (S s) (StateT [Point] (ST s)) a)
deriving (Functor, Applicative, Monad, MonadReader (S s), MonadState [Point])
data S s = S
{ bMin :: !Point
, bMax :: !Point
, arr :: !(ArrayST s)
}
runM :: M s a -> S s -> [Point]-> ST s a
runM (M m) = evalStateT . runReaderT m
liftST :: ST s a -> M s a
liftST = M . lift . lift
simulate :: ArrayU -> ArrayU
simulate a = runST $ simulateST a
simulateST :: forall s. ArrayU -> ST s ArrayU
simulateST a = do
let (p1, p2) = bounds a
s = [p | (p, c) <- assocs a, c >= 4]
b <- thaw a :: ST s (ArrayST s)
let st = S { bMin = p1
, bMax = p2
, arr = b
}
runM simulateM st s
simulateM :: forall s. M s ArrayU
simulateM = do
ps <- get
case ps of
[] -> asks arr >>= liftST . freeze
p : ps' -> do
c <- changeArr p $ \x -> x - 4
when (c < 4) $ put ps'
forM_ [north, east, south, west] $ inc . ($ p)
simulateM
changeArr :: Point -> (Word32 -> Word32) -> M s Word32
changeArr p f = do
a <- asks arr
oldC <- liftST $ readArray a p
let newC = f oldC
liftST $ writeArray a p newC
return newC
inc :: Point -> M s ()
inc p = do
b <- inBounds p
when b $ do
c <- changeArr p succ
when (c == 4) $ modify $ (p :)
inBounds :: Point -> M s Bool
inBounds p = do
st <- ask
return $ p >= bMin st && p <= bMax st
north, east, south, west :: Point -> Point
north (x, y) = (x, y + 1)
east (x, y) = (x + 1, y)
south (x, y) = (x, y - 1)
west (x, y) = (x - 1, y)
toPGM :: ArrayU -> FilePath -> IO ()
toPGM a fp = withFile fp WriteMode $ \h -> do
let ((x1, y1), (x2, y2)) = bounds a
width = x2 - x1 + 1
height = y2 - y1 + 1
hPutStrLn h "P2"
hPutStrLn h $ show width ++ " " ++ show height
hPutStrLn h "3"
forM_ [y1 .. y2] $ \y -> do
forM_ [x1 .. x2] $ \x -> do
let c = min 3 $ a ! (x, y)
hPutStr h $ show c ++ " "
hPutStrLn h ""
initArray :: Int -> Word32 -> ArrayU
initArray size height = array
((-size, -size), (size, size))
[((x, y), if x == 0 && y == 0 then height else 0) | x <- [-size .. size], y <- [-size .. size]]
test :: Int -> Word32 -> IO ()
test size height = do
printf "size = %d, height = %d\n" size height
let a = initArray size height
b = simulate a
fp = printf "sandpile_%d_%d.pgm" size height
toPGM b fp
putStrLn $ "wrote image to " ++ fp |
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
| #Forth | Forth | include FMS-SI.f
include FMS-SILib.f
${ 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 }
value list ' upper: list map:
: compare' { adr len $obj -- f }
len $obj size: > if false exit then
adr len $obj @: drop len compare 0= ;
: <= ( n1 n2 = f) 1+ swap > ;
: abbrev 0 0 { adr len obj1 obj2 -- }
list uneach:
list each: drop to obj1
begin
list each:
while
to obj2
obj2 @: >integer
if \ word followed by a number
len <= if adr len obj1 compare'
if obj1 p: exit then
then list each: if to obj1 else ." *error* " exit then
else \ word not followed by a number
adr len obj1 @: compare 0=
if obj1 p: exit then
obj2 to obj1
then
repeat ;
${ riG rePEAT copies put mo rest types fup. 6 poweRin }
value input-list ' upper: input-list map:
: valid-input ( adr len -- f)
over + swap do i c@ isalpha 0= if ." *error* " unloop false exit then loop true ;
: run
begin
input-list each:
while
dup @: valid-input
if @: abbrev space else drop then
repeat ;
run RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT ok
|
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
| #Factor | Factor | USING: arrays ascii assocs combinators.short-circuit io kernel
literals math qw sequences sequences.extras splitting.extras ;
IN: rosetta-code.abbreviations-easy
CONSTANT: commands qw{
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 }
CONSTANT: user-input $[ "riG rePEAT copies put mo rest "
"types fup. 6 poweRin" append ]
: starts-with? ( cand com -- ? ) [ >upper ] bi@ start 0 = ;
: capitals ( str -- n ) [ LETTER? ] count ;
: min-len? ( candidate command -- ? ) capitals swap length <= ;
: not-longer? ( candidate command -- ? ) [ length ] bi@ <= ;
: permitted? ( candidate command -- ? ) dup [ letter? ] count 0
> [ [ >upper ] bi@ = ] dip or ;
: valid-abbr? ( candidate command -- ? )
{
[ permitted? ]
[ starts-with? ]
[ min-len? ]
[ not-longer? ]
} 2&& ;
: find-command ( candidate -- command/f )
commands swap [ swap valid-abbr? ] curry find nip ;
: process-candidate ( candidate -- abbr/error )
find-command [ >upper ] [ "*error*" ] if* ;
: process-user-string ( str -- seq ) dup "" = [ drop "" ]
[ " " split-harvest [ process-candidate ] map ] if ;
: .abbr ( input -- )
[ " " split-harvest ] [ process-user-string ] bi zip
[ first2 32 pad-longest 2array ] map
[ keys ] [ values ] bi
[ " " join ] bi@
[ "User words: " write print ]
[ "Full words: " write print ] bi* ;
: main ( -- ) user-input "" [ .abbr ] bi@ ;
MAIN: main |
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
| #Go | Go | package main
import (
"fmt"
"strings"
)
var 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 "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
} |
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
| #Factor | Factor | USING: arrays grouping io kernel math math.vectors prettyprint
qw sequences ;
CONSTANT: neighbors {
{ 1 3 } { 0 2 4 } { 1 5 } { 0 4 6 } { 1 3 5 7 }
{ 2 4 8 } { 3 7 } { 4 6 8 } { 5 7 }
}
! Sandpile words
: find-tall ( seq -- n ) [ 3 > ] find drop ;
: tall? ( seq -- ? ) find-tall >boolean ;
: distribute ( ind seq -- ) [ [ 1 + ] change-nth ] curry each ;
: adjacent ( n seq -- ) [ neighbors nth ] dip distribute ;
: shrink ( n seq -- ) [ 4 - ] change-nth ;
: (topple) ( n seq -- ) [ shrink ] [ adjacent ] 2bi ;
: topple ( seq -- seq' ) [ find-tall ] [ (topple) ] [ ] tri ;
: avalanche ( seq -- ) [ dup tall? ] [ topple ] while drop ;
: s+ ( seq1 seq2 -- seq3 ) v+ dup avalanche ;
! Output words
: mappend ( seq1 seq2 -- seq3 ) [ flip ] bi@ append flip ;
: sym ( seq str -- seq ) 1array " " 1array tuck 3array mappend ;
: arrow ( seq -- new-seq ) ">" sym ;
: plus ( seq -- new-seq ) "+" sym ;
: eq ( seq -- new-seq ) "=" sym ;
: topple> ( seq seq -- seq seq ) arrow over topple 3 group mappend ;
: (.s+) ( seq seq seq -- seq ) [ plus ] [ mappend eq ] [ mappend ] tri* ;
: .s+ ( seq1 seq2 -- ) 2dup s+ [ 3 group ] tri@ (.s+) simple-table. ;
! Task
CONSTANT: s1 { 1 2 0 2 1 1 0 1 3 }
CONSTANT: s2 { 2 1 3 1 0 1 0 1 0 }
CONSTANT: s3 { 3 3 3 3 3 3 3 3 3 }
CONSTANT: id { 2 1 2 1 0 1 2 1 2 }
"Avalanche:" print nl
{ 4 3 3 3 1 2 0 2 3 }
dup 3 group topple> topple> topple> topple> nip simple-table. nl
"s1 + s2 = s2 + s1" print nl
s1 s2 .s+ nl s2 s1 .s+ nl
"s3 + s3_id = s3" print nl
s3 id .s+ nl
"s3_id + s3_id = s3_id" print nl
id id .s+ |
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.
| #BASIC | BASIC | INSTALL @lib$+"CLASSLIB"
REM Declare a class with no implementation:
DIM abstract{method}
PROC_class(abstract{})
REM Inherit from the abstract class:
DIM derived{member%}
PROC_inherit(derived{}, abstract{})
PROC_class(derived{})
REM Provide an implementation for the derived class:
DEF derived.method : PRINT "Hello world!" : ENDPROC
REM Instantiate the derived class:
PROC_new(instance{}, derived{})
REM Test by calling the method:
PROC(instance.method) |
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.
| #C | C | #ifndef INTERFACE_ABS
#define INTERFACE_ABS
typedef struct sAbstractCls *AbsCls;
typedef struct sAbstractMethods {
int (*method1)(AbsCls c, int a);
const char *(*method2)(AbsCls c, int b);
void (*method3)(AbsCls c, double d);
} *AbstractMethods, sAbsMethods;
struct sAbstractCls {
AbstractMethods klass;
void *instData;
};
#define ABSTRACT_METHODS( cName, m1, m2, m3 ) \
static sAbsMethods cName ## _Iface = { &m1, &m2, &m3 }; \
AbsCls cName ## _Instance( void *clInst) { \
AbsCls ac = malloc(sizeof(struct sAbstractCls)); \
if (ac) { \
ac->klass = &cName ## _Iface; \
ac->instData = clInst; \
}\
return ac; }
#define Abs_Method1( c, a) (c)->klass->method1(c, a)
#define Abs_Method2( c, b) (c)->klass->method2(c, b)
#define Abs_Method3( c, d) (c)->klass->method3(c, d)
#define Abs_Free(c) \
do { if (c) { free((c)->instData); free(c); } } while(0);
#endif |
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.
| #Oforth | Oforth | : A( m n -- p )
m ifZero: [ n 1+ return ]
m 1- n ifZero: [ 1 ] else: [ A( m, n 1- ) ] A
; |
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
| #J | J | grid=: 4 : 'x (<<.-:2$y)} (2$y)$0' NB. y by y grid with x grains in middle
ab=: - [: +/@(-"2 ((,-)=/~i.2)|.!.0]) 3&< NB. abelian sand pile for grid graph
require 'viewmat' NB. viewmat utility
viewmat ab ^: _ (1024 grid 25) NB. visual |
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
| #Java | Java | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AbelianSandpile {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Frame frame = new Frame();
frame.setVisible(true);
}
});
}
private static class Frame extends JFrame {
private Frame() {
super("Abelian Sandpile Model");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton start = new JButton("Restart Simulation");
start.addActionListener(e -> restartSimulation());
JButton stop = new JButton("Stop Simulation");
stop.addActionListener(e -> stopSimulation());
controlPanel.add(start);
controlPanel.add(stop);
contentPane.add(controlPanel, BorderLayout.NORTH);
contentPane.add(canvas = new Canvas(), BorderLayout.CENTER);
timer = new Timer(100, e -> canvas.runAndDraw());
timer.start();
pack();
}
private void restartSimulation() {
timer.stop();
canvas.initGrid();
timer.start();
}
private void stopSimulation() {
timer.stop();
}
private Timer timer;
private Canvas canvas;
}
private static class Canvas extends JComponent {
private Canvas() {
setBorder(BorderFactory.createEtchedBorder());
setPreferredSize(new Dimension(600, 600));
}
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
int cellWidth = width/GRID_LENGTH;
int cellHeight = height/GRID_LENGTH;
for (int i = 0; i < GRID_LENGTH; ++i) {
for (int j = 0; j < GRID_LENGTH; ++j) {
if (grid[i][j] > 0) {
g.setColor(COLORS[grid[i][j]]);
g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
}
}
}
}
private void initGrid() {
for (int i = 0; i < GRID_LENGTH; ++i) {
for (int j = 0; j < GRID_LENGTH; ++j) {
grid[i][j] = 0;
}
}
}
private void runAndDraw() {
for (int i = 0; i < 100; ++i)
addSand(GRID_LENGTH/2, GRID_LENGTH/2);
repaint();
}
private void addSand(int i, int j) {
int grains = grid[i][j];
if (grains < 3) {
grid[i][j]++;
}
else {
grid[i][j] = grains - 3;
if (i > 0)
addSand(i - 1, j);
if (i < GRID_LENGTH - 1)
addSand(i + 1, j);
if (j > 0)
addSand(i, j - 1);
if (j < GRID_LENGTH - 1)
addSand(i, j + 1);
}
}
private int[][] grid = new int[GRID_LENGTH][GRID_LENGTH];
}
private static final Color[] COLORS = {
Color.WHITE,
new Color(0x00, 0xbf, 0xff),
new Color(0xff, 0xd7, 0x00),
new Color(0xb0, 0x30, 0x60)
};
private static final int GRID_LENGTH = 300;
} |
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
| #Go | Go | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const 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 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
|
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
| #Haskell | Haskell |
import Data.Maybe (fromMaybe)
import Data.List (find, isPrefixOf)
import Data.Char (toUpper, isUpper)
isAbbreviationOf :: String -> String -> Bool
isAbbreviationOf abbreviation command =
minimumPrefix `isPrefixOf` normalizedAbbreviation
&& normalizedAbbreviation `isPrefixOf` normalizedCommand
where
normalizedAbbreviation = map toUpper abbreviation
normalizedCommand = map toUpper command
minimumPrefix = takeWhile isUpper command
expandAbbreviation :: String -> String -> Maybe String
expandAbbreviation commandTable abbreviation = do
command <- find (isAbbreviationOf abbreviation) (words commandTable)
return $ map toUpper command
commandTable = unwords [
"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"]
main :: IO ()
main = do
input <- getLine
let abbreviations = words input
let commands = map (fromMaybe "*error*" . expandAbbreviation commandTable) abbreviations
putStrLn $ unwords results
|
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
| #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
)
type sandpile struct{ a [9]int }
var neighbors = [][]int{
{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}
// 'a' is in row order
func newSandpile(a [9]int) *sandpile { return &sandpile{a} }
func (s *sandpile) plus(other *sandpile) *sandpile {
b := [9]int{}
for i := 0; i < 9; i++ {
b[i] = s.a[i] + other.a[i]
}
return &sandpile{b}
}
func (s *sandpile) isStable() bool {
for _, e := range s.a {
if e > 3 {
return false
}
}
return true
}
// just topples once so we can observe intermediate results
func (s *sandpile) topple() {
for i := 0; i < 9; i++ {
if s.a[i] > 3 {
s.a[i] -= 4
for _, j := range neighbors[i] {
s.a[j]++
}
return
}
}
}
func (s *sandpile) String() string {
var sb strings.Builder
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
}
sb.WriteString("\n")
}
return sb.String()
}
func main() {
fmt.Println("Avalanche of topplings:\n")
s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
fmt.Println(s4)
for !s4.isStable() {
s4.topple()
fmt.Println(s4)
}
fmt.Println("Commutative additions:\n")
s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
s3_a := s1.plus(s2)
for !s3_a.isStable() {
s3_a.topple()
}
s3_b := s2.plus(s1)
for !s3_b.isStable() {
s3_b.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)
fmt.Println("Addition of identity sandpile:\n")
s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
s4 = s3.plus(s3_id)
for !s4.isStable() {
s4.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)
fmt.Println("Addition of identities:\n")
s5 := s3_id.plus(s3_id)
for !s5.isStable() {
s5.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
} |
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.
| #C.23 | C# | abstract class Class1
{
public abstract void method1();
public int method2()
{
return 0;
}
} |
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.
| #C.2B.2B | C++ | class Abs {
public:
virtual int method1(double value) = 0;
virtual int add(int a, int b){
return a+b;
}
}; |
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.
| #OOC | OOC |
ack: func (m: Int, n: Int) -> Int {
if (m == 0) {
n + 1
} else if (n == 0) {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}
main: func {
for (m in 0..4) {
for (n in 0..10) {
"ack(#{m}, #{n}) = #{ack(m, n)}" println()
}
}
}
|
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
| #Julia | Julia | module AbelSand
# supports output functionality for the results of the sandpile simulations
# outputs the final grid in CSV format, as well as an image file
using CSV, DataFrames, Images
function TrimZeros(A)
# given an array A trims any zero rows/columns from its borders
# returns a 4 tuple of integers, i1, i2, j1, j2, where the trimmed array corresponds to A[i1:i2, j1:j2]
# A can be either numeric or a boolean array
i1, j1 = 1, 1
i2, j2 = size(A)
zz = typeof(A[1, 1])(0) # comparison of a value takes into account the type as well
# i1 is the first row which has non zero element
for i = 1:size(A, 1)
q = false
for k = 1:size(A, 2)
if A[i, k] != zz
q = true
i1 = i
break
end
end
if q == true
break
end
end
# i2 is the first from below row with non zero element
for i in size(A, 1):-1:1
q = false
for k = 1:size(A, 2)
if A[i, k] != zz
q = true
i2 = i
break
end
end
if q == true
break
end
end
# j1 is the first column with non zero element
for j = 1:size(A, 2)
q = false
for k = 1:size(A, 1)
if A[k, j] != zz
j1 = j
q = true
break
end
end
if q == true
break
end
end
# j2 is the last column with non zero element
for j in size(A, 2):-1:1
q=false
for k=1:size(A,1)
if A[k, j] != zz
j2 = j
q=true
break
end
end
if q==true
break
end
end
return i1, i2, j1, j2
end
function addLayerofZeros(A, extraLayer)
# adds layer of zeros from all corners to the given array A
if extraLayer <= 0
return A
end
N, M = size(A)
Z = zeros( typeof(A[1,1]), N + 2*extraLayer, M + 2*extraLayer)
Z[(extraLayer+1):(N + extraLayer ), (extraLayer+1):(M+extraLayer)] = A
return Z
end
function printIntoFile(A, extraLayer, strFileName, TrimSmallValues = false)
# exports a 2d matrix A into a csv file
# @extraLayer is an integers adding layer of 0-s sorrounding the output matrix
# trimming off very small values; tiny values affect the performance of CSV export
if TrimSmallValues == true
A = map(x -> if (abs(x - floor(x)) < 0.01) floor(x) else x end, A)
end
i1, i2, j1, j2 = TrimZeros( A )
A = A[i1:i2, j1:j2]
A = addLayerofZeros(A, extraLayer)
CSV.write(string(strFileName,".csv"), DataFrame(A), writeheader = false)
return A
end
function Array_magnifier(A, cell_mag, border_mag)
# A is the main array; @cell_mag is the magnifying size of the cell,
# @border_mag is the magnifying size of the border between lattice cells
# creates a new array where each cell of the original array A appears magnified by size = cell_mag
total_factor = cell_mag + border_mag
A1 = zeros(typeof(A[1, 1]), total_factor*size(A, 1), total_factor*size(A, 2))
for i = 1:size(A,1), j = 1:size(A,2), u = ((i-1)*total_factor+1):(i*total_factor),
v = ((j-1)*total_factor+1):(j*total_factor)
if(( u - (i - 1) * total_factor <= cell_mag) && (v - (j - 1) * total_factor <= cell_mag))
A1[u, v] = A[i, j]
end
end
return A1
end
function saveAsGrayImage(A, fileName, cell_mag, border_mag, TrimSmallValues = false)
# given a 2d matrix A, we save it as a gray image after magnifying by the given factors
A1 = Array_magnifier(A, cell_mag, border_mag)
A1 = A1/maximum(maximum(A1))
# trimming very small values from A1 to improve performance
if TrimSmallValues == true
A1 = map(x -> if ( x < 0.01) 0.0 else round(x, digits = 2) end, A1)
end
save(string(fileName, ".png") , colorview(Gray, A1))
end
function saveAsRGBImage(A, fileName, color_codes, cell_mag, border_mag)
# color_codes is a dictionary, where key is a value in A and value is an RGB triplet
# given a 2d array A, and color codes (mapping from values in A to RGB triples), save A
# into fileName as png image after applying the magnifying factors
A1 = Array_magnifier(A, cell_mag, border_mag)
color_mat = zeros(UInt8, (3, size(A1, 1), size(A1, 2)))
for i = 1:size(A1,1)
for j = 1:size(A1,2)
color_mat[:, i, j] = get(color_codes, A1[i, j] , [0, 0, 0])
end
end
save(string(fileName, ".png") , colorview(RGB, color_mat/255))
end
const N_size = 700 # the radius of the lattice Z^2, the actual size becomes (2*N+1)x(2*N+1)
const dx = [1, 0, -1, 0] # for a given (x,y) in Z^2, (x + dx, y + dy) for all (dx,dy) covers the neighborhood of (x,y)
const dy = [0, 1, 0, -1]
struct L_coord
# represents a lattice coordinate
x::Int
y::Int
end
function FindCoordinate(Z::Array{L_coord,1}, a::Int, b::Int)
# in the given array Z of coordinates finds the (first) index of the tuple (a,b)
# if no match, returns -1
for i=1:length(Z)
if (Z[i].x == a) && (Z[i].y == b)
return i
end
end
return -1
end
function move(N)
# the main function moving the pile sand grains of size N at the origin of Z^2 until the sandpile becomes stable
Z_lat = zeros(UInt8, 2 * N_size + 1, 2 * N_size + 1) # models the integer lattice Z^2, we will have at most 4 sands on each vertex
V_sites = falses(2 * N_size + 1, 2 * N_size + 1) # all sites which are visited by the sandpile process, are being marked here
Odometer = zeros(UInt64, 2 * N_size + 1, 2 * N_size + 1) # stores the values of the odometer function
walking = L_coord[] # the coordinates of sites which need to move
V_sites[N_size + 1, N_size + 1] = true
# i1, ... j2 -> show the boundaries of the box which is visited by the sandpile process
i1, i2, j1, j2 = N_size + 1, N_size + 1, N_size + 1, N_size + 1
n = N
t1 = time_ns()
while n > 0
n -= 1
Z_lat[N_size + 1, N_size + 1] += 1
if (Z_lat[N_size + 1, N_size + 1] >= 4)
push!(walking, L_coord(N_size + 1, N_size + 1))
end
while(length(walking) > 0)
w = pop!(walking)
x = w.x
y = w.y
Z_lat[x, y] -= 4
Odometer[x, y] += 4
for k = 1:4
Z_lat[x + dx[k], y + dy[k]] += 1
V_sites[x + dx[k], y + dy[k]] = true
if Z_lat[x + dx[k], y + dy[k]] >= 4
if FindCoordinate(walking, x + dx[k] , y + dy[k]) == -1
push!(walking, L_coord( x + dx[k], y + dy[k]))
end
end
end
i1 = min(i1, x - 1)
i2 = max(i2, x + 1)
j1 = min(j1, y - 1)
j2 = max(j2, y + 1)
end
end #end of the main while
t2 = time_ns()
println("The final boundaries are:: ", (i2 - i1 + 1),"x",(j2 - j1 + 1), "\n")
print("time elapsed: " , (t2 - t1) / 1.0e9, "\n")
Z_lat = printIntoFile(Z_lat, 0, string("Abel_Z_", N))
Odometer = printIntoFile(Odometer, 1, string("Abel_OD_", N))
saveAsGrayImage(Z_lat, string("Abel_Z_", N), 20, 0)
color_code = Dict(1=>[255, 128, 255], 2=>[255, 0, 0],3 => [0, 128, 255])
saveAsRGBImage(Z_lat, string("Abel_Z_color_", N), color_code, 20, 0)
# for the total elapsed time, it's better to use the @time macros on the main call
return Z_lat, Odometer # these are trimmed in output module
end # end of function move
end # module
using .AbelSand
Z_lat, Odometer = AbelSand.move(100000)
|
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
| #Lua | Lua | local sandpile = {
init = function(self, dim, val)
self.cell, self.dim = {}, dim
for r = 1, dim do
self.cell[r] = {}
for c = 1, dim do
self.cell[r][c] = 0
end
end
self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val
end,
iter = function(self)
local dim, cel, more = self.dim, self.cell
repeat
more = false
for r = 1, dim do
for c = 1, dim do
if cel[r][c] >= 4 then
cel[r][c] = cel[r][c] - 4
if c > 1 then cel[r][c-1], more = cel[r][c-1]+1, more or cel[r][c-1]>=3 end
if c < dim then cel[r][c+1], more = cel[r][c+1]+1, more or cel[r][c+1]>=3 end
if r > 1 then cel[r-1][c], more = cel[r-1][c]+1, more or cel[r-1][c]>=3 end
if r < dim then cel[r+1][c], more = cel[r+1][c]+1, more or cel[r+1][c]>=3 end
end
more = more or cel[r][c] >= 4
end
end
until not more
end,
draw = function(self)
for r = 1, self.dim do
print(table.concat(self.cell[r]," "))
end
end,
}
sandpile:init(15, 256)
sandpile:iter()
sandpile:draw() |
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
| #Haskell | Haskell | import Data.List (find, isPrefixOf)
import Data.Char (isDigit, toUpper)
import Data.Maybe (maybe)
withExpansions :: [(String, Int)] -> String -> String
withExpansions tbl s = unwords $ expanded tbl <$> words s
expanded :: [(String, Int)] -> String -> String
expanded tbl k = maybe "*error" fst (expand k)
where
expand [] = Just ([], 0)
expand s =
let u = toUpper <$> s
lng = length s
in find (\(w, n) -> lng >= n && isPrefixOf u w) tbl
cmdsFromString :: String -> [(String, Int)]
cmdsFromString s =
let go w@(x:_) (xs, n)
| isDigit x = (xs, read w :: Int)
| otherwise = ((toUpper <$> w, n) : xs, 0)
in fst $ foldr go ([], 0) (words s)
-- TESTS --------------------------------------------------
table :: [(String, Int)]
table =
cmdsFromString
"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"
main :: IO ()
main = do
let unAbbrev = withExpansions table
print $
unAbbrev
"riG rePEAT copies put mo rest types fup. 6 poweRin"
print $ unAbbrev "" |
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
| #J | J |
COMMAND_TABLE=: noun define
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
)
'CAPA CAPZ'=:a.i.'AZ'
CT =: (, 3 ": [: +/ (CAPA&<: *. <:&CAPZ)@:(a.&i.))&.>&.:;: CRLF -.~ COMMAND_TABLE
user_words =: 'riG rePEAT copies put mo rest types fup. 6 poweRin'
CT expand user_words
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
|
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
| #Java | Java | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) { //Populate words and number of caps
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false; //resets each outer loop
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) { //no match, print error msg
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
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
| #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.List (findIndex, transpose)
import Data.List.Split (chunksOf)
--------------------------- TEST ---------------------------
main :: IO ()
main = do
let s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]
s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]
s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]
s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]
s3 = replicate 3 (replicate 3 3)
x:xs = reverse $ cascade s0
mapM_
putStrLn
[ "Cascade:"
, showCascade $ ([], x) : fmap ("->", ) xs
, "s1 + s2 == s2 + s1 -> " <> show (addSand s1 s2 == addSand s2 s1)
, showCascade [([], s1), (" +", s2), (" =", addSand s1 s2)]
, showCascade [([], s2), (" +", s1), (" =", addSand s2 s1)]
, "s3 + s3_id == s3 -> " <> show (addSand s3 s3_id == s3)
, showCascade [([], s3), (" +", s3_id), (" =", addSand s3 s3_id)]
, "s3_id + s3_id == s3_id -> " <> show (addSand s3_id s3_id == s3_id)
, showCascade [([], s3_id), (" +", s3_id), (" =", addSand s3_id s3_id)]
]
------------------------ SAND PILES ------------------------
addSand :: [[Int]] -> [[Int]] -> [[Int]]
addSand xs ys =
(head . cascade . chunksOf (length xs)) $ zipWith (+) (concat xs) (concat ys)
cascade :: [[Int]] -> [[[Int]]]
cascade xs = chunksOf w <$> convergence (==) (iterate (tumble w) (concat xs))
where
w = length xs
convergence :: (a -> a -> Bool) -> [a] -> [a]
convergence p = go
where
go (x:ys@(y:_))
| p x y = [x]
| otherwise = go ys <> [x]
tumble :: Int -> [Int] -> [Int]
tumble w xs = maybe xs go $ findIndex (w <) xs
where
go i = zipWith f [0 ..] xs
where
neighbours = indexNeighbours w i
f j x
| j `elem` neighbours = succ x
| i == j = x - succ w
| otherwise = x
indexNeighbours :: Int -> Int -> [Int]
indexNeighbours w = go
where
go i =
concat
[ [ j
| j <- [i - w, i + w]
, -1 < j
, wSqr > j ]
, [ pred i
| 0 /= col ]
, [ succ i
| pred w /= col ]
]
where
wSqr = w * w
col = rem i w
------------------------- DISPLAY --------------------------
showCascade :: [(String, [[Int]])] -> String
showCascade pairs =
unlines $
fmap unwords $
transpose $
fmap
(\(pfx, xs) ->
unwords <$> transpose (centered pfx : transpose (fmap (fmap show) xs)))
pairs
centered :: String -> [String]
centered s = [pad, s, pad <> replicate r ' ']
where
lng = length s
pad = replicate lng ' '
(q, r) = quotRem (2 + lng) 2 |
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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Abstract.Class.Shape [ Abstract ]
{
Parameter SHAPE = 1;
Property Name As %String;
Method Description() {}
}
Class Abstract.Class.Square Extends (%RegisteredObject, Shape)
{
Method Description()
{
Write "SHAPE=", ..#SHAPE, !
Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape"
}
} |
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.
| #Clojure | Clojure | (defprotocol Foo (foo [this])) |
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.
| #ooRexx | ooRexx |
loop m = 0 to 3
loop n = 0 to 6
say "Ackermann("m", "n") =" ackermann(m, n)
end
end
::routine ackermann
use strict arg m, n
-- give us some precision room
numeric digits 10000
if m = 0 then return n + 1
else if n = 0 then return ackermann(m - 1, 1)
else return ackermann(m - 1, ackermann(m, n - 1))
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[sp]
sp[s_List] + sp[n_Integer] ^:= sp[s] + sp[ConstantArray[n, Dimensions[s]]]
sp[s_List] + sp[t_List] ^:= Module[{dim, r, tmp, neighbours}, dim = Dimensions[s];
r = s + t;
While[Max[r] > 3, r = ArrayPad[r, 1, 0];
tmp = Quotient[r, 4];
r -= 4 tmp;
r += RotateLeft[tmp, {0, 1}] + RotateLeft[tmp, {1, 0}] +
RotateLeft[tmp, {0, -1}] + RotateLeft[tmp, {-1, 0}];
r = ArrayPad[r, -1];];
sp[r]
]
u = sp[CenterArray[250, {15, 15}]];
u += sp[0];
StringRiffle[StringJoin /@ Map[ToString, u[[1]], {2}], "\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
| #Nim | Nim |
# Abelian sandpile.
from math import sqrt
from nimPNG import savePNG24
from sequtils import repeat
from strformat import fmt
from strutils import strip, addSep, parseInt
# The grid represented as a sequence of sequences of int32.
type Grid = seq[seq[int32]]
# Colors to use for PPM and PNG files.
const Colors = [[byte 100, 40, 15],
[byte 117, 87, 30],
[byte 181, 134, 47],
[byte 245, 182, 66]]
#---------------------------------------------------------------------------------------------------
func sideLength(initVal: int32): int32 =
# Return the grid side length needed for "initVal" particles.
# We make sure that the returned value is odd.
result = sqrt(initVal.toFloat / 1.75).int32 + 3
result += result and 1 xor 1
#---------------------------------------------------------------------------------------------------
func doOneStep(grid: var Grid; boundary: var array[4, int]): bool =
## Compute one step.
result = false
for y in boundary[0]..boundary[2]:
for x in boundary[1]..boundary[3]:
if grid[y][x] >= 4:
let rem = grid[y][x] div 4
grid[y][x] = grid[y][x] mod 4
if y - 1 >= 0:
inc grid[y - 1][x], rem
if y == boundary[0]:
dec boundary[0]
if x - 1 >= 0:
inc grid[y][x - 1], rem
if x == boundary[1]:
dec boundary[1]
if y + 1 < grid.len:
inc grid[y + 1][x], rem
if y == boundary[2]:
inc boundary[2]
if x + 1 < grid.len:
inc grid[y][x + 1], rem
if x == boundary[3]:
inc boundary[3]
result = true
#---------------------------------------------------------------------------------------------------
proc display(grid: Grid; initVal: int) =
## Display the grid as an array of values.
echo fmt"Starting with {initVal} particles."
echo ""
var line = newStringOfCap(2 * grid.len - 1)
for row in grid:
for value in row:
line.addSep(" ", 0)
line.add($value)
echo line
line.setLen(0)
echo ""
#---------------------------------------------------------------------------------------------------
proc writePpmFile(grid: Grid; name: string) =
## Write a grid representation in a PPM file.
var file = open(name, fmWrite)
file.write(fmt"P6 {grid.len} {grid.len} 255 ")
for row in grid:
for value in row:
discard file.writeBytes(Colors[value], 0, 3)
file.close()
echo fmt"PPM image written in ""{name}""."
#---------------------------------------------------------------------------------------------------
proc writePngFile(grid: Grid; name: string) =
## Write a grid representation in a PNG file.
var pixels = newSeq[byte](3 * grid.len * grid.len)
# Build pixel list.
var idx = 0
for row in grid:
for value in row:
pixels[idx..idx+2] = Colors[value]
inc idx, 3
discard savePNG24(name, pixels, grid.len, grid.len)
echo fmt"PNG image written in ""{name}""."
#---------------------------------------------------------------------------------------------------
proc askInitVal(): int32 =
# Ask user for the number of particles.
while true:
stdout.write("Number of particles? ")
try:
let input = stdin.readLine().strip().parseInt()
if input in 4..int32.high:
return input.int32
echo fmt"Value not in expected range: 4..{int32.high}"
except ValueError:
echo "Invalid input"
except EOFError:
quit(QuitSuccess)
#---------------------------------------------------------------------------------------------------
# Initialize the grid.
let initVal = askInitVal()
let sideLen = sideLength(initVal)
var grid = repeat(newSeq[int32](sideLen), sideLen)
let origin = grid.len div 2
var boundaries: array[4, int] = [origin, origin, origin, origin]
grid[origin][origin] = initVal
# Run the simulation.
while doOneStep(grid, boundaries):
discard
# Display grid.
if grid.len <= 20:
grid.display(initVal)
#grid.writePpmFile(fmt"grid_{initVal}.ppm")
grid.writePngFile(fmt"grid_{initVal}.png")
|
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
| #J | J |
range=:<.+[:i.>.-<.
assert 2 3 4 -: 2 range 5
assert (i.0) -: 3 range 3
abbreviate =: 3 :0
NB. input is the abbreviation table
NB. output are the valid abbreviations
y =. toupper CRLF -.~ y
y =. ;: y
y =. (([: (,3":#)L:_1 {)`[`]}~ ([: I. [: -. {.@e.&Num_j_&>)) y
y =. [&.:(;:inv) y
y =. _2 ({. , <./@:".&.>@:{:)\ y
y =. (<@] , ((range #) <@{."0 _ ]))&.>~/"1 y
ambiguities =. ;#~1<[:+/e.
(([: ~. {.@:[ , -.)L:_1 <@:ambiguities) y
)
assert ('ABC A AB' ,&(<@;:) 'ABCDE ABCD') -: abbreviate 'abc 1 abcde 3'
assert ('ABC A AB' ,&(<@;:) 'ABCDE') -: abbreviate 'abc 1 abcde'
expand =: dyad define
a =. abbreviate x
words =. <;._2 ' ' ,~ deb toupper y
interval_index =. <: +/\ #&> a
a =. a , <,<'*error*'
;:inv {.&> (interval_index I.(; a )i."_ 0 words){ a
)
|
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
| #JavaScript | JavaScript |
var abr=`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`
.split(/\W+/).map(_=>_.trim())
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var input = prompt();
console.log(input.length==0?null:input.trim().split(/\s+/)
.map(
(s=>abr.filter(
a=>(new RegExp('^'+escapeRegex(s),'i'))
.test(a)&&s.length>=a.match(/^[A-Z]+/)[0].length
)[0])
)
.map(_=>typeof _=="undefined"?"*error*":_).join(' ')
)
|
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
| #J | J |
While=:2 :'u^:(0-.@:-:v)^:_'
index_of_maximum=: $ #: (i. >./)@:,
frame=: ({.~ -@:>:@:$)@:({.~ >:@:$) :. ([;.0~ (1,:_2+$))
NEIGHBORS=: _2]\_1 0 0 _1 0 0 0 1 1 0
AVALANCHE =: 1 1 _4 1 1
avalanche=: (AVALANCHE + {)`[`]}~ ([: <"1 NEIGHBORS +"1 index_of_maximum)
erode=: avalanche&.:frame While(3 < [: >./ ,)
|
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.
| #COBOL | COBOL | INTERFACE-ID. Shape.
PROCEDURE DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
END METHOD perimeter.
METHOD-ID. shape-area.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
END METHOD shape-area.
END INTERFACE Shape.
CLASS-ID. Rectangle.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
INTERFACE Shape.
OBJECT IMPLEMENTS Shape.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 width USAGE FLOAT-LONG PROPERTY.
01 height USAGE FLOAT-LONG PROPERTY.
PROCEDURE DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * 2.0 + height * 2.0
GOBACK
.
END METHOD perimeter.
METHOD-ID. shape-area.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * height
GOBACK
.
END METHOD shape-area.
END OBJECT.
END CLASS Rectangle. |
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.
| #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8ack ORDER_PP_FN( \
8fn(8X, 8Y, \
8cond((8is_0(8X), 8inc(8Y)) \
(8is_0(8Y), 8ack(8dec(8X), 1)) \
(8else, 8ack(8dec(8X), 8ack(8X, 8dec(8Y)))))))
ORDER_PP(8to_lit(8ack(3, 4))) // 125 |
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
| #Pascal | Pascal | mul := val DIV 4;//not only := val -4 |
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
| #OCaml | OCaml |
module Make =
functor (M : sig val m : int val n : int end)
-> struct
let grid = Array.init M.m (fun _ -> Array.make M.n 0)
let print () =
for i = 0 to M.m - 1
do for j = 0 to M.n - 1
do Printf.printf "%d " grid.(i).(j)
done
; print_newline ()
done
let unstable = Hashtbl.create 10
let add_grain x y
= grid.(x).(y) <- grid.(x).(y) + 1
; if grid.(x).(y) >= 4 then
Hashtbl.replace unstable (x,y) () (* Use Hashtbl.replace for uniqueness *)
let topple x y
= grid.(x).(y) <- grid.(x).(y) - 4
; if grid.(x).(y) < 4
then Hashtbl.remove unstable (x,y)
; match (x,y) with
(* corners *)
| (0,0) -> add_grain 1 0
; add_grain 0 1
| (0,n) when n = M.n - 1
-> add_grain 1 n
; add_grain 0 (n-1)
| (m,0) when m = M.m - 1
-> add_grain m 1
; add_grain (m-1) 0
| (m,n) when m = M.m - 1 && n = M.n - 1
-> add_grain ( m ) (n-1)
; add_grain (m-1) ( n )
(* sides *)
| (0,y) -> add_grain 1 y
; add_grain 0 (y+1)
; add_grain 0 (y-1)
| (m,y) when m = M.m - 1
-> add_grain ( m ) (y-1)
; add_grain ( m ) (y+1)
; add_grain (m-1) ( y )
| (x,0) -> add_grain (x+1) 0
; add_grain (x-1) 0
; add_grain ( x ) 1
| (x,n) when n = M.n - 1
-> add_grain (x-1) ( n )
; add_grain (x+1) ( n )
; add_grain ( x ) (n-1)
(* else *)
| (x,y) -> add_grain ( x ) (y+1)
; add_grain ( x ) (y-1)
; add_grain (x+1) ( y )
; add_grain (x-1) ( y )
let add_sand n x y
= for i = 1 to n
do add_grain x y
done
let avalanche ()
= while Hashtbl.length unstable > 0
do
let unstable' = Hashtbl.fold (fun (x,y) () r -> (x,y) :: r) unstable []
in List.iter (fun (x,y) -> topple x y ) unstable'
done
end
(* testing *)
let ()
= let module S = Make (struct let m = 11 let n = 11 end)
in S.add_sand 500 5 5
; S.avalanche ()
; S.print ()
|
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
| #Java | Java | import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"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";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(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) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
} |
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
| #jq | jq |
def commands:
"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 ";
# produce a "dictionary" in the form of an array of {prefix, word} objects
def dictionary:
reduce (splits(" +") | select(length>0)) as $w ([];
. + [$w | {prefix: sub("[a-z]+";""), word: ascii_upcase} ]);
def translate($dict):
# input: a string; $command: a {prefix, word} object
def match($command):
. as $uc
| startswith($command.prefix) and ($command.word | startswith($uc));
if length==0 then ""
else ascii_upcase
| first($dict[] as $command | select( match($command) ) | $command | .word)
// "*error*"
end;
# Emit the translation of an entire "sentence"
def translation:
(commands|dictionary) as $dict
| reduce splits(" +") as $w (""; . + ($w|translate($dict)) + " ")
| sub(" $";"");
# Example:
"riG rePEAT copies put mo rest types fup. 6 poweRin"
| translation
|
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
| #Julia | Julia | const 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 "
function validate(commands::AbstractVector{<:AbstractString},
minlens::AbstractVector{<:Integer}, words::AbstractVector{<:AbstractString})
r = String[]
for word in words
matchfound = false
for (i, command) in enumerate(commands)
if iszero(minlens[i]) || length(word) ∉ minlens[i]:length(command)
continue
end
if startswith(lowercase(command), lowercase(word))
push!(r, uppercase(command))
matchfound = true
break
end
end
!matchfound && push!(r, "*error*")
end
return r
end
commands = split(strip(table))
minlens = count.(isupper, commands)
sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
words = split(sentence)
result = validate(commands, minlens, words)
println("User words: ", join(lpad.(words, 11)))
println("Full words: ", join(lpad.(result, 11))) |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).
Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.
To make things more interesting, this task is specifically about finding odd abundant numbers.
Task
Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
References
OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| #11l | 11l | V oddNumber = 1
V aCount = 0
V dSum = 0
F divisorSum(n)
V sum = 1
V i = Int(sqrt(n) + 1)
L(d) 2 .< i
I n % d == 0
sum += d
V otherD = n I/ d
I otherD != d
sum += otherD
R sum
print(‘The first 25 abundant odd numbers:’)
L aCount < 25
dSum = divisorSum(oddNumber)
I dSum > oddNumber
aCount++
print(‘#5 proper divisor sum: #.’.format(oddNumber, dSum))
oddNumber += 2
L aCount < 1000
dSum = divisorSum(oddNumber)
I dSum > oddNumber
aCount++
oddNumber += 2
print("\n1000th abundant odd number:")
print(‘ ’(oddNumber - 2)‘ proper divisor sum: ’dSum)
oddNumber = 1000000001
V found = 0B
L !found
dSum = divisorSum(oddNumber)
I dSum > oddNumber
found = 1B
print("\nFirst abundant odd number > 1 000 000 000:")
print(‘ ’oddNumber‘ proper divisor sum: ’dSum)
oddNumber += 2 |
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
| #Julia | Julia | import Base.+, Base.print
struct Sandpile
pile::Matrix{UInt8}
end
function Sandpile(s::String)
arr = [parse(UInt8, x.match) for x in eachmatch(r"\d+", s)]
siz = isqrt(length(arr))
return Sandpile(reshape(UInt8.(arr), siz, siz)')
end
const HMAX = 3
function avalanche!(s::Sandpile, lim=HMAX)
nrows, ncols = size(s.pile)
while any(x -> x > lim, s.pile)
for j in 1:ncols, i in 1:nrows
if s.pile[i, j] > lim
i > 1 && (s.pile[i - 1, j] += 1)
i < nrows && (s.pile[i + 1, j] += 1)
j > 1 && (s.pile[i, j - 1] += 1)
j < ncols && (s.pile[i, j + 1] += 1)
s.pile[i, j] -= 4
end
end
end
s
end
+(s1::Sandpile, s2::Sandpile) = avalanche!(Sandpile((s1.pile + s2.pile)))
function print(io::IO, s::Sandpile)
for row in 1:size(s.pile)[1]
for col in 1:size(s.pile)[2]
print(io, lpad(s.pile[row, col], 4))
end
println()
end
end
const s1 = Sandpile("""
1 2 0
2 1 1
0 1 3""")
const s2 = Sandpile("""
2 1 3
1 0 1
0 1 0""")
const s3 = Sandpile("""
3 3 3
3 3 3
3 3 3""")
const s3_id = Sandpile("""
2 1 2
1 0 1
2 1 2""")
const s3a = Sandpile("""
4 3 3
3 1 2
0 2 3""")
println("Avalanche reduction to group:\n", s3a, " =>")
println(avalanche!(s3a), "\n")
println("Commutative Property:\ns1 + s2 =\n", s1 + s2, "\ns2 + s1 =\n", s2 + s1, "\n")
println("Addition:\n", s3, " +\n", s3_id, " =\n", s3 + s3_id, "\n")
println(s3_id, " +\n", s3_id, " =\n", s3_id + s3_id, "\n")
|
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.
| #Common_Lisp | Common Lisp | (defgeneric kar (kons)
(:documentation "Return the kar of a kons."))
(defgeneric kdr (kons)
(:documentation "Return the kdr of a kons."))
(defun konsp (object &aux (args (list object)))
"True if there are applicable methods for kar and kdr on object."
(not (or (endp (compute-applicable-methods #'kar args))
(endp (compute-applicable-methods #'kdr args)))))
(deftype kons ()
'(satisfies konsp)) |
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.
| #Component_Pascal | Component Pascal |
(* Abstract type *)
Object = POINTER TO ABSTRACT RECORD END;
(* Integer inherits Object *)
Integer = POINTER TO RECORD (Object)
i: INTEGER
END;
(* Point inherits Object *)
Point = POINTER TO RECORD (Object)
x,y: REAL
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.
| #Oz | Oz | declare
fun {Ack M N}
if M == 0 then N+1
elseif N == 0 then {Ack M-1 1}
else {Ack M-1 {Ack M N-1}}
end
end
in
{Show {Ack 3 7}} |
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
| #Perl | Perl | #!/usr/bin/perl
use strict; # http://www.rosettacode.org/wiki/Abelian_sandpile_model
use warnings;
my ($high, $wide) = split ' ', qx(stty size);
my $mask = "\0" x $wide . ("\0" . "\177" x ($wide - 2) . "\0") x ($high - 5) .
"\0" x $wide;
my $pile = $mask =~ s/\177/ rand() < 0.02 ? chr 64 + rand 20 : "\0" /ger;
for ( 1 .. 1e6 )
{
print "\e[H", $pile =~ tr/\0-\177/ 1-~/r, "\n$_";
my $add = $pile =~ tr/\1-\177/\0\0\0\200/r; # set high bit for >=4
$add =~ /\200/ or last;
$pile =~ tr/\4-\177/\0-\173/; # subtract 4 if >=4
for ("\0$add", "\0" x $wide . $add, substr($add, 1), substr $add, $wide)
{
$pile |= $_;
$pile =~ tr/\200-\377/\1-\176/; # add one to each neighbor of >=4
$pile &= $mask;
}
select undef, undef, undef, 0.1; # comment out for full speed
} |
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
| #JavaScript | JavaScript | (() => {
'use strict';
// withExpansions :: [(String, Int)] -> String -> String
const withExpansions = tbl => s =>
unwords(map(expanded(tbl), words(s)));
// expanded :: [(String, Int)] -> String -> String
const expanded = tbl => s => {
const
lng = s.length,
u = toUpper(s),
p = wn => {
const [w, n] = Array.from(wn);
return lng >= n && isPrefixOf(u, w);
}
return maybe(
'*error*',
fst,
0 < lng ? (
find(p, tbl)
) : Just(Tuple([], 0))
);
};
// cmdsFromString :: String -> [(String, Int)]
const cmdsFromString = s =>
fst(foldr(
(w, a) => {
const [xs, n] = Array.from(a);
return isDigit(head(w)) ? (
Tuple(xs, parseInt(w, 10))
) : Tuple(
[Tuple(toUpper(w), n)].concat(xs),
0
);
},
Tuple([], 0),
words(s)
));
// TEST -----------------------------------------------
const main = () => {
// table :: [(String, Int)]
const table = cmdsFromString(
`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`
);
return fTable(
'Abbreviation tests:\n',
s => "'" + s + "'",
s => "\n\t'" + s + "'",
withExpansions(table),
[
'riG rePEAT copies put mo rest types fup. 6 poweRin',
''
]
);
};
// GENERIC FUNCTIONS ----------------------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (f, g) => x => f(g(x));
// find :: (a -> Bool) -> [a] -> Maybe a
const find = (p, xs) => {
for (let i = 0, lng = xs.length; i < lng; i++) {
if (p(xs[i])) return Just(xs[i]);
}
return Nothing();
};
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
1 < f.length ? (
(a, b) => f(b, a)
) : (x => y => f(y)(x));
// foldl1 :: (a -> a -> a) -> [a] -> a
const foldl1 = (f, xs) =>
1 < xs.length ? xs.slice(1)
.reduce(f, xs[0]) : xs[0];
// foldr :: (a -> b -> b) -> b -> [a] -> b
const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// fTable :: String -> (a -> String) ->
// (b -> String) -> (a -> b) -> [a] -> String
const fTable = (s, xShow, fxShow, f, xs) => {
// Heading -> x display function ->
// fx display function ->
// f -> values -> tabular string
const
ys = map(xShow, xs),
w = maximum(map(length, ys)),
rows = zipWith(
(a, b) => justifyRight(w, ' ', a) + ' -> ' + b,
ys,
map(compose(fxShow, f), xs)
);
return s + '\n' + unlines(rows);
};
// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;
// isDigit :: Char -> Bool
const isDigit = c => {
const n = ord(c);
return 48 <= n && 57 >= n;
};
// isPrefixOf takes two lists or strings and returns
// true iff the first is a prefix of the second.
// isPrefixOf :: [a] -> [a] -> Bool
// isPrefixOf :: String -> String -> Bool
const isPrefixOf = (xs, ys) => {
const go = (xs, ys) => {
const intX = xs.length;
return 0 < intX ? (
ys.length >= intX ? xs[0] === ys[0] && go(
xs.slice(1), ys.slice(1)
) : false
) : true;
};
return 'string' !== typeof xs ? (
go(xs, ys)
) : ys.startsWith(xs);
};
// justifyRight :: Int -> Char -> String -> String
const justifyRight = (n, cFiller, s) =>
n > s.length ? (
s.padStart(n, cFiller)
) : s;
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// maximum :: Ord a => [a] -> a
const maximum = xs =>
0 < xs.length ? (
foldl1((a, x) => x > a ? x : a, xs)
) : undefined;
// maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = (v, f, m) =>
m.Nothing ? v : f(m.Just);
// ord :: Char -> Int
const ord = c => c.codePointAt(0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// toUpper :: String -> String
const toUpper = s => s.toLocaleUpperCase();
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
// words :: String -> [String]
const words = s => s.split(/\s+/);
// Use of `take` and `length` here allows zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const
lng = Math.min(length(xs), length(ys)),
as = take(lng, xs),
bs = take(lng, ys);
return Array.from({
length: lng
}, (_, i) => f(as[i], bs[i], i));
};
// MAIN ---
return main();
})(); |
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
| #Kotlin | Kotlin | // version 1.1.4-3
val r = Regex("[ ]+")
val 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 "
fun validate(commands: List<String>, minLens: List<Int>, words: List<String>): List<String> {
if (words.isEmpty()) return emptyList<String>()
val results = mutableListOf<String>()
for (word in words) {
var matchFound = false
for ((i, command) in commands.withIndex()) {
if (minLens[i] == 0 || word.length !in minLens[i] .. command.length) continue
if (command.startsWith(word, true)) {
results.add(command.toUpperCase())
matchFound = true
break
}
}
if (!matchFound) results.add("*error*")
}
return results
}
fun main(args: Array<String>) {
val commands = table.trimEnd().split(r)
val minLens = MutableList(commands.size) { commands[it].count { c -> c.isUpperCase() } }
val sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
val words = sentence.trim().split(r)
val results = validate(commands, minLens, words)
print("user words: ")
for (j in 0 until words.size) print("${words[j].padEnd(results[j].length)} ")
print("\nfull words: ")
for (j in 0 until results.size) print("${results[j]} ")
println()
} |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).
Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.
To make things more interesting, this task is specifically about finding odd abundant numbers.
Task
Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
References
OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| #360_Assembly | 360 Assembly | * Abundant odd numbers 18/09/2019
ABUNODDS CSECT
USING ABUNODDS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R8,0 n=0
LA R6,3 i=3
DO WHILE=(C,R8,LT,NN1) do i=3 by 2 until n>=nn1
BAL R14,SIGMA s=sigma(i)
IF CR,R9,GT,R6 THEN if s>i then
LA R8,1(R8) n++
BAL R14,PRINT print results
ENDIF , endif
LA R6,2(R6) i+=2
ENDDO , enddo i
LA R8,0 n=0
LA R6,3 i=3
XR R1,R1 f=false
DO WHILE=(C,R1,EQ,=F'0') do i=3 by 2 while not f
BAL R14,SIGMA s=sigma(i)
IF CR,R9,GT,R6 THEN if s>i then
LA R8,1(R8) n++
IF C,R8,GE,NN2 THEN if n>=nn2 then
BAL R14,PRINT print results
LA R1,1 f=true
ENDIF , endif
ENDIF , endif
LA R6,2(R6) i+=2
ENDDO , enddo i
LA R8,0 n=0
L R6,NN3 i=mm3
LA R6,1(R6) +1
XR R1,R1 f=false
DO WHILE=(C,R1,EQ,=F'0') do i=nn3+1 by 2 while not f
BAL R14,SIGMA s=sigma(i)
IF CR,R9,GT,R6 THEN if s>i then
BAL R14,PRINT print results
LA R1,1 f=true
ENDIF , endif
LA R6,2(R6) i+=2
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
SIGMA CNOP 0,4 ---- subroutine sigma
LA R9,1 s=1
LA R7,3 j=3
LR R5,R7 j
MR R4,R7 j*j
DO WHILE=(CR,R5,LT,R6) do j=3 by 2 while j*j<i
LR R4,R6 i
SRDA R4,32 ~
DR R4,R7 i/j
IF LTR,R4,Z,R4 THEN if mod(i,j)=0 then
AR R9,R7 s+j
LR R4,R6 i
SRDA R4,32 ~
DR R4,R7 i/j
AR R9,R5 s=s+j+i/j
ENDIF , endif
LA R7,2(R7) j+=2
LR R5,R7 j
MR R4,R7 j*j
ENDDO , enddo j
IF CR,R5,EQ,R6 THEN if j*j=i then
AR R9,R7 s=s+j
ENDIF , endif
BR R14 ---- end of subroutine sigma
PRINT CNOP 0,4 ---- subroutine print
XDECO R8,XDEC edit n
MVC BUF(4),XDEC+8 output n
XDECO R6,BUF+14 edit & output i
XDECO R9,BUF+33 edit & output s
XPRNT BUF,L'BUF print buffer
BR R14 ---- end of subroutine print
NN1 DC F'25' nn1=25
NN2 DC F'1000' nn2=1000
NN3 DC F'1000000000' nn3=1000000000
BUF DC CL80'.... - number=............ sigma=............'
XDEC DS CL12 temp for edit
REGEQU equate registers
END ABUNODDS |
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
| #Lua | Lua | sandpile.__index = sandpile
sandpile.new = function(self, vals)
local inst = setmetatable({},sandpile)
inst.cell, inst.dim = {}, #vals
for r = 1, inst.dim do
inst.cell[r] = {}
for c = 1, inst.dim do
inst.cell[r][c] = vals[r][c]
end
end
return inst
end
sandpile.add = function(self, other)
local vals = {}
for r = 1, self.dim do
vals[r] = {}
for c = 1, self.dim do
vals[r][c] = self.cell[r][c] + other.cell[r][c]
end
end
local inst = sandpile:new(vals)
inst:iter()
return inst
end
local s1 = sandpile:new{{1,2,0},{2,1,1},{0,1,3}}
local s2 = sandpile:new{{2,1,3},{1,0,1},{0,1,0}}
print("s1 =") s1:draw()
print("\ns2 =") s2:draw()
local s1ps2 = s1:add(s2)
print("\ns1 + s2 =") s1ps2:draw()
local s2ps1 = s2:add(s1)
print("\ns2 + s1 =") s2ps1:draw()
local topple = sandpile:new{{4,3,3},{3,1,2},{0,2,3}}
print("\ntopple, before =") topple:draw()
topple:iter()
print("\ntopple, after =") topple:draw()
local s3 = sandpile:new{{3,3,3},{3,3,3},{3,3,3}}
print("\ns3 =") s3:draw()
local s3_id = sandpile:new{{2,1,2},{1,0,1},{2,1,2}}
print("\ns3_id =") s3_id:draw()
local s3ps3_id = s3:add(s3_id)
print("\ns3 + s3_id =") s3ps3_id:draw()
local s3_idps3_id = s3_id:add(s3_id)
print("\ns3_id + s3_id =") s3_idps3_id:draw() |
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.
| #Crystal | Crystal | abstract class Animal # only abstract class can have abstract methods
abstract def move
abstract def think
# abstract class can have normal fields and methods
def initialize(@name : String)
end
def process
think
move
end
end
# WalkingAnimal still have to be declared abstract because `think` was not implemented
abstract class WalkingAnimal < Animal
def move
puts "#{@name} walks"
end
end
class Human < WalkingAnimal
property in_car = false
def move
if in_car
puts "#{@name} drives a car"
else
super
end
end
def think
puts "#{@name} thinks"
end
end
# Animal.new # => can't instantiate abstract class
he = Human.new("Andrew") # ok
he.process |
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.
| #D | D | import std.stdio;
class Foo {
// abstract methods can have an implementation for
// use in super calls.
abstract void foo() {
writeln("Test");
}
}
interface Bar {
void bar();
// Final interface methods are allowed.
final int spam() { return 1; }
}
class Baz : Foo, Bar { // Super class must come first.
override void foo() {
writefln("Meep");
super.foo();
}
void bar() {}
}
void main() {} |
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.
| #PARI.2FGP | PARI/GP | A(m,n)={
if(m,
if(n,
A(m-1, A(m,n-1))
,
A(m-1,1)
)
,
n+1
)
}; |
http://rosettacode.org/wiki/Abbreviations,_automatic | Abbreviations, automatic | 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.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbreviation length of that list could be automatically (programmatically) determined.
For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miércoles xueves vienres sábadu
Bazar_gÜnÜ Birinci_gÜn Çkinci_gÜn ÜçÜncÜ_gÜn DÖrdÜncÜ_gÜn Bes,inci_gÜn Altòncò_gÜn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mèkredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^lí úterÿ str^eda c^tvrtek pátek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaùdo Vendredo Sabato
pÜhapäev esmaspäev teisipäev kolmapäev neljapäev reede laupäev
Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mércores Joves Venres Sábado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
pópule pó`akahi pó`alua pó`akolu pó`ahá pó`alima pó`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasárnap hétfö kedd szerda csütörtök péntek szombat
Sunnudagur Mánudagur ╞riδjudagur Miδvikudagar Fimmtudagur FÖstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
Dé_Domhnaigh Dé_Luain Dé_Máirt Dé_Ceadaoin Dé_ardaoin Dé_hAoine Dé_Sathairn
domenica lunedí martedí mercoledí giovedí venerdí sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_rì xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minòmishi mártes mièrkoles misheushi bèrnashi mishábaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sφndag mandag tirsdag onsdag torsdag fredag lφrdag
lo_dimenge lo_diluns lo_dimarç lo_dimèrcres lo_dijòus lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabièrna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terça-feire quarta-feire quinta-feire sexta-feira såbado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminicª Luni Mart'i Miercuri Joi Vineri Sâmbªtª
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-màirt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miércoles jueves viernes sábado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
söndag måndag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Lé-pài-jít Pài-it Pài-jï Pài-sañ Pài-sì Pài-gÖ. Pài-lák
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Çar,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nhâ.t Thú*_Hai Thú*_Ba Thú*_Tu* Thú*_Na'm Thú*_Sáu Thú*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gÜnÜ Bazar_ærtæsi Çærs,ænbæ_axs,amò Çærs,ænbæ_gÜnÜ CÜmæ_axs,amò CÜmæ_gÜnÜ CÜmæ_Senbæ
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sábado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tiàn xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
djadomingu djaluna djamars djarason djaweps djabièrnè djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau
Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.
To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).
Notes concerning the above list of words
each line has a list of days-of-the-week for a language, separated by at least one blank
the words on each line happen to be in order, from Sunday ──► Saturday
most lines have words in mixed case and some have all manner of accented words and other characters
some words were translated to the nearest character that was available to code page 437
the characters in the words are not restricted except that they may not have imbedded blanks
for this example, the use of an underscore (_) was used to indicate a blank in a word
Task
The list of words (days of the week) needn't be verified/validated.
Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.
A blank line (or a null line) should return a null string.
Process and show the output for at least the first five lines of the file.
Show all output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | F shortest_abbreviation_length(line, list_size)
V words = line.split(‘ ’)
V word_count = words.len
I word_count != list_size
X ValueError(‘Not enough entries, expected #. found #.’.format(list_size, word_count))
V abbreviation_length = 1
L
V abbreviations = Set(words.map(word -> word[0 .< @abbreviation_length]))
I abbreviations.len == list_size
R abbreviation_length
abbreviation_length++
F automatic_abbreviations(filename, words_per_line)
L(line) File(filename).read().split("\n")
I line.len > 0
V length = shortest_abbreviation_length(line, words_per_line)
print(‘#2 #.’.format(length, line))
E
print()
automatic_abbreviations(‘daysOfWeek.txt’, 7) |
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
| #Phix | Phix | -- demo\rosetta\Abelian_sandpile_model.exw
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer
sequence board = {{0,0,0},
{0,0,0},
{0,0,0}}
procedure drop(integer y, x)
sequence moves = {}
while true do
board[y,x] += 1
if board[y,x]>=4 then
board[y,x] -= 4
moves &= {{y,x-1},{y,x+1},{y-1,x},{y+1,x}}
end if
-- extend board if rqd (maintain a border of zeroes)
if x=1 then -- extend left
for i=1 to length(board) do
board[i] = prepend(board[i],0)
end for
for i=1 to length(moves) do
moves[i][2] += 1
end for
elsif x=length(board[1]) then -- extend right
for i=1 to length(board) do
board[i] = append(board[i],0)
end for
end if
-- (copy the all-0 lines from the other end...)
if y=1 then -- extend up
board = prepend(board,board[$])
for i=1 to length(moves) do
moves[i][1] += 1
end for
elsif y=length(board) then -- extend down
board = append(board,board[1])
end if
if length(moves)=0 then exit end if
{y,x} = moves[$]
moves = moves[1..$-1]
end while
IupUpdate(canvas)
end procedure
function timer_cb(Ihandle /*ih*/)
integer y = floor(length(board)/2)+1,
x = floor(length(board[1])/2)+1
drop(y,x)
return IUP_DEFAULT
end function
function redraw_cb(Ihandle ih, integer /*posx*/, integer /*posy*/)
IupGLMakeCurrent(ih)
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
for y=1 to length(board) do
for x=1 to length(board[1]) do
integer c = board[y][x]
if c!=0 then
integer colour = {CD_VIOLET,CD_RED,CD_BLUE}[c]
cdCanvasPixel(cddbuffer, x, y, colour)
end if
end for
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
IupGLMakeCurrent(ih)
atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
cddbuffer = cdCreateCanvas(CD_GL, "300x100 %g", {res})
cdCanvasSetBackground(cddbuffer, CD_PARCHMENT)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupGLCanvas("RASTERSIZE=300x100")
IupSetCallbacks({canvas}, {"ACTION", Icallback("redraw_cb"),
"MAP_CB", Icallback("map_cb")})
dlg = IupDialog(canvas,"TITLE=\"Abelian sandpile model\"")
IupShow(dlg)
Ihandle timer = IupTimer(Icallback("timer_cb"), 10)
IupMainLoop()
IupClose()
end procedure
main()
|
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
| #Julia | Julia |
const commandtable = """
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"""
function makedict(tbl)
str = split(uppercase(tbl), r"\s+")
dict = Dict{String, String}()
for (i, s) in enumerate(str)
if (n = tryparse(Int, s)) != nothing
dict[str[i-1][1:n]] = str[i-1]
else
dict[s] = s
end
end
dict
end
function okabbrev(dict, abb)
for i in length(abb):-1:1
if haskey(dict, abb[1:i])
com = dict[abb[1:i]]
if length(abb) <= length(com) && abb == com[1:length(abb)]
return dict[abb[1:i]]
end
end
end
return "*error*"
end
formattedprint(arr, n) = (for s in arr print(rpad(s, n)) end; println())
function teststring(str)
d = makedict(commandtable)
commands = split(str, r"\s+")
formattedprint(commands, 9)
formattedprint([okabbrev(d, uppercase(s)) for s in commands], 9)
end
teststring("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
| #Lua | Lua | #!/usr/bin/lua
local list1 = [[
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 ]]
local indata1 = [[riG rePEAT copies put mo rest types
fup. 6 poweRin]]
local indata2 = [[ALT aLt ALTE ALTER AL ALF ALTERS TER A]]
local indata3 = [[o ov oVe over overL overla]]
local function split(text)
local result = {}
for w in string.gmatch(text, "%g+") do
result[#result+1]=w
-- print(#result,w,#w)
end
return result
end
local function print_line( t )
for i = 1,#t do
io.write( string.format("%s ", t[i] ) )
end
print()
end
local function is_valid(cmd,abbrev)
--print(abbrev,cmd,"##")
local sm = string.match( cmd:lower(), abbrev:lower() )
if sm == nil then return -1 end
-- test if any lowercase in "cmd"
if false then do -- NOTE!: requirement spec error .. put not equal PUT
local lowcase = string.match(cmd,"%l+")
if lowcase == nil then return -2 end
if #lowcase < 1 then return -3 end
end
end
-- test if abbrev is too long
if #abbrev > #cmd then return -4 end
--- num caps in "cmd" is minimum length of abbrev
local caps = string.match(cmd,"%u+")
if #abbrev < #caps then return -5 end
local s1 = abbrev:sub(1,#caps)
local s2 = cmd:sub(1,#caps)
if s1:lower() ~= s2:lower() then return -6 end
return 1
end
local function start()
local t1 = {}
local t2 = {}
local result = {}
t1 = split(list1)
t2 = split(indata1)
print_line(t2);
for i = 1,#t2 do
good = 0
for j = 1,#t1 do
local abbrev = t2[i]
local cmd = t1[j]
good = is_valid(cmd,abbrev)
if good==1 then do
result[#result+1] = t1[j]:upper()
break end
end --if
end --for j
if good < 1 then result[#result+1] = "*error*" end
end --for i
print_line(result)
end
start() -- run the program
|
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).
Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.
To make things more interesting, this task is specifically about finding odd abundant numbers.
Task
Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
References
OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program abundant64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBDIVISORS, 1000
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n"
szMessError: .asciz "\033[31mError !!!\n"
szMessErrGen: .asciz "Error end program.\n"
szMessNbPrem: .asciz "This number is prime !!!.\n"
szMessOverflow: .asciz "Dépassement de capacité vérification premier.\n"
szMessResultFact: .asciz "// "
szCarriageReturn: .asciz "\n"
/* datas message display */
szMessEntete: .asciz "The first 25 abundant odd numbers are:\n"
szMessResult: .asciz "Number : @ sum : @ \n"
szMessEntete1: .asciz "The 1000 odd abundant number :\n"
szMessEntete2: .asciz "First odd abundant number > 1000000000 :\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
tbZoneDecom: .skip 16 * NBDIVISORS // facteur 8 octets nombre 8 octets
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // program start
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
ldr x0,qAdrszMessEntete // display result message
bl affichageMess
mov x2,#1
mov x3,#0
1:
mov x0,x2 // number
bl testAbundant
cmp x0,#1
bne 3f
add x3,x3,#1
mov x0,x2
mov x4,x1 // save sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
mov x5,x0
mov x0,x4 // sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
bl affichageMess
3:
add x2,x2,#2
cmp x3,#25
blt 1b
/* 1000 abundant number */
ldr x0,qAdrszMessEntete1
bl affichageMess
mov x2,#1
mov x3,#0
4:
mov x0,x2 // number
bl testAbundant
cmp x0,#1
bne 6f
add x3,x3,#1
6:
cmp x3,#1000
cinc x2,x2,lt // add two
cinc x2,x2,lt
blt 4b
mov x0,x2
mov x4,x1 // save sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
mov x5,x0
mov x0,x4 // sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
bl affichageMess
/* abundant number>1000000000 */
ldr x0,qAdrszMessEntete2
bl affichageMess
ldr x2,iN10P9
add x2,x2,#1
mov x3,#0
7:
mov x0,x2 // number
bl testAbundant
cmp x0,#1
beq 8f
add x2,x2,#2
b 7b
8:
mov x0,x2
mov x4,x1 // save sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
mov x5,x0
mov x0,x4 // sum
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
bl affichageMess
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszMessError: .quad szMessError
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrtbZoneDecom: .quad tbZoneDecom
qAdrszMessEntete: .quad szMessEntete
qAdrszMessEntete1: .quad szMessEntete1
qAdrszMessEntete2: .quad szMessEntete2
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
iN10P9: .quad 1000000000
/******************************************************************/
/* test if number is abundant number */
/******************************************************************/
/* x0 contains the number */
/* x0 return 1 if abundant number else return 0 */
/* x1 return sum */
testAbundant:
stp x2,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
mov x6,x0 // save number
ldr x1,qAdrtbZoneDecom
bl decompFact // create area of divisors
cmp x0,#1 // no divisors
ble 99f
lsl x5,x6,#1 // abondant number ?
cmp x5,x2
bgt 99f // no -> end
mov x0,#1
sub x1,x2,x6 // sum
b 100f
99:
mov x0,0
100:
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x2,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* decomposition en facteur */
/******************************************************************/
/* x0 contient le nombre à decomposer */
decompFact:
stp x3,lr,[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
stp x10,x11,[sp,-16]! // save registres
mov x5,x1
mov x8,x0 // save number
bl isPrime // prime ?
cmp x0,#1
beq 98f // yes is prime
mov x1,#1
str x1,[x5] // first factor
mov x12,#1 // divisors sum
mov x11,#1 // number odd divisors
mov x4,#1 // indice divisors table
mov x1,#2 // first divisor
mov x6,#0 // previous divisor
mov x7,#0 // number of same divisors
2:
mov x0,x8 // dividende
udiv x2,x0,x1 // x1 divisor x2 quotient x3 remainder
msub x3,x2,x1,x0
cmp x3,#0
bne 5f // if remainder <> zero -> no divisor
mov x8,x2 // else quotient -> new dividende
cmp x1,x6 // same divisor ?
beq 4f // yes
mov x7,x4 // number factors in table
mov x9,#0 // indice
21:
ldr x10,[x5,x9,lsl #3 ] // load one factor
mul x10,x1,x10 // multiply
str x10,[x5,x7,lsl #3] // and store in the table
tst x10,#1 // divisor odd ?
cinc x11,x11,ne
add x12,x12,x10
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 21b
mov x4,x7
mov x6,x1 // new divisor
b 7f
4: // same divisor
sub x9,x4,#1
mov x7,x4
41:
ldr x10,[x5,x9,lsl #3 ]
cmp x10,x1
sub x13,x9,1
csel x9,x13,x9,ne
bne 41b
sub x9,x4,x9
42:
ldr x10,[x5,x9,lsl #3 ]
mul x10,x1,x10
str x10,[x5,x7,lsl #3] // and store in the table
tst x10,#1 // divsor odd ?
cinc x11,x11,ne
add x12,x12,x10
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 42b
mov x4,x7
b 7f // and loop
/* not divisor -> increment next divisor */
5:
cmp x1,#2 // if divisor = 2 -> add 1
add x13,x1,#1 // add 1
add x14,x1,#2 // else add 2
csel x1,x13,x14,eq
b 2b
/* divisor -> test if new dividende is prime */
7:
mov x3,x1 // save divisor
cmp x8,#1 // dividende = 1 ? -> end
beq 10f
mov x0,x8 // new dividende is prime ?
mov x1,#0
bl isPrime // the new dividende is prime ?
cmp x0,#1
bne 10f // the new dividende is not prime
cmp x8,x6 // else dividende is same divisor ?
beq 9f // yes
mov x7,x4 // number factors in table
mov x9,#0 // indice
71:
ldr x10,[x5,x9,lsl #3 ] // load one factor
mul x10,x8,x10 // multiply
str x10,[x5,x7,lsl #3] // and store in the table
tst x10,#1 // divsor odd ?
cinc x11,x11,ne
add x12,x12,x10
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 71b
mov x4,x7
mov x7,#0
b 11f
9:
sub x9,x4,#1
mov x7,x4
91:
ldr x10,[x5,x9,lsl #3 ]
cmp x10,x8
sub x13,x9,#1
csel x9,x13,x9,ne
bne 91b
sub x9,x4,x9
92:
ldr x10,[x5,x9,lsl #3 ]
mul x10,x8,x10
str x10,[x5,x7,lsl #3] // and store in the table
tst x10,#1 // divisor odd ?
cinc x11,x11,ne
add x12,x12,x10
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 92b
mov x4,x7
b 11f
10:
mov x1,x3 // current divisor = new divisor
cmp x1,x8 // current divisor > new dividende ?
ble 2b // no -> loop
/* end decomposition */
11:
mov x0,x4 // return number of table items
mov x2,x12 // return sum
mov x1,x11 // return number of odd divisor
mov x3,#0
str x3,[x5,x4,lsl #3] // store zéro in last table item
b 100f
98:
//ldr x0,qAdrszMessNbPrem
//bl affichageMess
mov x0,#1 // return code
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
mov x0,#-1 // error code
b 100f
100:
ldp x10,x11,[sp],16 // restaur des 2 registres
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 x3,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessErrGen: .quad szMessErrGen
qAdrszMessNbPrem: .quad szMessNbPrem
/***************************************************/
/* Verification si un nombre est premier */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier 0 sinon */
isPrime:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
sub x1,x0,#1
cmp x2,0
beq 99f // retourne zéro
cmp x2,2 // pour 1 et 2 retourne 1
ble 2f
mov x0,#2
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,3
beq 2f
mov x0,#3
bl moduloPux64
blt 100f // erreur overflow
cmp x0,#1
bne 99f
cmp x2,5
beq 2f
mov x0,#5
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,7
beq 2f
mov x0,#7
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,11
beq 2f
mov x0,#11
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,13
beq 2f
mov x0,#13
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
2:
cmn x0,0 // carry à zero pas d'erreur
mov x0,1 // premier
b 100f
99:
cmn x0,0 // carry à zero pas d'erreur
mov x0,#0 // Pas premier
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/**************************************************************/
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/********************************************************/
/* x0 nombre */
/* x1 exposant */
/* x2 modulo */
moduloPux64:
stp x1,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
stp x9,x10,[sp,-16]! // save registres
cbz x0,100f
cbz x1,100f
mov x8,x0
mov x7,x1
mov x6,1 // resultat
udiv x4,x8,x2
msub x9,x4,x2,x8 // contient le reste
1:
tst x7,1
beq 2f
mul x4,x9,x6
umulh x5,x9,x6
//cbnz x5,99f
mov x6,x4
mov x0,x6
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x6,x3
2:
mul x8,x9,x9
umulh x5,x9,x9
mov x0,x8
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x9,x3
lsr x7,x7,1
cbnz x7,1b
mov x0,x6 // result
cmn x0,0 // carry à zero pas d'erreur
b 100f
99:
ldr x1,qAdrszMessOverflow
bl afficheErreur
cmp x0,0 // carry à un car erreur
mov x0,-1 // code erreur
100:
ldp x9,x10,[sp],16 // restaur des 2 registres
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessOverflow: .quad szMessOverflow
/***************************************************/
/* division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
stp x6,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x5,#0 // raz du reste R
mov x3,#128 // compteur de boucle
mov x4,#0 // dernier bit
1:
lsl x5,x5,#1 // on decale le reste de 1
tst x1,1<<63 // test du bit le plus à gauche
lsl x1,x1,#1 // on decale la partie haute du quotient de 1
beq 2f
orr x5,x5,#1 // et on le pousse dans le reste R
2:
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 3f
orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute
3:
orr x0,x0,x4 // position du dernier bit du quotient
mov x4,#0 // raz du bit
cmp x5,x2
blt 4f
sub x5,x5,x2 // on enleve le diviseur du reste
mov x4,#1 // dernier bit à 1
4:
// et boucle
subs x3,x3,#1
bgt 1b
lsl x1,x1,#1 // on decale le quotient de 1
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 5f
orr x1,x1,#1
5:
orr x0,x0,x4 // position du dernier bit du quotient
mov x3,x5
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x6,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/********************************************************/
/* 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/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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[sp]
sp[s_List] + sp[n_Integer] ^:= sp[s] + sp[ConstantArray[n, Dimensions[s]]]
sp[s_List] + sp[t_List] ^:= Module[{dim, r, tmp, neighbours}, dim = Dimensions[s];
r = s + t;
While[Max[r] > 3,
r = ArrayPad[r, 1, 0];
tmp = Quotient[r, 4];
r -= 4 tmp;
r += RotateLeft[tmp, {0, 1}] + RotateLeft[tmp, {1, 0}] +
RotateLeft[tmp, {0, -1}] + RotateLeft[tmp, {-1, 0}];
r = ArrayPad[r, -1];
];
sp[r]
]
Format[x_sp] := Grid[x[[1]]]
s1 = sp[{{1, 2, 0}, {2, 1, 1}, {0, 1, 3}}];
s2 = sp[{{2, 1, 3}, {1, 0, 1}, {0, 1, 0}}];
s3 = sp[ConstantArray[3, {3, 3}]];
s3id = sp[{{2, 1, 2}, {1, 0, 1}, {2, 1, 2}}];
s1 + s2
s2 + s1
sp[{{4, 3, 3}, {3, 1, 2}, {0, 2, 3}}] + sp[0]
s3 + s3id === s3
s3id + s3id === s3id |
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.
| #Delphi | Delphi | TSomeClass = class abstract (TObject)
...
end; |
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.
| #DWScript | DWScript | interface Foo {
to bar(a :int, b :int)
} |
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.
| #Pascal | Pascal | Program Ackerman;
function ackermann(m, n: Integer) : Integer;
begin
if m = 0 then
ackermann := n+1
else if n = 0 then
ackermann := ackermann(m-1, 1)
else
ackermann := ackermann(m-1, ackermann(m, n-1));
end;
var
m, n : Integer;
begin
for n := 0 to 6 do
for m := 0 to 3 do
WriteLn('A(', m, ',', n, ') = ', ackermann(m,n));
end. |
http://rosettacode.org/wiki/Abbreviations,_automatic | Abbreviations, automatic | 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.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbreviation length of that list could be automatically (programmatically) determined.
For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miércoles xueves vienres sábadu
Bazar_gÜnÜ Birinci_gÜn Çkinci_gÜn ÜçÜncÜ_gÜn DÖrdÜncÜ_gÜn Bes,inci_gÜn Altòncò_gÜn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mèkredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^lí úterÿ str^eda c^tvrtek pátek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaùdo Vendredo Sabato
pÜhapäev esmaspäev teisipäev kolmapäev neljapäev reede laupäev
Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mércores Joves Venres Sábado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
pópule pó`akahi pó`alua pó`akolu pó`ahá pó`alima pó`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasárnap hétfö kedd szerda csütörtök péntek szombat
Sunnudagur Mánudagur ╞riδjudagur Miδvikudagar Fimmtudagur FÖstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
Dé_Domhnaigh Dé_Luain Dé_Máirt Dé_Ceadaoin Dé_ardaoin Dé_hAoine Dé_Sathairn
domenica lunedí martedí mercoledí giovedí venerdí sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_rì xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minòmishi mártes mièrkoles misheushi bèrnashi mishábaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sφndag mandag tirsdag onsdag torsdag fredag lφrdag
lo_dimenge lo_diluns lo_dimarç lo_dimèrcres lo_dijòus lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabièrna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terça-feire quarta-feire quinta-feire sexta-feira såbado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminicª Luni Mart'i Miercuri Joi Vineri Sâmbªtª
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-màirt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miércoles jueves viernes sábado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
söndag måndag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Lé-pài-jít Pài-it Pài-jï Pài-sañ Pài-sì Pài-gÖ. Pài-lák
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Çar,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nhâ.t Thú*_Hai Thú*_Ba Thú*_Tu* Thú*_Na'm Thú*_Sáu Thú*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gÜnÜ Bazar_ærtæsi Çærs,ænbæ_axs,amò Çærs,ænbæ_gÜnÜ CÜmæ_axs,amò CÜmæ_gÜnÜ CÜmæ_Senbæ
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sábado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tiàn xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
djadomingu djaluna djamars djarason djaweps djabièrnè djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau
Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.
To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).
Notes concerning the above list of words
each line has a list of days-of-the-week for a language, separated by at least one blank
the words on each line happen to be in order, from Sunday ──► Saturday
most lines have words in mixed case and some have all manner of accented words and other characters
some words were translated to the nearest character that was available to code page 437
the characters in the words are not restricted except that they may not have imbedded blanks
for this example, the use of an underscore (_) was used to indicate a blank in a word
Task
The list of words (days of the week) needn't be verified/validated.
Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.
A blank line (or a null line) should return a null string.
Process and show the output for at least the first five lines of the file.
Show all output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program abbrAuto64.s */
/* store list of day in a file listDays.txt*/
/* and run the program abbrAuto64 listDays.txt */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 10000
.equ NBMAXIDAYS, 7
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre: .asciz "Nom du fichier : "
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Error detected.\n"
szMessErrBuffer: .asciz "buffer size too less !!"
szSpace: .asciz " "
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
sZoneConv: .skip 24
qAdrFicName: .skip 8
iTabAdrDays: .skip 8 * NBMAXIDAYS
iTabAdrDays2: .skip 8 * NBMAXIDAYS
sBufferDays: .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 process
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
/******************************************************************/
/* 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,qAdrsBufferDays // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,#READ // read file
svc #0
cmp x0,#0 // error ?
blt 99f
// extraction datas
ldr x1,qAdrsBufferDays // buffer address
add x1,x1,x0
mov x0,#0 // store zéro final
strb w0,[x1]
ldr x0,qAdriTabAdrDays // key string command table
ldr x1,qAdrsBufferDays // 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
qAdrszMessErreur: .quad szMessErreur
qAdrsBuffer: .quad sBuffer
qAdrsBufferDays: .quad sBufferDays
qAdriTabAdrDays: .quad iTabAdrDays
/******************************************************************/
/* extrac lines 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
1:
ldrb w3,[x6,x2]
cmp w3,#0
beq 4f // end
cmp w3,#0xA
beq 2f
cmp w3,#' ' // 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 22f
21:
add x2,x2,#1
22:
mov x0,x4 // store last day of line in table
str x4,[x7,x5,lsl #3]
mov x0,x5 // days number
bl traitLine // process a line of days
mov x5,#0 // new line
b 5f
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: // supress spaces
ldrb w3,[x6,x2]
cmp w3,#0
beq 100f
cmp w3,#' '
cinc x2,x2,eq
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
/******************************************************************/
/* processing a line */
/******************************************************************/
/* x0 contains days number in table */
traitLine: // INFO: traitLine
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
stp x10,x11,[sp,-16]! // save registres
stp x12,x13,[sp,-16]! // save registres
cmp x0,#1 // one day ?
bgt 1f // no
ldr x0,qAdrszCarriageReturn // yes display empty line
bl affichageMess
b 100f
1: // line OK
mov x6,x0 // days number
ldr x0,qAdriTabAdrDays
ldr x1,qAdriTabAdrDays2
mov x2,#0
11: // copy days table into other for display final
ldr x3,[x0,x2,lsl #3]
str x3,[x1,x2,lsl #3]
add x2,x2,#1
cmp x2,x6
ble 11b
ldr x0,qAdriTabAdrDays // and sort first table
mov x1,#0
add x2,x6,#1
bl insertionSort
mov x8,#1 // abbrevations counter
ldr x12,qAdriTabAdrDays
mov x2,#0
ldr x10,[x12,x2,lsl #3] // load first sorting day
mov x11,#0
mov x3,#1
2: // begin loop
ldr x4,[x12,x3,lsl #3] // load other day
mov x0,x10 // day1
mov x1,x4 // day 2
mov x2,#0 // position 0
bl compareChar
cmp x0,#0 // first letter equal ?
beq 3f
mov x10,x4 // no -> move day 2 in day 1
b 6f
3: // if equal
mov x7,x1 // characters length (1,2,3)
mov x11,#1 // letters position
4: // loop to compare letters days
mov x0,x10
mov x1,x4
mov x2,x7
bl compareChar
cmp x0,#0
bne 5f
cmp x5,#0 // if end
beq 5f
add x7,x7,x1 // next character
add x11,x11,#1 // count letter
b 4b
5:
add x11,x11,#1 // increment letters position
cmp x11,x8 // and store if > position précedente
csel x8,x11,x8,gt
//movgt x8,x11
mov x10,x4 // and day1 = day2
6:
add x3,x3,#1 // increment day
cmp x3,x6
ble 2b // and loop
mov x0,x8 // display position letter
ldr x1,qAdrsZoneConv
bl conversion10
//mov x2,#0
//strb x2,[x1,x0]
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszSpace
bl affichageMess
ldr x0,qAdriTabAdrDays2 // and display list origine days
mov x1,x6
bl displayListDays
100:
ldp x12,x13,[sp],16 // restaur des 2 registres
ldp x10,x11,[sp],16 // restaur des 2 registres
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
qAdrszSpace: .quad szSpace
qAdriTabAdrDays2: .quad iTabAdrDays2
/******************************************************************/
/* comparison character unicode */
/******************************************************************/
/* x0 contains address first string */
/* x1 contains address second string */
/* x2 contains the character position to compare */
/* x0 return 0 if equal 1 if > -1 if < */
/* x1 return character S1 size in octet if equal */
/* x2 return character S2 size in octet */
compareChar:
stp lr,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
ldrb w3,[x0,x2]
ldrb w4,[x1,x2]
cmp w3,w4 // compare first byte
blt 3f
bgt 4f
bne 100f
and w3,w3,#0b11100000 // 3 bytes ?
cmp w3,#0b11100000
bne 1f
add x2,x2,#1
ldrb w3,[x0,x2]
ldrb w4,[x1,x2]
cmp w3,w4
blt 3f
bgt 4f
bne 100f
add x2,x2,#1
ldrb w3,[x0,x2]
ldrb w4,[x1,x2]
cmp w3,w4
blt 3f
bgt 4f
bne 100f
mov x0,#0
mov x1,#3
b 100f
1:
cmp w3,#0b11000000 // 2 bytes ?
bne 2f
add x2,x2,#1
ldrb w3,[x0,x2]
ldrb w4,[x1,x2]
cmp w3,w4
blt 3f
bgt 4f
bne 100f
mov x0,#0
mov x1,#2
b 100f
2: // 1 byte
mov x0,#0
mov x1,#1
b 100f
3:
mov x0,#-1
b 100f
4:
mov x0,#1
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 lr,x3,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* control load */
/******************************************************************/
/* x0 contains string table */
/* x1 contains days number */
displayListDays:
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 x5,x0
mov x2,#0
1:
cmp x2,x1
bgt 2f
ldr x0,[x5,x2,lsl #3]
bl affichageMess
ldr x0,qAdrszSpace
bl affichageMess
add x2,x2,#1
b 1b
2:
ldr x0,qAdrszCarriageReturn
bl affichageMess
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
/************************************/
/* 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 w3,w4
blt 2f
bgt 3f
bne 100f // not equals
cmp w3,#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
/******************************************************************/
/* insertion sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
insertionSort:
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
add x3,x1,#1 // start index i
1: // start loop
ldr x1,[x6,x3,lsl #3] // load value A[i]
sub x5,x3,#1 // index j
2:
ldr x4,[x6,x5,lsl #3] // load value A[j]
mov x0,x4
bl comparStrings
cmp x0,#1 // compare value
bne 3f
add x5,x5,#1 // increment index j
str x4,[x6,x5,lsl #3] // store value A[j+1]
subs x5,x5,#2 // j = j - 1
bge 2b // loop if j >= 0
3:
add x5,x5,#1 // increment index j
str x1,[x6,x5,lsl #3] // store value A[i] in A[j+1]
add x3,x3,#1 // increment index i
cmp x3,x2 // end ?
blt 1b // no -> loop
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
/********************************************************/
/* 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
| #Python | Python | import numpy as np
import matplotlib.pyplot as plt
def iterate(grid):
changed = False
for ii, arr in enumerate(grid):
for jj, val in enumerate(arr):
if val > 3:
grid[ii, jj] -= 4
if ii > 0:
grid[ii - 1, jj] += 1
if ii < len(grid)-1:
grid[ii + 1, jj] += 1
if jj > 0:
grid[ii, jj - 1] += 1
if jj < len(grid)-1:
grid[ii, jj + 1] += 1
changed = True
return grid, changed
def simulate(grid):
while True:
grid, changed = iterate(grid)
if not changed:
return grid
if __name__ == '__main__':
start_grid = np.zeros((10, 10))
start_grid[4:5, 4:5] = 64
final_grid = simulate(start_grid.copy())
plt.figure()
plt.gray()
plt.imshow(start_grid)
plt.figure()
plt.gray()
plt.imshow(final_grid) |
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
| #Kotlin | Kotlin | import java.util.Locale
private const val 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 "
private data class Command(val name: String, val minLen: Int)
private fun parse(commandList: String): List<Command> {
val commands = mutableListOf<Command>()
val fields = commandList.trim().split(" ")
var i = 0
while (i < fields.size) {
val name = fields[i++]
var minLen = name.length
if (i < fields.size) {
val num = fields[i].toIntOrNull()
if (num != null && num in 1..minLen) {
minLen = num
i++
}
}
commands.add(Command(name, minLen))
}
return commands
}
private fun get(commands: List<Command>, word: String): String? {
for ((name, minLen) in commands) {
if (word.length in minLen..name.length && name.startsWith(word, true)) {
return name.toUpperCase(Locale.ROOT)
}
}
return null
}
fun main(args: Array<String>) {
val commands = parse(table)
val sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
val words = sentence.trim().split(" ")
val results = words.map { word -> get(commands, word) ?: "*error*" }
val paddedUserWords = words.mapIndexed { i, word -> word.padEnd(results[i].length) }
println("user words: ${paddedUserWords.joinToString(" ")}")
println("full words: ${results.joinToString(" ")}")
}
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ct, FunctionMatchQ, ValidFunctionQ, ProcessString]
ct = "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";
ct = FixedPoint[StringReplace[{"\n" -> "", Longest[" " ..] -> " "}], ct];
ct = StringSplit[ct, " "];
FunctionMatchQ[func_String, test_String] := Module[{min, max, l},
min = StringCount[func, Alternatives @@ CharacterRange["A", "Z"]];
max = StringLength[func];
l = StringLength[test];
If[min <= l <= max,
If[StringStartsQ[func, test, IgnoreCase -> True],
True
,
False
]
,
False
]
]
ValidFunctionQ[test_String] := Module[{val},
val = SelectFirst[ct, FunctionMatchQ[#, test] &, Missing[]];
If[MissingQ[val], "*error*", ToUpperCase[val]]
]
ProcessString[test_String] := Module[{parts},
parts = StringSplit[test];
StringRiffle[ValidFunctionQ /@ parts, " "]
]
ProcessString["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
| #MATLAB_.2F_Octave | MATLAB / Octave |
function R = abbreviations_easy(input)
CMD=strsplit(['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' ],' ');
for k=1:length(CMD)
cmd{k} = CMD{k}(CMD{k}<'a');
CMD{k} = upper(CMD{k});
end
ilist = strsplit(input,' ');
R = '';
for k=1:length(ilist)
input = upper(ilist{k});
ix = find(strncmp(CMD, input, length(input)));
result= '*error*';
for k = ix(:)',
if strncmp(input, cmd{k}, length(cmd{k}));
result = CMD{k};
end
end
R = [R,' ',result];
end
|
Subsets and Splits