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/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
| #Raku | Raku | sub auto-abbreviate ( Str $string ) {
return Nil unless my @words = $string.words;
return $_ if @words».substr(0, $_).Set == @words for 1 .. @words».chars.max;
return '∞';
}
# Testing
say ++$, ') ', .&auto-abbreviate, ' ', $_ for './DoWAKA.txt'.IO.lines; |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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
| #BCPL | BCPL | get "libhdr"
let canMakeWord(word) = valof
$( let blocks = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
let avl = vec 40/BYTESPERWORD
for i=0 to 39 do avl%i := blocks%(i+1)
for i=1 to word%0
$( for j=0 to 39
$( let ch = word%i
// make letter uppercase
if 'a' <= ch <= 'z' then ch := ch - 32
if ch = avl%j then
$( // this block is no longer available
avl%j := 0
avl%(j neqv 1) := 0
// but we did find a block
goto next
$)
$)
resultis false // no block found
next: loop
$)
resultis true
$)
let show(word) be
writef("%S: %S*N", word, canMakeWord(word) -> "yes", "no")
let start() be
$( show("A")
show("BARK")
show("book")
show("Treat")
show("CoMmOn")
show("SQUAD")
show("CONFUSE")
$) |
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)
| #Lobster | Lobster |
// Note that the following function is for odd numbers only
// Use "for (unsigned i = 2; i*i <= n; i++)" for even and odd numbers
def sum_proper_divisors_of_odd(n: int) -> int:
var sum = 1
var i = 3
let limit = sqrt(n) + 1
while i < limit:
if n % i == 0:
sum += i
let j = n / i
if i != j:
sum += j
i += 2
return sum
def abundant_odd_numbers():
var n = 1
var c = 0
print "index: number proper_sum"
while c < 25:
let s = sum_proper_divisors_of_odd(n)
if n < s:
c += 1
print concat_string([string(c), ": ", string(n), ", ", string(s)], "")
n += 2
var s = 1
while c < 1000:
s = sum_proper_divisors_of_odd(n)
if n < s:
c += 1
n += 2
print concat_string(["1000: ", string(n), ", ", string(s)], "")
n = 999999999
while n >= s:
n += 2
s = sum_proper_divisors_of_odd(n)
print concat_string(["The first abundant odd number above one billion is: ", string(n), ", ", string(s)], "")
abundant_odd_numbers()
|
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #bash | bash | shopt -s expand_aliases
alias bind_variables='
{
local -ri goal_count=21
local -ri player_human=0
local -ri player_computer=1
local -i turn=1
local -i total_count=0
local -i input_number=0
local -i choose_turn=0
}
'
whose_turn() {
case $(( ( turn + choose_turn ) % 2 )) in
${player_human}) echo "player";;
${player_computer}) echo "computer";;
esac
}
next_turn() {
let turn++
}
validate_number() {
! test ${input_number} -ge 1 -a ${input_number} -le $( max_guess )
}
prompt_number() {
local prompt_str
test $( max_guess ) -eq 1 && {
prompt_str="enter the number 1 to win"
true
} || {
prompt_str="enter a number between 1 and $( max_guess )"
}
while [ ! ]
do
read -p "${prompt_str} (or quit): "
input_number=${REPLY}
case ${REPLY} in
"quit") {
false
return
} ;;
esac
validate_number || break
echo "try again"
done
}
update_count() {
let total_count+=input_number
}
remaining_count() {
echo $(( goal_count - total_count ))
}
max_guess() {
local -i remaining_count
remaining_count=$( remaining_count )
case $( remaining_count ) in
1|2|3) echo ${remaining_count} ;;
*) echo 3 ;;
esac
}
iter() {
update_count
next_turn
}
on_game_over() {
test ! ${input_number} -eq $( remaining_count ) || {
test ! "$( whose_turn )" = "player" && {
echo -ne "\nYou won!\n\n"
true
} || {
echo -ne "\nThe computer won!\nGAME OVER\n\n"
}
false
}
}
on_game_start() {
echo 21 Game
read -p "Press enter key to start"
}
choose_turn() {
let choose_turn=${RANDOM}%2
}
choose_number() {
local -i remaining_count
remaining_count=$( remaining_count )
case ${remaining_count} in
1|2|3) {
input_number=${remaining_count}
} ;;
5|6|7) {
let input_number=remaining_count-4
} ;;
*) {
let input_number=${RANDOM}%$(( $( max_guess ) - 1 ))+1
}
esac
}
game_play() {
choose_turn
while [ ! ]
do
echo "Total now ${total_count} (remaining: $( remaining_count ))"
echo -ne "Turn: ${turn} ("
test ! "$( whose_turn )" = "player" && {
echo -n "Your"
true
} || {
echo -n "Computer"
}
echo " turn)"
test ! "$( whose_turn )" = "player" && {
prompt_number || break
true
} || {
choose_number
sleep 2
echo "Computer chose ${input_number}"
}
on_game_over || break
sleep 1
iter
done
}
21_Game() {
bind_variables
on_game_start
game_play
}
if [ ${#} -eq 0 ]
then
true
else
exit 1
fi
21_Game
|
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Crystal | Crystal | def check(list)
a, b, c, d, e, f, g = list
first = a + b
{b + c + d, d + e + f, f + g}.all? &.==(first)
end
def four_squares(low, high, unique = true, show = unique)
solutions = [] of Array(Int32)
if unique
uniq = "unique"
(low..high).to_a.each_permutation(7, true) { |ary| solutions << ary.clone if check(ary) }
else
uniq = "non-unique"
(low..high).to_a.each_repeated_permutation(7, true) { |ary| solutions << ary.clone if check(ary) }
end
if show
puts " " + ("a".."g").join(" ")
solutions.each { |ary| p ary }
end
puts "#{solutions.size} #{uniq} solutions in #{low} to #{high}"
puts
end
{ {1, 7}, {3, 9} }.each do |(low, high)|
four_squares(low, high)
end
four_squares(0, 9, false) |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #J | J | T=: 0:`1:`(($:&<:+ - $: ])`0:@.(0=]))@.(1+*@-) M. "0 |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Java | Java | import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import static java.lang.Math.min;
public class Test {
static List<BigInteger> cumu(int n) {
List<List<BigInteger>> cache = new ArrayList<>();
cache.add(asList(BigInteger.ONE));
for (int L = cache.size(); L < n + 1; L++) {
List<BigInteger> r = new ArrayList<>();
r.add(BigInteger.ZERO);
for (int x = 1; x < L + 1; x++)
r.add(r.get(r.size() - 1).add(cache.get(L - x).get(min(x, L - x))));
cache.add(r);
}
return cache.get(n);
}
static List<BigInteger> row(int n) {
List<BigInteger> r = cumu(n);
return range(0, n).mapToObj(i -> r.get(i + 1).subtract(r.get(i)))
.collect(toList());
}
public static void main(String[] args) {
System.out.println("Rows:");
for (int x = 1; x < 11; x++)
System.out.printf("%2d: %s%n", x, row(x));
System.out.println("\nSums:");
for (int x : new int[]{23, 123, 1234}) {
List<BigInteger> c = cumu(x);
System.out.printf("%s %s%n", x, c.get(c.size() - 1));
}
}
} |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #APL | APL | ⎕+⎕ |
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.
| #Seed7 | Seed7 |
const type: myInterf is sub object interface;
const func integer: method1 (in myInterf: interf, in float: aFloat) is DYNAMIC;
const func integer: method2 (in myInterf: interf, in string: name) is DYNAMIC;
const func integer: add (in myInterf: interf, in integer: a, in integer: b) is DYNAMIC;
|
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.
| #Sidef | Sidef | class A {
# must be filled in by the class which will inherit it
method abstract() { die 'Unimplemented' };
# can be overridden in the class, but that's not mandatory
method concrete() { say '# 42' };
}
class SomeClass << A {
method abstract() {
say "# made concrete in class"
}
}
var obj = SomeClass.new;
obj.abstract(); # made concrete in class
obj.concrete(); # 42 |
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.
| #Run_BASIC | Run BASIC | print ackermann(1, 2)
function ackermann(m, n)
if (m = 0) then ackermann = (n + 1)
if (m > 0) and (n = 0) then ackermann = ackermann((m - 1), 1)
if (m > 0) and (n > 0) then ackermann = ackermann((m - 1), ackermann(m, (n - 1)))
end function |
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
| #Red | Red |
Red []
;; read and convert data to a string - to char conversion is neccessary to avoid
;; illegal utf8 encoding error....
data: collect/into [foreach b read/binary %abbrev.txt [keep to-char b ]] ""
;; data: read %abbrev.txt - would work, if file was utf-8 encoded ...
foreach line split data newline [ ;; split data in lines at carriage return & line feed:
if empty? trim line [ continue ] ;; continues at head of loop
arr: split line space ;; now split line in words ; accumulate in array / series
min: 1 ;; preset min length
until [
;; head is the first position of series
if head? arr [m: make map! [] ] ;; define an empty map (key -value store)
abbr: copy/part first arr min ;; copy/part ~ leftstr of first word with length min
arr: either m/:abbr [ ;; abbreviation already exists ?
min: min + 1
head arr ;; reset series position to head
][ ;; otherwise ....
m/:abbr: true ;; mark abreviation in map as existent
next arr ;; set series position to next word
]
tail? arr ;; this is the until condition , end /tail of series reached ?
]
print [min line] ;; print automatically reduces all words in block
]
|
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
| #REXX | REXX | /*REXX program finds the minimum length abbreviation for a lists of words (from a file).*/
parse arg uw /*obtain optional arguments from the CL*/
iFID= 'ABBREV_A.TAB' /*name of the file that has the table. */
say 'minimum' /*display the first part of the title. */
say 'abbrev' center("days of the week", 80) /*display the title for the output. */
say '══════' center("", 80, '═') /*display separator for the title line.*/
/* [↓] process the file until done. */
do while lines(iFID)\==0; days=linein(iFID) /*read a line (should contain 7 words).*/
minLen= abb(days) /*find the minimum abbreviation length.*/
say right(minLen, 4) ' ' days /*display a somewhat formatted output. */
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
abb: procedure; parse arg x; #=words(x) /*obtain list of words; find how many.*/
if #==0 then return '' /*check for a blank line or null line. */
@.= /*@. is a stemmed array of the words.*/
L=0 /*L is the max length of " " */
do j=1 for #; @.j=word(x, j) /*assign to array for faster processing*/
L.j=length(@.j); L= max(L, L.j) /*find the maximum length of any item. */
end /*L*/
/* [↓] determine minimum abbrev length*/
do m=1 for L; $= /*for all lengths, find a unique abbrev*/
do k=1 to #; a=left(@.k, m) /*get an abbreviation (with length M).*/
if wordpos(a,$)\==0 then iterate M /*test this abbreviation for uniquness.*/
$=$ a /*so far, it's unique; add to the list.*/
end /*k*/
leave m /*a good abbreviation length was found.*/
end /*m*/
return m |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BQN | BQN | ABC ← {
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
𝕨(×∘≠∘⊢ ◶ ⟨1˙, # if the word is empty, it can be made
Matches(×∘≠∘⊣ ◶ ⟨0˙, # if no matching blocks, it cannot
∨´(𝕨 Others⊣) 𝕊¨ 1<∘↓⊢ # otherwise, remove block and try remaining letters
⟩)⊢
⟩) (⊢-32×1="a{"⍋⊢)𝕩
}
blocks←⟨"BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"⟩
words←⟨"A","bark","BOOK","TrEaT","Common","Squad","Confuse"⟩
> {(<𝕩) ∾ blocks ABC 𝕩}¨ words |
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)
| #Lua | Lua | -- Return the sum of the proper divisors of x
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
-- Return a table of odd abundant numbers
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
-- Write a result to stdout
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
-- Main procedure
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6)) |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #C | C | /**
* Game 21 - an example in C language for Rosseta Code.
*
* A simple game program whose rules are described below
* - see DESCRIPTION string.
*
* This program should be compatible with C89 and up.
*/
/*
* Turn off MS Visual Studio panic warnings which disable to use old gold
* library functions like printf, scanf etc. This definition should be harmless
* for non-MS compilers.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
* Define bool, true and false as needed. The stdbool.h is a standard header
* in C99, therefore for older compilers we need DIY booleans. BTW, there is
* no __STDC__VERSION__ predefined macro in MS Visual C, therefore we need
* check also _MSC_VER.
*/
#if __STDC_VERSION__ >= 199901L || _MSC_VER >= 1800
#include <stdbool.h>
#else
#define bool int
#define true 1
#define false 0
#endif
#define GOAL 21
#define NUMBER_OF_PLAYERS 2
#define MIN_MOVE 1
#define MAX_MOVE 3
#define BUFFER_SIZE 256
#define _(STRING) STRING
/*
* Spaces are meaningful: on some systems they can be visible.
*/
static char DESCRIPTION[] =
"21 Game \n"
" \n"
"21 is a two player game, the game is played by choosing a number \n"
"(1, 2, or 3) to be added to the running total. The game is won by\n"
"the player whose chosen number causes the running total to reach \n"
"exactly 21. The running total starts at zero. \n\n";
static int total;
void update(char* player, int move)
{
printf("%8s: %d = %d + %d\n\n", player, total + move, total, move);
total += move;
if (total == GOAL)
printf(_("The winner is %s.\n\n"), player);
}
int ai()
{
/*
* There is a winning strategy for the first player. The second player can win
* then and only then the frist player does not use the winning strategy.
*
* The winning strategy may be defined as best move for the given running total.
* The running total is a number from 0 to GOAL. Therefore, for given GOAL, best
* moves may be precomputed (and stored in a lookup table). Actually (when legal
* moves are 1 or 2 or 3) the table may be truncated to four first elements.
*/
#if GOAL < 32 && MIN_MOVE == 1 && MAX_MOVE == 3
static const int precomputed[] = { 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1,
3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3 };
update(_("ai"), precomputed[total]);
#elif MIN_MOVE == 1 && MAX_MOVE == 3
static const int precomputed[] = { 1, 1, 3, 2};
update(_("ai"), precomputed[total % (MAX_MOVE + 1)]);
#else
int i;
int move = 1;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if ((total + i - 1) % (MAX_MOVE + 1) == 0)
move = i;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if (total + i == GOAL)
move = i;
update(_("ai"), move);
#endif
}
void human(void)
{
char buffer[BUFFER_SIZE];
int move;
while ( printf(_("enter your move to play (or enter 0 to exit game): ")),
fgets(buffer, BUFFER_SIZE, stdin),
sscanf(buffer, "%d", &move) != 1 ||
(move && (move < MIN_MOVE || move > MAX_MOVE || total+move > GOAL)))
puts(_("\nYour answer is not a valid choice.\n"));
putchar('\n');
if (!move) exit(EXIT_SUCCESS);
update(_("human"), move);
}
int main(int argc, char* argv[])
{
srand(time(NULL));
puts(_(DESCRIPTION));
while (true)
{
puts(_("\n---- NEW GAME ----\n"));
puts(_("\nThe running total is currently zero.\n"));
total = 0;
if (rand() % NUMBER_OF_PLAYERS)
{
puts(_("The first move is AI move.\n"));
ai();
}
else
puts(_("The first move is human move.\n"));
while (total < GOAL)
{
human();
ai();
}
}
} |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #D | D | import std.stdio;
void main() {
fourSquare(1,7,true,true);
fourSquare(3,9,true,true);
fourSquare(0,9,false,false);
}
void fourSquare(int low, int high, bool unique, bool print) {
int count;
if (print) {
writeln("a b c d e f g");
}
for (int a=low; a<=high; ++a) {
for (int b=low; b<=high; ++b) {
if (!valid(unique, a, b)) continue;
int fp = a+b;
for (int c=low; c<=high; ++c) {
if (!valid(unique, c, a, b)) continue;
for (int d=low; d<=high; ++d) {
if (!valid(unique, d, a, b, c)) continue;
if (fp != b+c+d) continue;
for (int e=low; e<=high; ++e) {
if (!valid(unique, e, a, b, c, d)) continue;
for (int f=low; f<=high; ++f) {
if (!valid(unique, f, a, b, c, d, e)) continue;
if (fp != d+e+f) continue;
for (int g=low; g<=high; ++g) {
if (!valid(unique, g, a, b, c, d, e, f)) continue;
if (fp != f+g) continue;
++count;
if (print) {
writeln(a,' ',b,' ',c,' ',d,' ',e,' ',f,' ',g);
}
}
}
}
}
}
}
}
if (unique) {
writeln("There are ", count, " unique solutions in [",low,",",high,"]");
} else {
writeln("There are ", count, " non-unique solutions in [",low,",",high,"]");
}
}
bool valid(bool unique, int needle, int[] haystack ...) {
if (unique) {
foreach (value; haystack) {
if (needle == value) {
return false;
}
}
}
return true;
} |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #11l | 11l | T Error
String message
F (message)
.message = message
T RPNParse
[Float] stk
[Int] digits
F op(f)
I .stk.len < 2
X Error(‘Improperly written expression’)
V b = .stk.pop()
V a = .stk.pop()
.stk.append(f(a, b))
F parse(s)
L(c) s
I c C ‘0’..‘9’
.stk.append(Float(c))
.digits.append(Int(c))
E I c == ‘+’ {.op((a, b) -> a + b)}
E I c == ‘-’ {.op((a, b) -> a - b)}
E I c == ‘*’ {.op((a, b) -> a * b)}
E I c == ‘/’ {.op((a, b) -> a / b)}
E I c != ‘ ’
X Error(‘Wrong char: ’c)
F get_result()
I .stk.len != 1
X Error(‘Improperly written expression’)
R .stk.last
[Int] digits
print(‘Make 24 with the digits:’, end' ‘’)
L 4
V n = random:(1..9)
print(‘ ’n, end' ‘’)
digits.append(n)
print()
V parser = RPNParse()
X.try
parser.parse(input())
V r = parser.get_result()
I sorted(digits) != sorted(parser.digits)
print(‘Error: Not using the given digits’)
E
print(‘Result: ’r)
I r C 23.999<.<24.001
print(‘Good job!’)
E
print(‘Try again.’)
X.catch Error error
print(‘Error: ’error.message) |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #JavaScript | JavaScript |
(function () {
var cache = [
[1]
];
//this was never needed.
/* function PyRange(start, end, step) {
step = step || 1;
if (!end) {
end = start;
start = 0;
}
var arr = [];
for (var i = start; i < end; i += step) arr.push(i);
return arr;
}*/
function cumu(n) {
var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this
r, l, x, Aa, Mi;
// for (ll in ra) { too pythony
for (l=cache.length;l<n+1;l++) {
r = [0];
// l = ra[ll];
// ran = PyRange(1, l + 1);
// for (xx in ran) {
for(x=1;x<l+1;x++){
// x = ran[xx];
r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
}
cache.push(r);
}
return cache[n];
}
function row(n) {
var r = cumu(n),
// rra = PyRange(n),
leArray = [],
i;
// for (ii in rra) {
for (i=0;i<n;i++) {
// i = rra[ii];
leArray.push(r[i + 1] - r[i]);
}
return leArray;
}
console.log("Rows:");
for (iterator = 1; iterator < 12; iterator++) {
console.log(row(iterator));
}
// PL clearly this was not tested:
// console.log("Sums")[23, 123, 1234, 12345].foreach(function (a) {
console.log("Sums");
[23, 123, 1234, 12345].forEach(function (a) {
var s = cumu(a);
console.log(a, s[s.length - 1]);
});
})()
|
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #AppleScript | AppleScript | on run argv
try
return ((first item of argv) as integer) + (second item of argv) as integer
on error
return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
end try
end run |
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.
| #Simula | Simula |
! ABSTRACT HASH KEY TYPE ;
LISTVAL CLASS HASHKEY;
VIRTUAL:
PROCEDURE HASH IS
INTEGER PROCEDURE HASH;;
PROCEDURE EQUALTO IS
BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;;
BEGIN
END HASHKEY;
|
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.
| #Smalltalk | Smalltalk | someClass class >> isAbstract
^ true
someClass class >> new
self isAbstract ifTrue:[
^ self error:'trying to instantiate an abstract class'
].
^ super new
someClass >> method1
^ self subclassResponsibility
|
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.
| #Rust | Rust | fn ack(m: isize, n: isize) -> isize {
if m == 0 {
n + 1
} else if n == 0 {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}
fn main() {
let a = ack(3, 4);
println!("{}", a); // 125
}
|
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
| #Ruby | Ruby | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size: #{abbr.values.max_by(&:size).size}", abbr.inspect, "\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
| #Rust | Rust | /**
* Abbreviations from tintenalarm.de
*/
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
fn main() {
let table = read_days("weekdays.txt").expect("Error in Function read_days:");
for line in table {
if line.len() == 0 {
continue;
};
let mut max_same = 0;
for i in 0..(line.len() - 1) {
for j in i + 1..line.len() {
max_same = max_same.max(begins_with_num_same_chars(&line[i], &line[j]));
}
}
println!("{}\t{:?}", max_same + 1, line);
}
}
fn read_days(filename: &str) -> io::Result<Vec<Vec<String>>> {
let f = File::open(filename)?;
let reader = BufReader::new(f);
let mut table: Vec<Vec<String>> = Vec::new();
for line in reader.lines() {
let mut days: Vec<String> = Vec::with_capacity(7);
for day in line?.split_whitespace() {
days.push(day.to_string());
}
table.push(days);
}
Ok(table)
}
fn begins_with_num_same_chars(str_a: &str, str_b: &str) -> u32 {
let mut num = 0;
for (pos, char_a) in str_a.chars().enumerate() {
match str_b.chars().nth(pos) {
Some(char_b) => {
if char_a == char_b {
num = num + 1;
} else {
return num;
}
}
None => return num,
}
}
num
} |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Bracmat | Bracmat | (
( can-make-word
= ABC blocks
. (B O)
+ (X K)
+ (D Q)
+ (C P)
+ (N A)
+ (G T)
+ (R E)
+ (T G)
+ (Q D)
+ (F S)
+ (J W)
+ (H U)
+ (V I)
+ (A N)
+ (O B)
+ (E R)
+ (F S)
+ (L Y)
+ (P C)
+ (Z M)
: ?blocks
& ( ABC
= letter blocks A Z
. !arg:(.?)
| !arg:(@(?:%?letter ?arg).?blocks)
& !blocks
: ?
+ ?*(? !letter ?:?block)
+ (?&ABC$(!arg.!blocks+-1*!block))
)
& out
$ ( !arg
( ABC$(upp$!arg.!blocks)&yes
| no
)
)
)
& can-make-word'A
& can-make-word'BARK
& can-make-word'BOOK
& can-make-word'TREAT
& can-make-word'COMMON
& can-make-word'SQUAD
& can-make-word'CONFUSE
); |
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)
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(ND)
ENTRY TO ODDSUM.
SUM = 1
SQN = SQRT.(ND)
THROUGH CHECK, FOR CN=3, 2, CN.G.SQN
TM = ND/CN
WHENEVER TM*CN.E.ND
SUM = SUM + CN
WHENEVER TM.NE.CN, SUM = SUM + TM
CHECK END OF CONDITIONAL
FUNCTION RETURN SUM
END OF FUNCTION
SEEN = 0
NUM = 1
THROUGH SHOW, FOR NUM=1, 2, SEEN.G.1000
WHENEVER NUM.L.ODDSUM.(NUM)
SEEN = SEEN + 1
WHENEVER SEEN.LE.25 .OR. SEEN.E.1000,
0 PRINT FORMAT OUTFMT,SEEN,NUM,ODDSUM.(NUM)
SHOW END OF CONDITIONAL
BILION THROUGH BILION, FOR NUM=NUM, 2,
0 NUM.G.1000000000 .AND. NUM.L.ODDSUM.(NUM)
PRINT FORMAT HUGENO,NUM,ODDSUM.(NUM)
VECTOR VALUES OUTFMT =
0 $4HNO. ,I4,S1,3HIS ,I6,S1,7HDIVSUM ,I6*$
VECTOR VALUES HUGENO =
0 $25HFIRST ABOVE 1 BILLION IS ,I10,S1,7HDIVSUM ,I10*$
END OF PROGRAM |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #C.2B.2B | C++ | /**
* Game 21 - an example in C++ language for Rosseta Code.
*
* This version is an example of MVC architecture. It seems be a little cleaner
* than MVP. The friendship has broken encapsulations to avoid getters.
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
#define _(STR) STR
class Model
{
public:
static const int GOAL = 21;
static const int NUMBER_OF_PLAYERS = 2;
static const int MIN_MOVE = 1;
static const int MAX_MOVE = 3;
int bestMove();
bool update(const char* player, int move);
bool isGameBegin();
bool isGameOver();
protected:
friend class View;
View* view = nullptr;
const char* player = nullptr;
int oldTotal = 0;
int newTotal = 0;
int lastMove = 0;
};
class View
{
protected:
Model* model;
public:
View(Model* model);
void init(const char* player);
void update();
};
class Controller
{
protected:
Model* model;
View* view;
public:
Controller(Model* model, View* view);
int input();
void clear();
void run();
};
int Model::bestMove()
{
// This is not the fastest algorithm. There is possible to precompute
// and memorize all answers before game begin or even hard code them.
int move = MIN_MOVE;
for (int i = MIN_MOVE; i <= MAX_MOVE; i++)
if ((newTotal + i - 1) % (MAX_MOVE + 1) == 0)
move = i;
for (int i = MIN_MOVE; i <= MAX_MOVE; i++)
if (newTotal + i == GOAL)
move = i;
return move;
}
bool Model::update(const char* player, int move)
{
if (move >= MIN_MOVE && move <= MAX_MOVE && newTotal + move <= GOAL)
{
this->player = player;
oldTotal = newTotal;
newTotal = oldTotal + move;
lastMove = move;
view->update();
return true;
}
else
return false;
}
bool Model::isGameBegin()
{
return oldTotal == 0;
}
bool Model::isGameOver()
{
return newTotal == GOAL;
}
View::View(Model* model)
{
this->model = model;
model->view = this;
}
void View::init(const char* player)
{
if (model->newTotal == 0)
cout << _("----NEW GAME----\n\n")
<< _("The running total is currently zero.\n")
<< _("The first move is ") << player << _(" move.\n\n");
}
void View::update()
{
cout << setw(8) << model->player << ": " << model->newTotal << " = "
<< model->oldTotal << " + " << model->lastMove << endl << endl;
if (model->isGameOver())
cout << endl << _("The winner is ") << model->player << _(".\n\n\n");
}
Controller::Controller(Model* model, View* view)
{
this->model = model;
this->view = view;
}
void Controller::run()
{
if (rand() % Model::NUMBER_OF_PLAYERS == 0)
{
view->init("AI");
model->update("AI", model->bestMove());
}
else
view->init("human");
while (!model->isGameOver())
{
while (!model->update("human", input()))
clear();
model->update("AI", model->bestMove());
}
}
int Controller::input()
{
int value;
cout << _("enter a valid number to play (or enter 0 to exit game): ");
cin >> value;
cout << endl;
if (!cin.fail())
{
if (value == 0)
exit(EXIT_SUCCESS);
else
return value;
}
else
return model->MIN_MOVE - 1;
}
void Controller::clear()
{
cout << _("Your answer is not a valid choice.") << endl;
cin.clear();
cin.ignore((streamsize)numeric_limits<int>::max, '\n');
}
int main(int argc, char* argv)
{
srand(time(NULL));
cout << _(
"21 Game \n"
" \n"
"21 is a two player game, the game is played by choosing a number \n"
"(1, 2, or 3) to be added to the running total. The game is won by\n"
"the player whose chosen number causes the running total to reach \n"
"exactly 21. The running total starts at zero. \n\n");
while (true)
{
Model* model = new Model();
View* view = new View(model);
Controller* controler = new Controller(model, view);
controler->run();
delete controler;
delete model;
delete view;
}
return EXIT_SUCCESS; // dead code
} |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Delphi | Delphi |
(* A simple function to generate the sequence
Nigel Galloway: January 31st., 2017 *)
type G = {d:int;x:int;b:int;f:int}
let N n g =
{(max (n-g) n) .. (min (g-n) g)} |> Seq.collect(fun d->{(max (d+n+n) (n+n))..(min (g+g) (d+g+g))} |> Seq.collect(fun x ->
seq{for a in n .. g do for b in n .. g do if (a+b) = x then for c in n .. g do if (b+c+d) = x then yield b} |> Seq.collect(fun b ->
seq{for f in n .. g do for G in n .. g do if (f+G) = x then for e in n .. g do if (f+e+d) = x then yield f} |> Seq.map(fun f -> {d=d;x=x;b=b;f=f}))))
|
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #8th | 8th |
\ Generate four random digits and display to the user
\ then get an expression from the user using +, -, / and * and the digits
\ the result must equal 24
\ http://8th-dev.com/24game.html
\ Only the words in namespace 'game' are available to the player:
ns: game
: + n:+ ;
: - n:- ;
: * n:* ;
: / n:/ ;
ns: G
var random-digits
var user-input
: one-digit \ a -- a
rand n:abs 9 n:mod n:1+ a:push ;
: gen-digits \ - a
[] clone nip \ the clone nip is not needed in versions past 1.0.2...
' one-digit 4 times
' n:cmp a:sort
random-digits ! ;
: prompt-user
cr "The digits are: " . random-digits @ . cr ;
: goodbye
cr "Thanks for playing!\n" . cr 0 die ;
: get-input
70 null con:accept dup user-input !
null? if drop goodbye then ;
: compare-digits
true swap
(
\ inputed-array index
dup >r
a:@
random-digits @ r> a:@ nip
n:= not if
break
swap drop false swap
then
) 0 3 loop drop ;
/^\D*(\d)\D+(\d)\D+(\d)\D+(\d)\D*$/ var, digits-regex
: all-digits?
user-input @ digits-regex @ r:match
null? if drop false else
5 = not if
false
else
\ convert the captured digits in the regex into a sorted array:
digits-regex @
( r:@ >n swap ) 1 4 loop drop
4 a:close ' n:cmp a:sort
compare-digits
then
then ;
: does-eval?
0 user-input @ eval 24 n:=
dup not if
cr "Sorry, that expression is wrong" . cr
then ;
: check-input
reset
all-digits? if
does-eval? if
cr "Excellent! Your expression: \"" .
user-input @ .
"\" worked!" . cr
then
else
cr "You did not use the digits properly, try again." . cr
then ;
: intro quote |
Welcome to the '24 game'!
You will be shown four digits each time. Using only the + - * and / operators
and all the digits (and only the digits), produce the number '24'
Enter your result in 8th syntax, e.g.: 4 4 + 2 1 + *
To quit the game, just hit enter by itself. Enjoy!
| . ;
: start
\ don't allow anything but the desired words
ns:game only
intro
repeat
gen-digits
prompt-user
get-input
check-input
again ;
start
|
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Julia | Julia |
using Combinatorics, StatsBase
namesofline(n) = counts([x[1] for x in integer_partitions(n)])
function centerjustpyramid(n)
maxwidth = length(string(namesofline(n)))
for i in 1:n
s = string(namesofline(i))
println(" " ^ div(maxwidth - length(s), 2), s)
end
end
centerjustpyramid(25)
const cachecountpartitions = Dict{BigInt,BigInt}()
function countpartitions(n::BigInt)
if n < 0
0
elseif n < 2
1
elseif (np = get(cachecountpartitions, n, 0)) > 0
np
else
np = 0
sgn = 1
for k = 1:n
np += sgn * (countpartitions(n - (k*(3k-1)) >> 1) + countpartitions(n - (k*(3k+1)) >> 1))
sgn = -sgn
end
cachecountpartitions[n] = np
end
end
G(n) = countpartitions(BigInt(n))
for g in [23, 123, 1234, 12345]
@time println("\nG($g) is $(G(g))")
end
|
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Kotlin | Kotlin | import java.lang.Math.min
import java.math.BigInteger
import java.util.ArrayList
import java.util.Arrays.asList
fun namesOfGod(n: Int): List<BigInteger> {
val cache = ArrayList<List<BigInteger>>()
cache.add(asList(BigInteger.ONE))
(cache.size..n).forEach { l ->
val r = ArrayList<BigInteger>()
r.add(BigInteger.ZERO)
(1..l).forEach { x ->
r.add(r[r.size - 1] + cache[l - x][min(x, l - x)])
}
cache.add(r)
}
return cache[n]
}
fun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } }
fun main(args: Array<String>) {
println("Rows:")
(1..25).forEach {
System.out.printf("%2d: %s%n", it, row(it))
}
println("\nSums:")
intArrayOf(23, 123, 1234, 1234).forEach {
val c = namesOfGod(it)
System.out.printf("%s %s%n", it, c[c.size - 1])
}
} |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #Arc | Arc |
(prn (+ (read)
(read)))
|
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.
| #Standard_ML | Standard ML | signature QUEUE = sig
type 'a queue
val empty : 'a queue
val enqueue : 'a -> 'a queue -> 'a queue
val dequeue : 'a queue -> ('a * 'a queue) option
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.
| #Tcl | Tcl | oo::class create AbstractQueue {
method enqueue item {
error "not implemented"
}
method dequeue {} {
error "not implemented"
}
self unexport create new
} |
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.
| #Sather | Sather | class MAIN is
ackermann(m, n:INT):INT
pre m >= 0 and n >= 0
is
if m = 0 then return n + 1; end;
if n = 0 then return ackermann(m-1, 1); end;
return ackermann(m-1, ackermann(m, n-1));
end;
main is
n, m :INT;
loop n := 0.upto!(6);
loop m := 0.upto!(3);
#OUT + "A(" + m + ", " + n + ") = " + ackermann(m, n) + "\n";
end;
end;
end;
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
| #Scala | Scala | name := "Abbreviations-automatic"
scalaVersion := "2.13.0"
version := "0.1"
homepage := Some(url("http://rosettacode.org/wiki/Abbreviations,_automatic#Scala"))
libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.3.0" |
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
| #SenseTalk | SenseTalk | function AbbreviationsAutomatic days
put 1 into abbreviationLength
put the number of items in days into len
repeat forever
put () into abbreviations
repeat with each item day in days
put the first abbreviationLength characters of day into abbreviation
if abbreviations contains abbreviation
exit repeat
end if
insert abbreviation after abbreviations
if the number of items in abbreviations is len
return abbreviationLength
end if
end repeat
add 1 to abbreviationLength
end repeat
end AbbreviationsAutomatic |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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 <stdio.h>
#include <ctype.h>
int can_make_words(char **b, char *word)
{
int i, ret = 0, c = toupper(*word);
#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }
if (!c) return 1;
if (!b[0]) return 0;
for (i = 0; b[i] && !ret; i++) {
if (b[i][0] != c && b[i][1] != c) continue;
SWAP(b[i], b[0]);
ret = can_make_words(b + 1, word + 1);
SWAP(b[i], b[0]);
}
return ret;
}
int main(void)
{
char* blocks[] = {
"BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM",
0 };
char *words[] = {
"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse", 0
};
char **w;
for (w = words; *w; w++)
printf("%s\t%d\n", *w, can_make_words(blocks, *w));
return 0;
} |
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)
| #Maple | Maple |
with(NumberTheory):
# divisorSum returns the sum of the divisors of x not including x
divisorSum := proc(x::integer)
return SumOfDivisors(x) - x;
end proc:
# abundantNumber returns true if x is an abundant number and false otherwise
abundantNumber := proc(x::integer)
if (SumOfDivisors(x) > 2*x) then return true
else return false end if;
end proc:
count := 0:
number := 1:
cat("First 25 abundant odd numbers");
while count < 25 do
if (abundantNumber(number)) then
count += 1:
print(cat(count, ": ", number, " sum of divisors ", SumOfDivisors(number), " sum of proper divisors ", divisorSum(number)));
else end if;
number += 2:
end:
while (count < 1000) do
if (abundantNumber(number)) then
count += 1:
else end if:
number += 2:
end:
cat("The 1000th odd abundant number is ", number - 2, ", its sum of divisors is ", SumOfDivisors(number - 2), ", and its sum of proper divisors is ", divisorSum(number - 2));
for number from 10^9 + 1 by 2 to infinity while not abundantNumber(number) do end:
cat("First abundant odd number > 10^9 is ", number, ", its sum of divisors is ", SumOfDivisors(number), ", and its sum of proper divisors is ",divisorSum(number));
|
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #C.23 | C# | // 21 Game
using System;
namespace _21Game
{
public class Program
{
private const string computerPlayer = "Computer";
private const string humanPlayer = "Player 1";
public static string SwapPlayer(string currentPlayer)
{
if (currentPlayer == computerPlayer)
{
currentPlayer = humanPlayer;
}
else
{
currentPlayer = computerPlayer;
}
return currentPlayer;
}
public static void PlayGame()
{
bool playAnother = true;
int total = 0;
int final = 21;
int roundChoice = 0;
string currentPlayer = RandomPLayerSelect();
int compWins = 0;
int humanWins = 0;
while (playAnother)
{
Console.WriteLine($"Now playing: {currentPlayer}");
try
{
if (currentPlayer == computerPlayer)
{
roundChoice = CompMove(total);
}
else
{
roundChoice = int.Parse(Console.ReadLine());
}
if (roundChoice != 1 && roundChoice != 2 && roundChoice != 3)
{
throw new Exception();
}
total += roundChoice;
}
catch (Exception)
{
Console.WriteLine("Invalid choice! Choose from numbers: 1, 2, 3.");
continue;
}
Console.WriteLine(total);
if (total == final)
{
if (currentPlayer == computerPlayer)
{
compWins++;
}
if (currentPlayer == humanPlayer)
{
humanWins++;
}
Console.WriteLine($"Winner: {currentPlayer}");
Console.WriteLine($"Comp wins: {compWins}. Human wins: {humanWins}");
Console.WriteLine($"do you wan to play another round? y/n");
var choice = Console.ReadLine();
if (choice == "y")
{
total = 0;
}
else if (choice == "n")
{
break;
}
else
{
Console.WriteLine("Invalid choice! Choose from y or n");
continue;
}
}
else if (total > 21)
{
Console.WriteLine("Not the right time to play this game :)");
break;
}
currentPlayer = SwapPlayer(currentPlayer);
}
}
public static bool CheckIfCanWin(int total)
{
bool result = false;
if (total == 18)
{
result = true;
}
return result;
}
public static int CompMove(int total)
{
int choice = 0;
if (CheckIfCanWin(total))
{
choice = 21 - total;
}
else
{
choice = new Random().Next(1,4);
}
return choice;
}
public static string RandomPLayerSelect()
{
string[] players = new string[] { computerPlayer, humanPlayer };
var random = new Random().Next(0,2);
return players[random];
}
public static void Main(string[] args)
{
// welcome message and rules
Console.WriteLine("Welcome to 21 game \n");
Console.WriteLine(@"21 is a two player game.
The game is played by choosing a number.
1, 2, or 3 to be added a total sum. \n
The game is won by the player reaches exactly 21. \n" );
Console.WriteLine("Choose your number: (1, 2 or 3)");
PlayGame();
}
}
}
|
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #F.23 | F# |
(* A simple function to generate the sequence
Nigel Galloway: January 31st., 2017 *)
type G = {d:int;x:int;b:int;f:int}
let N n g =
{(max (n-g) n) .. (min (g-n) g)} |> Seq.collect(fun d->{(max (d+n+n) (n+n))..(min (g+g) (d+g+g))} |> Seq.collect(fun x ->
seq{for a in n .. g do for b in n .. g do if (a+b) = x then for c in n .. g do if (b+c+d) = x then yield b} |> Seq.collect(fun b ->
seq{for f in n .. g do for G in n .. g do if (f+G) = x then for e in n .. g do if (f+e+d) = x then yield f} |> Seq.map(fun f -> {d=d;x=x;b=b;f=f}))))
|
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game24_64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBDIGITS, 4 // digits number
.equ TOTAL, 24
.equ BUFFERSIZE, 100
.equ STACKSIZE, 10 // operator and digits number items in stacks
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRules: .ascii "24 Game 64 bits.\n"
.ascii "The program will display four randomly-generated \n"
.ascii "single-digit numbers and will then prompt you to enter\n"
.ascii "an arithmetic expression followed by <enter> to sum \n"
.ascii "the given numbers to 24.\n"
.asciz "Exemple : 9+8+3+4 or (7+5)+(3*4) \n\n"
szMessExpr: .asciz "Enter your expression (or type (q)uit to exit or (n) for other digits): \n"
szMessDigits: .asciz "The four digits are @ @ @ @ and the score is 24. \n"
szMessNoDigit: .asciz "Error : One digit is not in digits list !! \n"
szMessSameDigit: .asciz "Error : Two digits are same !! \n"
szMessOK: .asciz "It is OK. \n"
szMessNotOK: .asciz "Error, it is not ok total = @ \n"
szMessErrOper: .asciz "Unknow Operator (+,-,$,/,(,)) \n"
szMessNoparen: .asciz "no opening parenthesis !! \n"
szMessErrParen: .asciz "Error parenthesis number !! \n"
szMessNoalldigits: .asciz "One or more digits not used !!\n"
szMessNewGame: .asciz "New game (y/n) ? \n"
szCarriageReturn: .asciz "\n"
.align 4
qGraine: .quad 123456
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
sBuffer: .skip BUFFERSIZE
iTabDigit: .skip 8 * NBDIGITS
iTabTopDigit: .skip 8 * NBDIGITS
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRules // display rules
bl affichageMess
1:
mov x3,#0
ldr x12,qAdriTabDigit
ldr x11,qAdriTabTopDigit
ldr x5,qAdrszMessDigits
2: // loop generate random digits
mov x0,#8
bl genereraleas
add x0,x0,#1
str x0,[x12,x3,lsl #3] // store in table
mov x1,#0
str x1,[x11,x3,lsl #3] // raz top table
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
//mov x2,#0
//strb w2,[x1,x0] // reduce size display area with zéro final
mov x0,x5
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x5,x0
add x3,x3,#1
cmp x3,#NBDIGITS // end ?
blt 2b // no -> loop
mov x0,x5
bl affichageMess
3: // loop human entry
ldr x0,qAdrszMessExpr
bl affichageMess
bl saisie // entry
cmp x0,#'q'
beq 100f
cmp x0,#'Q'
beq 100f
cmp x0,#'n'
beq 1b
cmp x0,#'N'
beq 1b
bl evalExpr // expression evaluation
cmp x0,#0 // ok ?
bne 3b // no - > loop
10: // display new game ?
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrszMessNewGame
bl affichageMess
bl saisie
cmp x0,#'y'
beq 1b
cmp x0,#'Y'
beq 1b
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
qAdrszMessRules: .quad szMessRules
qAdrszMessDigits: .quad szMessDigits
qAdrszMessExpr: .quad szMessExpr
qAdrszMessNewGame: .quad szMessNewGame
qAdrsZoneConv: .quad sZoneConv
qAdriTabDigit: .quad iTabDigit
qAdriTabTopDigit: .quad iTabTopDigit
/******************************************************************/
/* evaluation expression */
/******************************************************************/
/* x0 return 0 if ok -1 else */
evalExpr:
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,fp,[sp,-16]! // save registres
mov x0,#0
ldr x1,qAdriTabTopDigit
mov x2,#0
1: // loop init table top digits
str x0,[x1,x2,lsl #3]
add x2,x2,#1
cmp x2,#NBDIGITS
blt 1b
sub sp,sp,#STACKSIZE * 8 // stack operator
mov fp,sp
sub sp,sp,#STACKSIZE * 8 // stack digit
mov x1,sp
ldr x10,qAdrsBuffer
mov x8,#0 // indice character in buffer
mov x7,#0 // indice digits stack
mov x2,#0 // indice operator stack
mov x9,0
1: // begin loop
ldrb w9,[x10,x8]
cmp x9,#0xA // end expression ?
beq 90f
cmp x9,#' ' // space ?
cinc x8,x8,eq // loop
beq 1b
cmp x9,#'(' // left parenthesis -> store in operator stack
bne 11f
str x9,[fp,x2,lsl 3]
add x2,x2,#1
add x8,x8,#1 // and loop
b 1b
11:
cmp x9,#')' // right parenthesis ?
bne 3f
mov x0,fp // compute operator stack until left parenthesis
sub x2,x2,#1
2:
ldr x6,[fp,x2,lsl 3]
cmp x6,#'(' // left parenthesis
cinc x8,x8,eq // end ?
beq 1b // and loop
sub x7,x7,#1 // last digit
mov x3,x7
bl compute
sub x2,x2,#1
cmp x2,#0
bge 2b
ldr x0,qAdrszMessNoparen // no left parenthesis in stack
bl affichageMess
mov x0,#-1
b 100f
3:
cmp x9,#'+' // addition
beq 4f
cmp x9,#'-' // soustraction
beq 4f
cmp x9,#'*' // multiplication
beq 4f
cmp x9,#'/' // division
beq 4f
b 5f // not operator
4: // control priority and depile stacks
mov x0,fp
mov x3,x7
mov x4,x9
bl depileOper
mov x7,x3
add x8,x8,#1
b 1b // and loop
5: // digit
sub x9,x9,#0x30
mov x0,x9
bl digitControl
cmp x0,#0 // error ?
bne 100f
str x9,[x1,x7,lsl #3] // store digit in digits stack
add x7,x7,#1
add x8,x8,#1
beq 1b
b 100f
90: // compute all stack operators
mov x0,fp
sub x7,x7,#1
91:
subs x2,x2,#1
blt 92f
mov x3,x7
bl compute
sub x7,x7,#1
b 91b
92:
ldr x0,[x1] // total = first value on digits stack
cmp x0,#TOTAL // control total
beq 93f // ok
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
mov x2,#0
strb w2,[x1,x0]
ldr x0,qAdrszMessNotOK
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess
mov x0,#-1
b 100f
93: // control use all digits
ldr x1,qAdriTabTopDigit
mov x2,#0
94: // begin loop
ldr x0,[x1,x2,lsl #3] // load top
cmp x0,#0
bne 95f
ldr x0,qAdrszMessNoalldigits
bl affichageMess
mov x0,#-1
b 100f
95:
add x2,x2,#1
cmp x2,#NBDIGITS
blt 94b
96: // display message OK
ldr x0,qAdrszMessOK
bl affichageMess
mov x0,#0
b 100f
100:
add sp,sp,8 * (STACKSIZE *2) // stack algnement
ldp x10,fp,[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
qAdrszMessNoparen: .quad szMessNoparen
qAdrszMessNotOK: .quad szMessNotOK
qAdrszMessOK: .quad szMessOK
qAdrszMessNoalldigits: .quad szMessNoalldigits
/******************************************************************/
/* depile operator */
/******************************************************************/
/* x0 operator stack address */
/* x1 digits stack address */
/* x2 operator indice */
/* x3 digits indice */
/* x4 operator */
/* x2 return a new operator indice */
/* x3 return a new digits indice */
depileOper:
stp x4,lr,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
cmp x2,#0 // first operator ?
beq 60f
sub x5,x2,#1
1:
ldr x6,[x0,x5,lsl #3] // load stack operator
cmp x6,x4 // same operators
beq 50f
cmp x6,#'*' // multiplication
beq 50f
cmp x6,#'/' // division
beq 50f
cmp x6,#'-' // soustraction
beq 50f
b 60f
50: // depile operators stack and compute
sub x2,x2,#1
sub x3,x3,#1
bl compute
sub x5,x5,#1
cmp x5,#0
bge 1b
60:
str x4,[x0,x2,lsl #3] // add operator in stack
add x2,x2,#1
100:
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x4,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* compute */
/******************************************************************/
/* x0 operator stack address */
/* x1 digits stack address */
/* x2 operator indice */
/* x3 digits indice */
compute:
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
ldr x6,[x1,x3,lsl 3] // load second digit
sub x5,x3,#1
ldr x7,[x1,x5,lsl 3] // load first digit
ldr x8,[x0,x2,lsl 3] // load operator
cmp x8,#'+'
bne 1f
add x7,x7,x6 // addition
str x7,[x1,x5,lsl 3]
b 100f
1:
cmp x8,#'-'
bne 2f
sub x7,x7,x6 // soustaction
str x7,[x1,x5,lsl 3]
b 100f
2:
cmp x8,#'*'
bne 3f // multiplication
mul x7,x6,x7
str x7,[x1,x5,lsl 3]
b 100f
3:
cmp x8,#'/'
bne 4f
udiv x7,x7,x6 // division
str x7,[x1,x5,lsl 3]
b 100f
4:
cmp x8,#'(' // left parenthesis ?
bne 5f
ldr x0,qAdrszMessErrParen // error
bl affichageMess
mov x0,#-1
b 100f
5:
ldr x0,qAdrszMessErrOper
bl affichageMess
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 x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessErrOper: .quad szMessErrOper
qAdrszMessErrParen: .quad szMessErrParen
/******************************************************************/
/* control digits */
/******************************************************************/
/* x0 return 0 if OK 1 if not digit */
digitControl:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
ldr x1,qAdriTabTopDigit
ldr x2,qAdriTabDigit
mov x3,#0
1:
ldr x4,[x2,x3,lsl #3] // load digit
cmp x0,x4 // equal ?
beq 2f // yes
add x3,x3,#1 // no -> loop
cmp x3,#NBDIGITS // end ?
blt 1b
ldr x0,qAdrszMessNoDigit // error
bl affichageMess
mov x0,#1
b 100f
2: // control prev use
ldr x4,[x1,x3,lsl #3]
cmp x4,#0
beq 3f
add x3,x3,#1
cmp x3,#NBDIGITS
blt 1b
ldr x0,qAdrszMessSameDigit
bl affichageMess
mov x0,#1
b 100f
3:
mov x4,#1
str x4,[x1,x3,lsl #3]
mov x0,#0
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
qAdrszMessNoDigit: .quad szMessNoDigit
qAdrszMessSameDigit: .quad szMessSameDigit
/******************************************************************/
/* string entry */
/******************************************************************/
/* x0 return the first character of human entry */
saisie:
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 x0,STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,BUFFERSIZE // buffer size
mov x8,READ // request to read datas
svc 0 // call system
ldr x1,qAdrsBuffer // buffer address
ldrb w0,[x1] // load first character
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
qAdrsBuffer: .quad sBuffer
/***************************************************/
/* Generation random number */
/***************************************************/
/* x0 contains limit */
genereraleas:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
ldr x4,qAdrqGraine
ldr x2,[x4]
ldr x3,qNbDep1
mul x2,x3,x2
ldr x3,qNbDep2
add x2,x2,x3
str x2,[x4] // maj de la graine pour l appel suivant
cmp x0,#0
beq 100f
add x0,x0,#1
udiv x3,x2,x0
msub x0,x3,x0,x2 // résult = remainder
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
/*****************************************************/
qAdrqGraine: .quad qGraine
qNbDep1: .quad 0x0019660d
qNbDep2: .quad 0x3c6ef35f
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Lasso | Lasso | define cumu(n::integer) => {
loop(-from=$cache->size,-to=#n+1) => {
local(r = array(0), l = loop_count)
loop(loop_count) => {
protect => { #r->insert(#r->last + $cache->get(#l - loop_count)->get(math_min(loop_count+1, #l - loop_count))) }
}
#r->size > 1 ? $cache->insert(#r)
}
return $cache->get(#n)
}
define row(n::integer) => {
// cache gets reset & rebuilt for each row, slower but more accurate
var(cache = array(array(1)))
local(r = cumu(#n+1))
local(o = array)
loop(#n) => {
protect => { #o->insert(#r->get(loop_count+1) - #r->get(loop_count)) }
}
return #o
}
'rows:\r'
loop(25) => {^
loop_count + ': '+ row(loop_count)->join(' ') + '\r'
^}
'sums:\r'
with x in array(23, 123, 1234) do => {^
var(cache = array(array(1)))
cumu(#x+1)->last
'\r'
^} |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Lua | Lua | function nog(n)
local tri = {{1}}
for r = 2, n do
tri[r] = {}
for c = 1, r do
tri[r][c] = (tri[r-1][c-1] or 0) + (tri[r-c] and tri[r-c][c] or 0)
end
end
return tri
end
function G(n)
local tri, sum = nog(n), 0
for _, v in ipairs(tri[n]) do sum = sum + v end
return sum
end
tri = nog(25)
for i, row in ipairs(tri) do
print(i .. ": " .. table.concat(row, " "))
end
print("G(23) = " .. G(23))
print("G(123) = " .. G(123)) |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #Argile | Argile | (: Standard input-output streams :)
use std, array
Cfunc scanf "%d%d" (&val int a) (&val int b)
printf "%d\n" (a + b) |
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.
| #Vala | Vala | public abstract class Animal : Object {
public void eat() {
print("Chomp! Chomp!\n");
}
public abstract void talk();
}
public class Mouse : Animal {
public override void talk() {
print("Squeak! Squeak!\n");
}
}
public class Dog : Animal {
public override void talk() {
print("Woof! Woof!\n");
}
}
void main() {
Dog mike = new Dog();
Mouse scott = new Mouse();
mike.talk();
mike.eat();
scott.talk();
scott.eat();
} |
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.
| #VBA | VBA | MustInherit Class Base
Protected Sub New()
End Sub
Public Sub StandardMethod()
'code
End Sub
Public Overridable Sub Method_Can_Be_Replaced()
'code
End Sub
Public MustOverride Sub Method_Must_Be_Replaced()
End Class |
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.
| #Scala | Scala | def ack(m: BigInt, n: BigInt): BigInt = {
if (m==0) n+1
else if (n==0) ack(m-1, 1)
else ack(m-1, ack(m, 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
| #Tcl | Tcl |
set f [open abbreviations_automatic_weekdays.txt]
set lines [split [read -nonewline $f] \n]
close $f
foreach days $lines {
if {[string length $days] == 0} continue
if {[llength $days] != 7} {
throw ERROR {not 7 days in a line}
}
if {[llength [lsort -unique $days]] != 7} {
throw ERROR {not all 7 days in a line are distinct}
}
for {set i 0} {1} {incr i} {
if {[llength [lsort -unique [lmap x $days {string range $x 0 $i}]]] == 7} break
}
incr i
puts "$i $days"
} |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# | using System;
using System.IO;
// Needed for the method.
using System.Text.RegularExpressions;
using System.Collections.Generic;
void Main()
{
string blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
List<string> words = new List<string>() {
"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"
};
foreach(var word in words)
{
Console.WriteLine("{0}: {1}", word, CheckWord(blocks, word));
}
}
bool CheckWord(string blocks, string word)
{
for(int i = 0; i < word.Length; ++i)
{
int length = blocks.Length;
Regex rgx = new Regex("([a-z]"+word[i]+"|"+word[i]+"[a-z])", RegexOptions.IgnoreCase);
blocks = rgx.Replace(blocks, "", 1);
if(blocks.Length == length) return false;
}
return true;
}
|
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Commodore_BASIC | Commodore BASIC | 1 rem 21 game
2 rem for rosetta code
3 rem initialization
4 l$=chr$(157):rem left cursor
5 dim p$(2),hc(2),ca(4):hc(1)=0:hc(2)=0:rem players
6 ca(0)=1:ca(1)=1:ca(2)=3:ca(3)=2:rem computer answers
7 dim cn$(6):for i=1 to 6:read cn$(i):next:rem computer names
8 def fn m(x)=(x-(int(x/4))*4):rem modulo function
10 rem optionally set screen colors here
20 print chr$(147);chr$(14):print spc(16);"21 GAME"
25 print:print " The goal of this game is to take turns"
26 print " adding the value of either 1, 2, or 3"
27 print " to a running total. The first player"
28 print " to bring the total to 21..."
29 print:print spc(10);"... WINS THE GAME!"
30 print:gosub 1000
35 print chr$(147):for p=1 to 2
40 rem game setup and get players
42 for p=1 to 2
44 print:print "Player";p;l$;", [H]uman or [C]omputer? ";
45 get k$:if k$<>"c" and k$<>"h" then 45
46 print k$:hc(p)=(k$="c")
50 print:print"Player";p;l$",":print"Enter your name";:if hc(p)then goto54
52 input p$(p):next p:goto 60
54 gosub 1500:print "? ";p$(p):next p
60 print:for p=1 to 2:print p;l$;". ";p$(p):next
65 print:print "Is this correct (y/n)? ";
70 get k$:if k$<>"y" and k$<>"n" then 70
75 print k$:if k$="n" then goto 35
80 print:print "Who will play first (1 or 2)? ";
85 get k$:if k$<"1" or k$>"2" then 85
90 fp=asc(k$)-48:print k$:print
95 print "Okay, ";p$(fp);" will play first.":print:gosub 1000
100 rem start main game loop
105 pi=fp:rt=0
110 print chr$(147);"Total so far:";rt
115 print:print p$(pi);"'s turn."
120 if hc(pi) then gosub 1200
125 if not hc(pi) then gosub 1100
130 rt=rt+ad
135 if rt=21 then goto 200
140 if rt>21 then print:print p$(pi);" loses by going over 21!!":goto 210
145 pi=pi+1:if pi>2 then pi=1
150 goto 110
200 rem winner winner chicken dinner
205 print:print "21! ";p$(pi);" wins the game!!!"
210 print:print "Would you like to play again? ";
215 get k$:if k$<>"n" and k$<>"y" then 215
220 print k$
225 if k$="n" then print:print "Okay, maybe another time. Bye!":end
230 goto 10
1000 rem pause for keypress
1010 z$=" Press a key to continue. "
1015 print spc(20-int(len(z$)/2));
1016 print chr$(18);z$;chr$(146)
1020 get k$:if k$="" then 1020
1025 return
1100 rem human player move
1105 print:print "How much to add,"
1110 print "1, 2, or 3 (0 to quit)";:input ad
1115 if ad<0 or ad>3 then print:print"Illegal amount. Try again.":goto1105
1120 if ad=0 then print:print "Game was ended by ";p$(pi);".":end
1125 return
1200 rem computer player move
1205 print:print "Thinking...";
1210 tt=int(rnd(1)*10)
1215 for t=1 to tt:print ".";:for i=1 to 250:next i,t:print
1220 rm=fn m(rt)
1225 ad=ca(rm)
1230 print:print p$(pi);" adds";ca(rm);l$;"."
1235 for t=1 to 1000:next t
1240 return
1500 rem pick a computer name
1505 pn=int(rnd(1)*6)+1:t$=cn$(pn)
1510 if t$=p$(p-1) then goto 1505
1515 p$(p)=t$
1520 return
2000 rem some computer names to pick from
2010 data "Commodore 64","VIC-20","Commodore 128","PET"
2020 data "Plus/4","Commodore 16" |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #11l | 11l | [Char = ((Float, Float) -> Float)] op
op[Char(‘+’)] = (x, y) -> x + y
op[Char(‘-’)] = (x, y) -> x - y
op[Char(‘*’)] = (x, y) -> x * y
op[Char(‘/’)] = (x, y) -> I y != 0 {x / y} E 9999999
F almost_equal(a, b)
R abs(a - b) <= 1e-5
F solve(nums)
V syms = ‘+-*/’
V sorted_nums = sorted(nums).map(Float)
L(x, y, z) cart_product(syms, syms, syms)
V n = copy(sorted_nums)
L
V (a, b, c, d) = (n[0], n[1], n[2], n[3])
I almost_equal(:op[x](:op[y](a, b), :op[z](c, d)), 24.0)
R ‘(’a‘ ’y‘ ’b‘) ’x‘ (’c‘ ’z‘ ’d‘)’
I almost_equal(:op[x](a, :op[y](b, :op[z](c, d))), 24.0)
R a‘ ’x‘ (’b‘ ’y‘ (’c‘ ’z‘ ’d‘))’
I almost_equal(:op[x](:op[y](:op[z](c, d), b), a), 24.0)
R ‘((’c‘ ’z‘ ’d‘) ’y‘ ’b‘) ’x‘ ’a
I almost_equal(:op[x](:op[y](b, :op[z](c, d)), a), 24.0)
R ‘(’b‘ ’y‘ (’c‘ ’z‘ ’d‘)) ’x‘’a
I !n.next_permutation()
L.break
R ‘not found’
L(nums) [[9, 4, 4, 5],
[1, 7, 2, 7],
[5, 7, 5, 4],
[1, 4, 6, 6],
[2, 3, 7, 3],
[8, 7, 9, 7],
[1, 6, 2, 6],
[7, 9, 4, 1],
[6, 4, 2, 2],
[5, 7, 9, 7],
[3, 3, 8, 8]]
print(‘solve(’nums‘) -> ’solve(nums)) |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Factor | Factor | USING: arrays backtrack formatting grouping kernel locals math
math.ranges prettyprint sequences sequences.generalizations
sets ;
IN: rosetta-code.4-rings
:: 4-rings ( lo hi unique? -- seq ) [
7 [ lo hi [a,b] amb-lazy ] replicate
7 firstn :> ( a b c d e f g )
{ a b c d e f g } :> p
a b +
b c d + +
d e f + +
f g +
4array all-equal?
unique? [ p all-unique? and ] when
must-be-true p
] bag-of ;
: report ( lo hi unique? -- )
3dup 4-rings over [ dup . ] when length swap "" "non-" ?
"In [%d, %d] there are %d %sunique solutions.\n" printf ;
1 7 t report
3 9 t report
0 9 f report |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #ABAP | ABAP | with Ada.Float_Text_IO;
with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Game_24 is
subtype Digit is Character range '1' .. '9';
package Random_Digit is new Ada.Numerics.Discrete_Random (Digit);
Exp_Error : exception;
Digit_Generator : Random_Digit.Generator;
Given_Digits : array (1 .. 4) of Digit;
Float_Value : constant array (Digit) of Float :=
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
function Apply_Op (L, R : Float; Op : Character) return Float is
begin
case Op is
when '+' =>
return L + R;
when '-' =>
return L - R;
when '*' =>
return L * R;
when '/' =>
return L / R;
when others =>
Ada.Text_IO.Put_Line ("Unexpected operator: " & Op);
raise Exp_Error;
end case;
end Apply_Op;
function Eval_Exp (E : String) return Float is
Flt : Float;
First : Positive := E'First;
Last : Positive;
function Match_Paren (Start : Positive) return Positive is
Pos : Positive := Start + 1;
Level : Natural := 1;
begin
loop
if Pos > E'Last then
Ada.Text_IO.Put_Line ("Unclosed parentheses.");
raise Exp_Error;
elsif E (Pos) = '(' then
Level := Level + 1;
elsif E (Pos) = ')' then
Level := Level - 1;
exit when Level = 0;
end if;
Pos := Pos + 1;
end loop;
return Pos;
end Match_Paren;
begin
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Eval_Exp (E (First + 1 .. Last - 1));
elsif E (First) in Digit then
Last := First;
Flt := Float_Value (E (First));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
loop
if Last = E'Last then
return Flt;
elsif Last = E'Last - 1 then
Ada.Text_IO.Put_Line ("Unexpected end of expression.");
raise Exp_Error;
end if;
First := Last + 2;
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Apply_Op (Flt, Eval_Exp (E (First + 1 .. Last - 1)),
Op => E (First - 1));
elsif E (First) in Digit then
Last := First;
Flt := Apply_Op (Flt, Float_Value (E (First)),
Op => E (First - 1));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
end loop;
end Eval_Exp;
begin
Ada.Text_IO.Put_Line ("24 Game");
Ada.Text_IO.Put_Line ("- Enter Q to Quit");
Ada.Text_IO.Put_Line ("- Enter N for New digits");
Ada.Text_IO.Put_Line ("Note: Operators are evaluated left-to-right");
Ada.Text_IO.Put_Line (" (use parentheses to override)");
Random_Digit.Reset (Digit_Generator);
<<GEN_DIGITS>>
Ada.Text_IO.Put_Line ("Generating 4 digits...");
for I in Given_Digits'Range loop
Given_Digits (I) := Random_Digit.Random (Digit_Generator);
end loop;
<<GET_EXP>>
Ada.Text_IO.Put ("Your Digits:");
for I in Given_Digits'Range loop
Ada.Text_IO.Put (" " & Given_Digits (I));
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Enter your Expression: ");
declare
Value : Float;
Response : constant String := Ada.Text_IO.Get_Line;
Prev_Ch : Character := ' ';
Unused_Digits : array (Given_Digits'Range) of Boolean :=
(others => True);
begin
if Response = "n" or Response = "N" then
goto GEN_DIGITS;
end if;
if Response = "q" or Response = "Q" then
return;
end if;
-- check input
for I in Response'Range loop
declare
Ch : constant Character := Response (I);
Found : Boolean;
begin
if Ch in Digit then
if Prev_Ch in Digit then
Ada.Text_IO.Put_Line ("Illegal multi-digit number used.");
goto GET_EXP;
end if;
Found := False;
for J in Given_Digits'Range loop
if Unused_Digits (J) and then
Given_Digits (J) = Ch then
Unused_Digits (J) := False;
Found := True;
exit;
end if;
end loop;
if not Found then
Ada.Text_IO.Put_Line ("Illegal number used: " & Ch);
goto GET_EXP;
end if;
elsif Ch /= '(' and Ch /= ')' and Ch /= '+' and
Ch /= '-' and Ch /= '*' and Ch /= '/' then
Ada.Text_IO.Put_Line ("Illegal character used: " & Ch);
goto GET_EXP;
end if;
Prev_Ch := Ch;
end;
end loop;
-- check all digits used
for I in Given_Digits'Range loop
if Unused_Digits (I) then
Ada.Text_IO.Put_Line ("Digit not used: " & Given_Digits (I));
goto GET_EXP;
end if;
end loop;
-- check value
begin
Value := Eval_Exp (Response);
exception
when Exp_Error =>
goto GET_EXP; -- Message displayed by Eval_Exp;
end;
if abs (Value - 24.0) > 0.001 then
Ada.Text_IO.Put ("Value ");
Ada.Float_Text_IO.Put (Value, Fore => 0, Aft => 3, Exp => 0);
Ada.Text_IO.Put_Line (" is not 24!");
goto GET_EXP;
else
Ada.Text_IO.Put_Line ("You won!");
Ada.Text_IO.Put_Line ("Enter N for a new game, or try another solution.");
goto GET_EXP;
end if;
end;
end Game_24; |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Maple | Maple | TriangleLine(n) := map(rhs, Statistics :- Tally(map(x -> x[-1], combinat:-partition(n)))):
Triangle := proc(m)
local i;
for i from 1 to m do
print(op(TriangleLine(i)));
end do
end proc:
|
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Table[Last /@ Reverse@Tally[First /@ IntegerPartitions[n]], {n, 10}] // Grid |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #ARM_Assembly | ARM Assembly | arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run |
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.
| #Visual_Basic | Visual Basic | MustInherit Class Base
Protected Sub New()
End Sub
Public Sub StandardMethod()
'code
End Sub
Public Overridable Sub Method_Can_Be_Replaced()
'code
End Sub
Public MustOverride Sub Method_Must_Be_Replaced()
End Class |
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.
| #Visual_Basic_.NET | Visual Basic .NET | MustInherit Class Base
Protected Sub New()
End Sub
Public Sub StandardMethod()
'code
End Sub
Public Overridable Sub Method_Can_Be_Replaced()
'code
End Sub
Public MustOverride Sub Method_Must_Be_Replaced()
End Class |
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.
| #Scheme | Scheme | (define (A m n)
(cond
((= m 0) (+ n 1))
((= n 0) (A (- m 1) 1))
(else (A (- m 1) (A m (- 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
| #Transd | Transd | #lang transd
MainModule : {
_start: (λ
(with fs FileStream() words String()
(open-r fs "D:\\Temp\\wordlist.txt")
(for line in (read-lines fs) do
(with days (split line " ") len 0
(for w in days do (for y in days do
(if (neq w y) (= len (max len (coincide w y))))))
(lout (+ len 1) " " days))
) ) )
} |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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++ | g++-4.7 -Wall -std=c++0x abc.cpp |
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)
| #Maxima | Maxima | block([k: 0, n: 1, l: []],
while k < 25 do (
n: n+2,
if divsum(n,-1) > 2 then (
k: k+1,
l: append(l, [[n,divsum(n)]])
)
),
return(l)
); |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Delphi | Delphi | print "Who reaches 21, wins"
print "Do you want to begin (y/n)"
if input = "n"
who = 1
.
who$[] = [ "Human" "Computer" ]
repeat
if who = 0
repeat
print ""
print "Choose 1,2 or 3 (q for quit)"
a$ = input
n = number a$
until a$ = "q" or (n >= 1 and n <= 3)
.
else
sleep 1
if sum mod 4 = 1
n = random 3 + 1
else
n = 4 - (sum + 3) mod 4
.
.
sum += n
print who$[who] & ": " & n & " --> " & sum
until sum >= 21 or a$ = "q"
who = (who + 1) mod 2
.
if a$ <> "q"
print ""
if who = 0
print "Congratulation, you won"
else
print "Sorry, you lost"
.
. |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game24Solvex64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBDIGITS, 4 // digits number
.equ TOTAL, 24
.equ BUFFERSIZE, 80
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRules: .ascii "24 Game\n"
.ascii "The program will display four randomly-generated \n"
.asciz "single-digit numbers and search a solution for a total to 24\n\n"
szMessDigits: .asciz "The four digits are @ @ @ @ and the score is 24. \n"
szMessOK: .asciz "Solution : \n"
szMessNotOK: .asciz "No solution for this problem !! \n"
szMessNewGame: .asciz "New game (y/n) ? \n"
szMessErrOper: .asciz "Error opérator in display result !!!"
szCarriageReturn: .asciz "\n"
.align 4
qGraine: .quad 123456
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
sZoneConv: .skip 24
sBuffer: .skip BUFFERSIZE
qTabDigit: .skip 8 * NBDIGITS // digits table
qTabOperand1: .skip 8 * NBDIGITS // operand 1 table
qTabOperand2: .skip 8 * NBDIGITS // operand 2 table
qTabOperation: .skip 8 * NBDIGITS // operator table
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRules // display rules
bl affichageMess
1:
mov x3,#0
ldr x12,qAdrqTabDigit
ldr x5,qAdrszMessDigits
2: // loop generate random digits
mov x0,#8
bl genereraleas
add x0,x0,#1
str x0,[x12,x3,lsl 3] // store in table
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
mov x0,x5
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x5,x0
add x3,x3,#1
cmp x3,#NBDIGITS // end ?
blt 2b // no -> loop
mov x0,x5
bl affichageMess
mov x0,#0 // start leval
mov x1,x12 // address digits table
bl searchSoluce
cmp x0,#-1 // solution ?
bne 3f // no
ldr x0,qAdrszMessOK
bl affichageMess
bl writeSoluce // yes -> write solution in buffer
ldr x0,qAdrsBuffer // and display buffer
bl affichageMess
b 10f
3: // display message no solution
ldr x0,qAdrszMessNotOK
bl affichageMess
10: // display new game ?
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrszMessNewGame
bl affichageMess
bl saisie
cmp x0,#'y'
beq 1b
cmp x0,#'Y'
beq 1b
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
qAdrszMessRules: .quad szMessRules
qAdrszMessDigits: .quad szMessDigits
qAdrszMessNotOK: .quad szMessNotOK
qAdrszMessOK: .quad szMessOK
qAdrszMessNewGame: .quad szMessNewGame
qAdrsZoneConv: .quad sZoneConv
qAdrqTabDigit: .quad qTabDigit
/******************************************************************/
/* recherche solution */
/******************************************************************/
/* x0 level */
/* x1 table value address */
/* x0 return -1 if ok */
searchSoluce:
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,fp,[sp,-16]! // save registres
sub sp,sp,#8* NBDIGITS // reserve size new digits table
mov fp,sp // frame pointer = address stack
mov x10,x1 // save table
add x9,x0,#1 // new level
mov x13,#NBDIGITS
sub x3,x13,x9 // last element digits table
ldr x4,[x1,x3,lsl 3] // load last element
cmp x4,#TOTAL // equal to total to search ?
bne 0f // no
cmp x9,#NBDIGITS // all digits are used ?
bne 0f // no
mov x0,#-1 // yes -> it is ok -> end
b 100f
0:
mov x5,#0 // indice loop 1
1: // begin loop 1
cmp x5,x3
bge 9f
ldr x4,[x10,x5,lsl 3] // load first operand
ldr x8,qAdrqTabOperand1
str x4,[x8,x9,lsl 3] // and store in operand1 table
add x6,x5,#1 // indice loop 2
2: // begin loop 2
cmp x6,x3
bgt 8f
ldr x12,[x10,x6,lsl 3] // load second operand
ldr x8,qAdrqTabOperand2
str x12,[x8,x9,lsl 3] // and store in operand2 table
mov x7,#0 // k
mov x8,#0 // n
3:
cmp x7,x5
beq 4f
cmp x7,x6
beq 4f
ldr x0,[x10,x7,lsl 3] // copy other digits in new table on stack
str x0,[fp,x8,lsl 3]
add x8,x8,#1
4:
add x7,x7,#1
cmp x7,x3
ble 3b
add x7,x4,x12 // addition test
str x7,[fp,x8,lsl 3] // store result of addition
mov x7,#'+'
ldr x0,qAdrqTabOperation
str x7,[x0,x9,lsl 3] // store operator
mov x0,x9 // pass new level
mov x1,fp // pass new table address on stack
bl searchSoluce
cmp x0,#0
blt 100f
// soustraction test
sub x13,x4,x12
sub x14,x12,x4
cmp x4,x12
csel x7,x13,x14,gt
str x7,[fp,x8,lsl 3]
mov x7,#'-'
ldr x0,qAdrqTabOperation
str x7,[x0,x9,lsl 3]
mov x0,x9
mov x1,fp
bl searchSoluce
cmp x0,#0
blt 100f
mul x7,x4,x12 // multiplication test
str x7,[fp,x8,lsl 3]
mov x7,#'*'
ldr x0,qAdrqTabOperation
str x7,[x0,x9,lsl 3]
mov x0,x9
mov x1,fp
bl searchSoluce
cmp x0,#0
blt 100f
5: // division test
udiv x13,x4,x12
msub x14,x13,x12,x4
cmp x14,#0
bne 6f
str x13,[fp,x8,lsl 3]
mov x7,#'/'
ldr x0,qAdrqTabOperation
str x7,[x0,x9,lsl 3]
mov x0,x9
mov x1,fp
bl searchSoluce
b 7f
6:
udiv x13,x12,x4
msub x14,x13,x4,x12
cmp x14,#0
bne 7f
str x13,[fp,x8,lsl 3]
mov x7,#'/'
ldr x0,qAdrqTabOperation
str x7,[x0,x9,lsl 3]
mov x0,x9
mov x1,fp
bl searchSoluce
7:
cmp x0,#0
blt 100f
add x6,x6,#1 // increment indice loop 2
b 2b
8:
add x5,x5,#1 // increment indice loop 1
b 1b
9:
100:
add sp,sp,8* NBDIGITS // stack alignement
ldp x12,fp,[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
qAdrqTabOperand1: .quad qTabOperand1
qAdrqTabOperand2: .quad qTabOperand2
qAdrqTabOperation: .quad qTabOperation
/******************************************************************/
/* write solution */
/******************************************************************/
writeSoluce:
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,fp,[sp,-16]! // save registres
ldr x6,qAdrqTabOperand1
ldr x7,qAdrqTabOperand2
ldr x8,qAdrqTabOperation
ldr x10,qAdrsBuffer
mov x4,#0 // buffer indice
mov x9,#1
1:
ldr x13,[x6,x9,lsl 3] // operand 1
ldr x11,[x7,x9,lsl 3] // operand 2
ldr x12,[x8,x9,lsl 3] // operator
cmp x12,#'-'
beq 2f
cmp x12,#'/'
beq 2f
b 3f
2: // if division or soustraction
cmp x13,x11 // reverse operand if operand 1 is < operand 2
bge 3f
mov x2,x13
mov x13,x11
mov x11,x2
3: // conversion operand 1 = x13
mov x1,#10
udiv x2,x13,x1
msub x3,x1,x2,x13
cmp x2,#0
beq 31f
add x2,x2,#0x30
strb w2,[x10,x4]
add x4,x4,#1
31:
add x3,x3,#0x30
strb w3,[x10,x4]
add x4,x4,#1
ldr x2,[x7,x9,lsl 3]
strb w12,[x10,x4] // operator
add x4,x4,#1
mov x1,#10 // conversion operand 2 = x11
udiv x2,x11,x1
msub x3,x2,x1,x11
cmp x2,#0
beq 32f
add x2,x2,#0x30
strb w2,[x10,x4]
add x4,x4,#1
32:
add x3,x3,#0x30
strb w3,[x10,x4]
add x4,x4,#1
mov x0,#'='
strb w0,[x10,x4] // compute sous total
add x4,x4,#1
cmp x12,'+' // addition
bne 33f
add x0,x13,x11
b 37f
33:
cmp x12,'-' // soustraction
bne 34f
sub x0,x13,x11
b 37f
34:
cmp x12,'*' // multiplication
bne 35f
mul x0,x13,x11
b 37f
35:
cmp x12,'/' // division
bne 36f
udiv x0,x13,x11
b 37f
36: // error
ldr x0,qAdrszMessErrOper
bl affichageMess
b 100f
37: // and conversion ascii
mov x1,#10
udiv x2,x0,x1
msub x3,x2,x1,x0
cmp x2,#0
beq 36f
add x2,x2,#0x30
strb w2,[x10,x4]
add x4,x4,#1
36:
add x3,x3,#0x30
strb w3,[x10,x4]
add x4,x4,#1
mov x0,#'\n'
strb w0,[x10,x4]
add x4,x4,#1
add x9,x9,1
cmp x9,#NBDIGITS
blt 1b
mov x1,#0
strb w1,[x10,x4] // store 0 final
100:
ldp x12,fp,[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
qAdrsBuffer: .quad sBuffer
qAdrszMessErrOper: .quad szMessErrOper
/******************************************************************/
/* string entry */
/******************************************************************/
/* x0 return the first character of human entry */
saisie:
stp x1,lr,[sp,-16]! // save registres
stp x2,x8,[sp,-16]! // save registres
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,#READ // request to read datas
svc 0 // call system
ldr x1,qAdrsBuffer // buffer address
ldrb w0,[x1] // load first character
100:
ldp x2,x8,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* Generation random number */
/***************************************************/
/* x0 contains limit */
genereraleas:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
ldr x4,qAdrqGraine
ldr x2,[x4]
ldr x3,qNbDep1
mul x2,x3,x2
ldr x3,qNbDep2
add x2,x2,x3
str x2,[x4] // maj de la graine pour l appel suivant
cmp x0,#0
beq 100f
add x1,x0,#1 // divisor
mov x0,x2 // dividende
udiv x3,x2,x1
msub x0,x3,x1,x0 // résult = remainder
100: // end function
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
/*****************************************************/
qAdrqGraine: .quad qGraine
qNbDep1: .quad 0x0019660d
qNbDep2: .quad 0x3c6ef35f
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Fortran | Fortran | WRITE(...) FIRST,LAST,IF (UNIQUE) THEN "Distinct values only" ELSE "Repeated values allowed" FI // "." |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Ada | Ada | with Ada.Float_Text_IO;
with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Game_24 is
subtype Digit is Character range '1' .. '9';
package Random_Digit is new Ada.Numerics.Discrete_Random (Digit);
Exp_Error : exception;
Digit_Generator : Random_Digit.Generator;
Given_Digits : array (1 .. 4) of Digit;
Float_Value : constant array (Digit) of Float :=
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
function Apply_Op (L, R : Float; Op : Character) return Float is
begin
case Op is
when '+' =>
return L + R;
when '-' =>
return L - R;
when '*' =>
return L * R;
when '/' =>
return L / R;
when others =>
Ada.Text_IO.Put_Line ("Unexpected operator: " & Op);
raise Exp_Error;
end case;
end Apply_Op;
function Eval_Exp (E : String) return Float is
Flt : Float;
First : Positive := E'First;
Last : Positive;
function Match_Paren (Start : Positive) return Positive is
Pos : Positive := Start + 1;
Level : Natural := 1;
begin
loop
if Pos > E'Last then
Ada.Text_IO.Put_Line ("Unclosed parentheses.");
raise Exp_Error;
elsif E (Pos) = '(' then
Level := Level + 1;
elsif E (Pos) = ')' then
Level := Level - 1;
exit when Level = 0;
end if;
Pos := Pos + 1;
end loop;
return Pos;
end Match_Paren;
begin
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Eval_Exp (E (First + 1 .. Last - 1));
elsif E (First) in Digit then
Last := First;
Flt := Float_Value (E (First));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
loop
if Last = E'Last then
return Flt;
elsif Last = E'Last - 1 then
Ada.Text_IO.Put_Line ("Unexpected end of expression.");
raise Exp_Error;
end if;
First := Last + 2;
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Apply_Op (Flt, Eval_Exp (E (First + 1 .. Last - 1)),
Op => E (First - 1));
elsif E (First) in Digit then
Last := First;
Flt := Apply_Op (Flt, Float_Value (E (First)),
Op => E (First - 1));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
end loop;
end Eval_Exp;
begin
Ada.Text_IO.Put_Line ("24 Game");
Ada.Text_IO.Put_Line ("- Enter Q to Quit");
Ada.Text_IO.Put_Line ("- Enter N for New digits");
Ada.Text_IO.Put_Line ("Note: Operators are evaluated left-to-right");
Ada.Text_IO.Put_Line (" (use parentheses to override)");
Random_Digit.Reset (Digit_Generator);
<<GEN_DIGITS>>
Ada.Text_IO.Put_Line ("Generating 4 digits...");
for I in Given_Digits'Range loop
Given_Digits (I) := Random_Digit.Random (Digit_Generator);
end loop;
<<GET_EXP>>
Ada.Text_IO.Put ("Your Digits:");
for I in Given_Digits'Range loop
Ada.Text_IO.Put (" " & Given_Digits (I));
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Enter your Expression: ");
declare
Value : Float;
Response : constant String := Ada.Text_IO.Get_Line;
Prev_Ch : Character := ' ';
Unused_Digits : array (Given_Digits'Range) of Boolean :=
(others => True);
begin
if Response = "n" or Response = "N" then
goto GEN_DIGITS;
end if;
if Response = "q" or Response = "Q" then
return;
end if;
-- check input
for I in Response'Range loop
declare
Ch : constant Character := Response (I);
Found : Boolean;
begin
if Ch in Digit then
if Prev_Ch in Digit then
Ada.Text_IO.Put_Line ("Illegal multi-digit number used.");
goto GET_EXP;
end if;
Found := False;
for J in Given_Digits'Range loop
if Unused_Digits (J) and then
Given_Digits (J) = Ch then
Unused_Digits (J) := False;
Found := True;
exit;
end if;
end loop;
if not Found then
Ada.Text_IO.Put_Line ("Illegal number used: " & Ch);
goto GET_EXP;
end if;
elsif Ch /= '(' and Ch /= ')' and Ch /= '+' and
Ch /= '-' and Ch /= '*' and Ch /= '/' then
Ada.Text_IO.Put_Line ("Illegal character used: " & Ch);
goto GET_EXP;
end if;
Prev_Ch := Ch;
end;
end loop;
-- check all digits used
for I in Given_Digits'Range loop
if Unused_Digits (I) then
Ada.Text_IO.Put_Line ("Digit not used: " & Given_Digits (I));
goto GET_EXP;
end if;
end loop;
-- check value
begin
Value := Eval_Exp (Response);
exception
when Exp_Error =>
goto GET_EXP; -- Message displayed by Eval_Exp;
end;
if abs (Value - 24.0) > 0.001 then
Ada.Text_IO.Put ("Value ");
Ada.Float_Text_IO.Put (Value, Fore => 0, Aft => 3, Exp => 0);
Ada.Text_IO.Put_Line (" is not 24!");
goto GET_EXP;
else
Ada.Text_IO.Put_Line ("You won!");
Ada.Text_IO.Put_Line ("Enter N for a new game, or try another solution.");
goto GET_EXP;
end if;
end;
end Game_24; |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Maxima | Maxima | for n thru 25 do print(makelist(length(integer_partitions(n-k,k)),k,1,n))$ |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Nim | Nim | import bigints
var cache = @[@[1.initBigInt]]
proc cumu(n: int): seq[BigInt] =
for m in cache.len .. n:
var r = @[0.initBigInt]
for x in 1..m:
r.add r[r.high] + cache[m-x][min(x, m-x)]
cache.add r
result = cache[n]
proc row(n: int): seq[BigInt] =
let r = cumu n
result = @[]
for i in 0 .. <n:
result.add r[i+1] - r[i]
echo "rows:"
for x in 1..10:
echo row x
echo "sums:"
for x in [23, 123, 1234, 12345]:
let c = cumu(x)
echo x, " ", c[c.high] |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #Arturo | Arturo | while ø [
x: map split.words input "give me 2 numbers:" 'x -> to :integer x
print add x\0 x\1
]
|
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.
| #Vlang | Vlang | interface Beast {
kind() string
name() string
cry() string
}
struct Dog {
kind string
name string
}
fn (d Dog) kind() string { return d.kind }
fn (d Dog) name() string { return d.name }
fn (d Dog) cry() string { return "Woof" }
struct Cat {
kind string
name string
}
fn (c Cat) kind() string { return c.kind }
fn (c Cat) name() string { return c.name }
fn (c Cat) cry() string { return "Meow" }
fn bprint(b Beast) {
println("${b.name()}, who's a ${b.kind()}, cries: ${b.cry()}.")
}
fn main() {
d := Dog{"labrador", "Max"}
c := Cat{"siamese", "Sammy"}
bprint(d)
bprint(c)
} |
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.
| #Wren | Wren | import "/fmt" for Fmt
class Beast{
kind {}
name {}
cry() {}
print() { System.print("%(name), who's a %(kind), cries: %(Fmt.q(cry())).") }
}
class Dog is Beast {
construct new(kind, name) {
_kind = kind
_name = name
}
kind { _kind }
name { _name }
cry() { "Woof" }
}
class Cat is Beast {
construct new(kind, name) {
_kind = kind
_name = name
}
kind { _kind }
name { _name }
cry() { "Meow" }
}
var d = Dog.new("labrador", "Max")
var c = Cat.new("siamese", "Sammy")
d.print()
c.print() |
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.
| #Scilab | Scilab | clear
function acker=ackermann(m,n)
global calls
calls=calls+1
if m==0 then acker=n+1
else
if n==0 then acker=ackermann(m-1,1)
else acker=ackermann(m-1,ackermann(m,n-1))
end
end
endfunction
function printacker(m,n)
global calls
calls=0
printf('ackermann(%d,%d)=',m,n)
printf('%d calls=%d\n',ackermann(m,n),calls)
endfunction
maxi=3; maxj=6
for i=0:maxi
for j=0:maxj
printacker(i,j)
end
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
| #TSE_SAL | TSE SAL |
STRING PROC FNStringGetExpressionRegularCharacterMetaEscapeS( STRING inS )
STRING s[255] = inS
s = StrReplace( "\", s, "\\", "gn" )
s = StrReplace( "{", s, "\{", "gn" )
s = StrReplace( "[", s, "\[", "gn" )
s = StrReplace( "}", s, "\}", "gn" )
s = StrReplace( "]", s, "\]", "gn" )
s = StrReplace( "*", s, "\*", "gn" )
s = StrReplace( "+", s, "\+", "gn" )
s = StrReplace( "@", s, "\@", "gn" )
s = StrReplace( ".", s, "\.", "gn" )
s = StrReplace( "^", s, "\^", "gn" )
s = StrReplace( "$", s, "\$", "gn" )
s = StrReplace( "|", s, "\|", "gn" )
s = StrReplace( "?", s, "\?", "gn" )
s = StrReplace( "#", s, "\#", "gn" )
RETURN( s )
END
//
INTEGER PROC FNBlockGetAbbreviationLengthMinimumToBufferB( INTEGER buffer1I )
INTEGER B = FALSE
INTEGER downB = TRUE
STRING s[255] = ""
INTEGER foundB = FALSE
INTEGER minI = 1
INTEGER I = 0
INTEGER buffer2I = 0
STRING s1[255] = ""
INTEGER lineColumnStartI = 4 // change this
Set( BREAK, ON )
PushPosition()
PushBlock()
GotoBlockBegin()
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
I = minI - 1
REPEAT
I = I + 1
PushPosition()
buffer2I = CreateTempBuffer()
PopPosition()
BegLine()
REPEAT
IF ( LFind( "{.*}{{[ ]#}|$}\c", "cx" ) )
s = GetFoundText( 1 )
s = Trim( s )
s1 = LeftStr( s, I )
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
foundB = LFind( Format( "^", FNStringGetExpressionRegularCharacterMetaEscapeS( s1 ), "$" ), "gx" )
IF NOT foundB
EndFile()
AddLine( s1 )
ENDIF
PopBlock()
PopPosition()
ENDIF
UNTIL ( ( ( CurrChar() == _AT_EOL_ ) OR ( CurrChar() == _BEYOND_EOL_ ) ) OR ( foundB ) )
AbandonFile( buffer2I )
UNTIL ( NOT ( foundB ) )
ENDIF
IF NOT foundB
PushPosition()
PushBlock()
BegLine()
UnMarkBlock()
MarkStream()
EndLine()
Left()
MarkStream()
Copy()
GotoBufferId( buffer1I )
EndFile()
AddLine( Str( I ) )
GotoColumn( lineColumnStartI )
Paste()
PopBlock()
PopPosition()
ENDIF
downB = Down()
ENDWHILE
B = TRUE
PopPosition()
PopBlock()
RETURN( B )
END
//
PROC Main()
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
Message( FNBlockGetAbbreviationLengthMinimumToBufferB( bufferI ) )
GotoBufferId( bufferI )
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
| #VBA | VBA | Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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
| #Ceylon | Ceylon |
module rosetta.abc "1.0.0" {}
|
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)
| #Nim | Nim |
from math import sqrt
import strformat
#---------------------------------------------------------------------------------------------------
proc sumProperDivisors(n: int): int =
## Compute the sum of proper divisors.
## "n" is supposed to be odd.
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
#---------------------------------------------------------------------------------------------------
iterator oddAbundant(start: int): tuple[n, s: int] =
## Yield the odd abundant numbers and the sum of their proper
## divisors greater or equal to "start".
var n = start + (start and 1 xor 1) # Start with an odd number.
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
#---------------------------------------------------------------------------------------------------
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
|
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #EasyLang | EasyLang | print "Who reaches 21, wins"
print "Do you want to begin (y/n)"
if input = "n"
who = 1
.
who$[] = [ "Human" "Computer" ]
repeat
if who = 0
repeat
print ""
print "Choose 1,2 or 3 (q for quit)"
a$ = input
n = number a$
until a$ = "q" or (n >= 1 and n <= 3)
.
else
sleep 1
if sum mod 4 = 1
n = random 3 + 1
else
n = 4 - (sum + 3) mod 4
.
.
sum += n
print who$[who] & ": " & n & " --> " & sum
until sum >= 21 or a$ = "q"
who = (who + 1) mod 2
.
if a$ <> "q"
print ""
if who = 0
print "Congratulation, you won"
else
print "Sorry, you lost"
.
. |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #ABAP | ABAP | data: lv_flag type c,
lv_number type i,
lt_numbers type table of i.
constants: c_no_val type i value 9999.
append 1 to lt_numbers.
append 1 to lt_numbers.
append 2 to lt_numbers.
append 7 to lt_numbers.
write 'Evaluating 24 with the following input: '.
loop at lt_numbers into lv_number.
write lv_number.
endloop.
perform solve_24 using lt_numbers.
form eval_formula using iv_eval type string changing ev_out type i.
call function 'EVAL_FORMULA' "analysis of a syntactically correct formula
exporting
formula = iv_eval
importing
value = ev_out
exceptions
others = 1.
if sy-subrc <> 0.
ev_out = -1.
endif.
endform.
" Solve a 24 puzzle.
form solve_24 using it_numbers like lt_numbers.
data: lv_flag type c,
lv_op1 type c,
lv_op2 type c,
lv_op3 type c,
lv_var1 type c,
lv_var2 type c,
lv_var3 type c,
lv_var4 type c,
lv_eval type string,
lv_result type i,
lv_var type i.
define retrieve_var.
read table it_numbers index &1 into lv_var.
&2 = lv_var.
end-of-definition.
define retrieve_val.
perform eval_formula using lv_eval changing lv_result.
if lv_result = 24.
write / lv_eval.
endif.
end-of-definition.
" Loop through all the possible number permutations.
do.
" Init. the operations table.
retrieve_var: 1 lv_var1, 2 lv_var2, 3 lv_var3, 4 lv_var4.
do 4 times.
case sy-index.
when 1.
lv_op1 = '+'.
when 2.
lv_op1 = '*'.
when 3.
lv_op1 = '-'.
when 4.
lv_op1 = '/'.
endcase.
do 4 times.
case sy-index.
when 1.
lv_op2 = '+'.
when 2.
lv_op2 = '*'.
when 3.
lv_op2 = '-'.
when 4.
lv_op2 = '/'.
endcase.
do 4 times.
case sy-index.
when 1.
lv_op3 = '+'.
when 2.
lv_op3 = '*'.
when 3.
lv_op3 = '-'.
when 4.
lv_op3 = '/'.
endcase.
concatenate '(' '(' lv_var1 lv_op1 lv_var2 ')' lv_op2 lv_var3 ')' lv_op3 lv_var4 into lv_eval separated by space.
retrieve_val.
concatenate '(' lv_var1 lv_op1 lv_var2 ')' lv_op2 '(' lv_var3 lv_op3 lv_var4 ')' into lv_eval separated by space.
retrieve_val.
concatenate '(' lv_var1 lv_op1 '(' lv_var2 lv_op2 lv_var3 ')' ')' lv_op3 lv_var4 into lv_eval separated by space.
retrieve_val.
concatenate lv_var1 lv_op1 '(' '(' lv_var2 lv_op2 lv_var3 ')' lv_op3 lv_var4 ')' into lv_eval separated by space.
retrieve_val.
concatenate lv_var1 lv_op1 '(' lv_var2 lv_op2 '(' lv_var3 lv_op3 lv_var4 ')' ')' into lv_eval separated by space.
retrieve_val.
enddo.
enddo.
enddo.
" Once we've reached the last permutation -> Exit.
perform permute using it_numbers changing lv_flag.
if lv_flag = 'X'.
exit.
endif.
enddo.
endform.
" Permutation function - this is used to permute:
" A = {A1...AN} -> Set of supplied variables.
" B = {B1...BN - 1} -> Set of operators.
" Can be used for an unbounded size set. Relies
" on lexicographic ordering of the set.
form permute using iv_set like lt_numbers
changing ev_last type c.
data: lv_len type i,
lv_first type i,
lv_third type i,
lv_count type i,
lv_temp type i,
lv_temp_2 type i,
lv_second type i,
lv_changed type c,
lv_perm type i.
describe table iv_set lines lv_len.
lv_perm = lv_len - 1.
lv_changed = ' '.
" Loop backwards through the table, attempting to find elements which
" can be permuted. If we find one, break out of the table and set the
" flag indicating a switch.
do.
if lv_perm <= 0.
exit.
endif.
" Read the elements.
read table iv_set index lv_perm into lv_first.
add 1 to lv_perm.
read table iv_set index lv_perm into lv_second.
subtract 1 from lv_perm.
if lv_first < lv_second.
lv_changed = 'X'.
exit.
endif.
subtract 1 from lv_perm.
enddo.
" Last permutation.
if lv_changed <> 'X'.
ev_last = 'X'.
exit.
endif.
" Swap tail decresing to get a tail increasing.
lv_count = lv_perm + 1.
do.
lv_first = lv_len + lv_perm - lv_count + 1.
if lv_count >= lv_first.
exit.
endif.
read table iv_set index lv_count into lv_temp.
read table iv_set index lv_first into lv_temp_2.
modify iv_set index lv_count from lv_temp_2.
modify iv_set index lv_first from lv_temp.
add 1 to lv_count.
enddo.
lv_count = lv_len - 1.
do.
if lv_count <= lv_perm.
exit.
endif.
read table iv_set index lv_count into lv_first.
read table iv_set index lv_perm into lv_second.
read table iv_set index lv_len into lv_third.
if ( lv_first < lv_third ) and ( lv_first > lv_second ).
lv_len = lv_count.
endif.
subtract 1 from lv_count.
enddo.
read table iv_set index lv_perm into lv_temp.
read table iv_set index lv_len into lv_temp_2.
modify iv_set index lv_perm from lv_temp_2.
modify iv_set index lv_len from lv_temp.
endform. |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #FreeBASIC | FreeBASIC | ' version 18-03-2017
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Sub four_rings(low As Long, high As Long, unique As Long, show As Long)
Dim As Long a, b, c, d, e, f, g
Dim As ULong t, total
Dim As ULong l = Len(Str(high))
If l < Len(Str(low)) Then l = Len(Str(low))
If show = TRUE Then
For a = 97 To 103
Print Space(l); Chr(a);
Next
Print
Print String((l +1) * 7, "=");
Print
End If
For a = low To high
For b = low To high
If unique = TRUE Then
If b = a Then Continue For
End If
t = a + b
For c = low To high
If unique = TRUE Then
If c = a OrElse c = b Then Continue For
End If
For d = low To high
If unique = TRUE Then
If d = a OrElse d = b OrElse d = c Then Continue For
End If
If b + c + d = t Then
For e = low To high
If unique = TRUE Then
If e = a OrElse e = b OrElse e = c OrElse e = d Then Continue For
End If
For f = low To high
If unique = TRUE Then
If f = a OrElse f = b OrElse f = c OrElse f = d OrElse f = e Then Continue For
End If
If d + e + f = t Then
For g = low To high
If unique = TRUE Then
If g = a OrElse g = b OrElse g = c OrElse g = d OrElse g = e OrElse g = f Then Continue For
End If
If f + g = t Then
total += 1
If show = TRUE Then
Print Using String(l +1, "#"); a; b; c; d; e; f; g
End If
End If
Next
End If
Next
Next
End If
Next
Next
Next
Next
If unique = TRUE Then
Print
Print total; " Unique solutions for "; Str(low); " to "; Str(high)
Else
Print total; " Non unique solutions for "; Str(low); " to "; Str(high)
End If
Print String(40, "-") : Print
End Sub
' ------=< MAIN >=------
four_rings(1, 7, TRUE, TRUE)
four_rings(3, 9, TRUE, TRUE)
four_rings(0, 9, FALSE, FALSE)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #APL | APL | tfgame←{⎕IO←1
⎕←d←?⍵⍴9
i←⍞
u[⍋u←{⍎¨⍣(0≠≢⍵)⊢⍵}(i∊'1234567890')⊆i]≢d[⍋d]:'nope'
~∧/((~b←i∊'1234567890')/i)∊'+-×÷()':'nope'
24≠⍎i:'nope'
'Yeah!'
} |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #OCaml | OCaml |
let get, sum_unto =
let cache = ref [||]
let rec get i j =
if Array.length !cache < i then
cache :=
Array.init i begin fun i ->
try !cache.(i) with Invalid_argument _ ->
Array.make (i+1) (Num.num_of_int 0)
end;
if Num.(!cache.(i-1).(j-1) =/ num_of_int 0)
then !cache.(i-1).(j-1) <- sum_unto (i-j) j;
!cache.(i-1).(j-1)
and sum_unto i j =
let rec sum_unto sum i j =
match (i,j) with
|(0,0) -> (Num.num_of_int 1)
|(_,0) -> sum
|(i,j) when j > i -> sum_unto sum i i
|(i,j) -> sum_unto Num.(sum +/ (get i j)) i (j-1)
in
sum_unto (Num.num_of_int 0) i j
in
get, sum_unto
let sum_of_row n = sum_unto n n
let euler_recurrence =
let cache = ref [||] in
let rec recurrence = function
|n when n < 0 -> Num.num_of_int 0
|0 -> Num.num_of_int 1
|n ->
if n >= Array.length !cache then
cache :=
Array.init (n+1) (fun i ->
try !cache.(i) with Invalid_argument _ -> Num.num_of_int 0);
if Num.(!cache.(n) =/ num_of_int 0)
then begin
let rec summing sum = function
|0 -> sum
|k ->
let op = if k mod 2 = 0 then Num.sub_num else Num.add_num in
let sum = op sum (recurrence (n - k * (3*k - 1) / 2)) in
let sum = op sum (recurrence (n - k * (3*k + 1) / 2)) in
summing sum (k-1)
in
!cache.(n) <- summing (Num.num_of_int 0) n
end;
!cache.(n)
in
recurrence
let print i_max =
for i=1 to i_max do
print_int (i+1); print_string ": ";
for j=1 to i do
print_string (Num.string_of_num (get i j));
print_char ' ';
done;
print_newline ();
done
let () =
print 30;
print_newline ();
List.iter begin fun i ->
Printf.printf "%i: %s ?= %s\n" i
(Num.string_of_num (sum_of_row i))
(Num.string_of_num (euler_recurrence i));
flush stdout;
end
[23;123;1234;];
List.iter begin fun i ->
Printf.printf "%i: %s\n" i
(Num.string_of_num (euler_recurrence i));
flush stdout;
end
[23;123;1234;12345;123456]
|
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #AsciiDots | AsciiDots |
&-#$-\
.-#?-[+]
.-#?--/
|
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.
| #zkl | zkl | class Stream{ // Mostly virtural base class
var [proxy protected]
isBroken = fcn { _broken.isSet() },
isClosed = fcn { return(_closed.isSet() or _broken.isSet()); };
fcn init{
var [protected]
_closed = Atomic.Bool(True),
_broken = Atomic.Bool(False),
whyBroken = Void;
}
fcn clear { _closed.clear(); _broken.clear(); return(self.topdog); }
fcn open { return(topdog.init(vm.pasteArgs())); }
fcn toStream { return(self); }
fcn close { _closed.set(); return(self.topdog); }
fcn flush { return(self.topdog); }
fcn read { throw(Exception.TheEnd); } // destructive or advance
fcn readln { throw(Exception.TheEnd); }
fcn write(x) { return(self.topdog); }
fcn writeln(x) { return(self.topdog); }
fcn walker { return((0).walker(*,wap((self.topdog.read.fpM(""))))); }
} |
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.
| #Seed7 | Seed7 | const func integer: ackermann (in integer: m, in integer: n) is func
result
var integer: result is 0;
begin
if m = 0 then
result := succ(n);
elsif n = 0 then
result := ackermann(pred(m), 1);
else
result := ackermann(pred(m), ackermann(m, pred(n)));
end if;
end func; |
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
| #VBScript | VBScript |
sub print(s) wscript.stdout.writeline s :end sub
set d=createobject("Scripting.Dictionary")
set fso=createobject("Scripting.Filesystemobject")
const fn="weekdays_ansi.txt"
sfn=WScript.ScriptFullName
sfn= Left(sfn, InStrRev(sfn, "\"))
set f=fso.opentextfile(sfn & fn,1)
while not f.atendofstream
s=f.readline
if s=vbNullString then
print " "
else
a=split(trim(s)," ")
for abrlen=1 to 14
d.removeall
for wd=0 to 6
k=left(a(wd),abrlen)
if d.exists(k) then
exit for
else
d.add k,""
end if
next 'wd
if wd>6 then exit for
next 'abrlen
b=right(" " & abrlen,2)
for wd=0 to 6
b=b &" "& left(a(wd),abrlen)
next
print b
end if
wend 'line
f.close
|
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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 |
(def blocks
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
(defn omit
"return bs with (one instance of) b omitted"
[bs b]
(let [[before after] (split-with #(not= b %) bs)]
(concat before (rest after))))
(defn abc
"return lazy sequence of solutions (i.e. block lists)"
[blocks [c & cs]]
(if (some? c)
(for [b blocks :when (some #(= c %) b)
bs (abc (omit blocks b) cs)]
(cons b bs))
[[]]))
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word))) |
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)
| #Pari.2FGP | Pari/GP | genit(brk1,brk2,brk3)={tcnt=0;
print("First 25 abundant odd numbers:");
forstep(n=1,999999999999999999,2,
if(tcnt==brk2&&n<brk3,next);
if(sigma(n)<=2*n,next);
tcnt+=1;
if(tcnt>brk1&&tcnt<brk2,next);
if(n>=brk3 && sigma(n)>2*n,print("The first odd abundant number greater than 1000000000 is ",n," with sigma = ",sigma(n) );break);
if(tcnt==brk2,print("The 1000th odd abundant number is ",n," with sigma = ",sigma(n) );next);
print(n," with sigma = ",sigma(n)));}
Output:
(11:14) gp > genit(25,1000,1000000000 )
First 25 abundant odd numbers:
945 with sigma = 1920
1575 with sigma = 3224
2205 with sigma = 4446
2835 with sigma = 5808
3465 with sigma = 7488
4095 with sigma = 8736
4725 with sigma = 9920
5355 with sigma = 11232
5775 with sigma = 11904
5985 with sigma = 12480
6435 with sigma = 13104
6615 with sigma = 13680
6825 with sigma = 13888
7245 with sigma = 14976
7425 with sigma = 14880
7875 with sigma = 16224
8085 with sigma = 16416
8415 with sigma = 16848
8505 with sigma = 17472
8925 with sigma = 17856
9135 with sigma = 18720
9555 with sigma = 19152
9765 with sigma = 19968
10395 with sigma = 23040
11025 with sigma = 22971
The 1000th odd abundant number is 492975 with sigma = 1012336
The first odd abundant number greater than 1000000000 is 1000000575 with sigma = 2083561584
(11:24) gp >
|
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Factor | Factor | USING: accessors combinators.random continuations formatting io
kernel math math.functions math.parser multiline qw random
sequences ;
IN: rosetta-code.21-game
STRING: welcome
21 is a two-player game. The game is played by choosing a number
(1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the
running total to reach 21.
One player will be the computer. Players alternate supplying a
number to be added to the running total.
;
: .welcome ( -- ) welcome print ;
SYMBOLS: +computer+ +human+ ;
TUPLE: game total difficulty who ;
! Instead of saying something dry like 'invalid input,' spice
! it up a little.
: insult ( -- )
{
"No." "Er..." "Learn to read." "I think not."
"Come on, is it really this difficult?"
} random print ;
: get-input ( options-seq prompt-str -- str )
dup "%s: " printf flush readln dup reach member?
[ 2nip ] [ drop insult get-input ] if ;
: get-integer ( options-seq prompt-str -- n )
get-input string>number ;
: get-difficulty ( -- x )
qw{ 1 2 3 4 5 6 7 8 9 10 }
"Difficulty (1-10)" get-integer 10 / ;
: human-move ( game -- n )
drop qw{ q 1 2 3 } "Your move (1-3) or q to quit" get-input
dup "q" = [ drop return ] when string>number ;
: choose-first-player ( difficulty -- player )
[ +computer+ ] [ +human+ ] ifp ;
: <game> ( -- game )
0 get-difficulty dup choose-first-player game boa ;
: swap-player ( game -- )
[ +human+ = +computer+ +human+ ? ] change-who drop ;
: .total ( game -- ) total>> "Running total: %d\n" printf ;
: random-move ( game -- n ) drop 3 random 1 + ;
: boundary? ( n -- ? ) 1 - 4 divisor? ;
: (optimal-move) ( m -- n ) dup 4 / ceiling 4 * 1 + swap - ;
: optimal-move ( game -- n )
total>> dup boundary? [ random-move ] [ (optimal-move) ] if ;
: computer-move ( game -- n )
dup difficulty>> [ optimal-move ] [ random-move ] ifp
dup "Computer chose %d.\n" printf ;
: do-turn ( game -- )
dup dup who>> +human+ = [ human-move ] [ computer-move ] if
[ + ] curry change-total dup .total swap-player ;
: do-turns ( game -- )
[ dup total>> 20 > ] [ dup do-turn ] until
dup swap-player who>> "%u wins!\n" printf ;
: play-21-game ( -- )
.welcome nl [ <game> do-turns ] with-return ;
MAIN: play-21-game |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Argile | Argile | die "Please give 4 digits as argument 1\n" if argc < 2
print a function that given four digits argv[1] subject to the rules of \
the _24_ game, computes an expression to solve the game if possible.
use std, array
let digits be an array of 4 byte
let operators be an array of 4 byte
(: reordered arrays :)
let (type of digits) rdigits
let (type of operators) roperators
.: a function that given four digits <text digits> subject to
the rules of the _24_ game, computes an expression to solve
the game if possible. :. -> text
if #digits != 4 {return "[error: need exactly 4 digits]"}
operators[0] = '+' ; operators[1] = '-'
operators[2] = '*' ; operators[3] = '/'
for each (val int d) from 0 to 3
if (digits[d] < '1') || (digits[d] > '9')
return "[error: non-digit character given]"
(super digits)[d] = digits[d]
let expr = for each operand order stuff
return "" if expr is nil
expr
.:for each operand order stuff:. -> text
for each (val int a) from 0 to 3
for each (val int b) from 0 to 3
next if (b == a)
for each (val int c) from 0 to 3
next if (c == b) or (c == a)
for each (val int d) from 0 to 3
next if (d == c) or (d == b) or (d == a)
rdigits[0] = digits[a] ; rdigits[1] = digits[b]
rdigits[2] = digits[c] ; rdigits[3] = digits[d]
let found = for each operator order stuff
return found unless found is nil
nil
.:for each operator order stuff:. -> text
for each (val int i) from 0 to 3
for each (val int j) from 0 to 3
for each (val int k) from 0 to 3
roperators[0] = operators[i]
roperators[1] = operators[j]
roperators[2] = operators[k]
let found = for each RPN pattern stuff
return found if found isn't nil
nil
our (raw array of text) RPN_patterns = Cdata
"xx.x.x."
"xx.xx.."
"xxx..x."
"xxx.x.."
"xxxx..."
our (raw array of text) formats = Cdata
"((%c%c%c)%c%c)%c%c"
"(%c%c%c)%c(%c%c%c)"
"(%c%c(%c%c%c))%c%c"
"%c%c((%c%c%c)%c%c)"
"%c%c(%c%c(%c%c%c))"
our (raw array of array of 3 int) rrop = Cdata
{0;1;2}; {0;2;1}; {1;0;2}; {2;0;1}; {2;1;0}
.:for each RPN pattern stuff:. -> text
let RPN_stack be an array of 4 real
for each (val int rpn) from 0 to 4
let (nat) sp=0, op=0, dg=0.
let text p
for (p = RPN_patterns[rpn]) (*p != 0) (p++)
if *p == 'x'
if sp >= 4 {die "RPN stack overflow\n"}
if dg > 3 {die "RPN digits overflow\n"}
RPN_stack[sp++] = (rdigits[dg++] - '0') as real
if *p == '.'
if sp < 2 {die "RPN stack underflow\n"}
if op > 2 {die "RPN operators overflow\n"}
sp -= 2
let x = RPN_stack[sp]
let y = RPN_stack[sp + 1]
switch roperators[op++]
case '+' {x += y}
case '-' {x -= y}
case '*' {x *= y}
case '/' {x /= y}
default {die "RPN operator unknown\n"}
RPN_stack[sp++] = x
if RPN_stack[0] == 24.0
our array of 12 byte buffer (: 4 paren + 3 ops + 4 digits + null :)
snprintf (buffer as text) (size of buffer) (formats[rpn]) \
(rdigits[0]) (roperators[(rrop[rpn][0])]) (rdigits[1]) \
(roperators[(rrop[rpn][1])]) (rdigits[2]) \
(roperators[(rrop[rpn][2])]) (rdigits[3]);
return buffer as text
nil |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Go | Go | package main
import "fmt"
func main(){
n, c := getCombs(1,7,true)
fmt.Printf("%d unique solutions in 1 to 7\n",n)
fmt.Println(c)
n, c = getCombs(3,9,true)
fmt.Printf("%d unique solutions in 3 to 9\n",n)
fmt.Println(c)
n, _ = getCombs(0,9,false)
fmt.Printf("%d non-unique solutions in 0 to 9\n",n)
}
func getCombs(low,high int,unique bool) (num int,validCombs [][]int){
for a := low; a <= high; a++ {
for b := low; b <= high; b++ {
for c := low; c <= high; c++ {
for d := low; d <= high; d++ {
for e := low; e <= high; e++ {
for f := low; f <= high; f++ {
for g := low; g <= high; g++ {
if validComb(a,b,c,d,e,f,g) {
if !unique || isUnique(a,b,c,d,e,f,g) {
num++
validCombs = append(validCombs,[]int{a,b,c,d,e,f,g})
}
}
}
}
}
}
}
}
}
return
}
func isUnique(a,b,c,d,e,f,g int) (res bool) {
data := make(map[int]int)
data[a]++
data[b]++
data[c]++
data[d]++
data[e]++
data[f]++
data[g]++
return len(data) == 7
}
func validComb(a,b,c,d,e,f,g int) bool{
square1 := a + b
square2 := b + c + d
square3 := d + e + f
square4 := f + g
return square1 == square2 && square2 == square3 && square3 == square4
}
|
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
97 bottles of beer on the wall
... and so on, until reaching 0 (zero).
Grammatical support for 1 bottle of beer is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
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
See also
http://99-bottles-of-beer.net/
Category:99_Bottles_of_Beer
Category:Programming language families
Wikipedia 99 bottles of beer
| #0815 | 0815 | L(i) (99..1).step(-1)
print(i‘ bottles of beer on the wall’)
print(i‘ bottles of beer’)
print(‘Take one down, pass it around’)
print((i - 1)" bottles of beer on the wall\n") |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Applesoft_BASIC | Applesoft BASIC | 0 BH = PEEK (104):BL = PEEK (103)
1 GOSUB 1200: CALL - 868
10 LET N$ = ""
20 R = RND ( - ( PEEK (78) + PEEK (79) * 256)): REM RANDOMIZE
30 FOR I = 1 TO 4
40 LET N$ = N$ + STR$ ( INT ( RND (1) * 9) + 1)
50 NEXT I
60 PRINT " PRESS A KEY TO CONTINUE. ";: GET A$
65 LET I$ = "": LET F$ = "": LET P$ = ""
70 HOME
80 PRINT M$M$ SPC( 16)"24 GAME"
90 PRINT M$"ALLOWED CHARACTERS:"M$
100 LET I$ = N$ + "+-*/()"
110 HTAB 20
120 FOR I = 1 TO 10
130 PRINT MID$ (I$,I,1)" ";
140 NEXT I
150 PRINT M$ TAB( 7)"0 TO END"M$
160 INPUT "ENTER THE FORMULA: ";F$
170 IF F$ = "0" THEN END : GOTO 65
180 PRINT M$ TAB( 7)F$" = ";
190 FOR I = 1 TO LEN (F$)
200 LET C$ = MID$ (F$,I,1)
210 IF C$ = " " THEN LET F$ = MID$ (F$,1,I - 1) + MID$ (F$,I + 1): GOTO 250
220 IF C$ = "+" OR C$ = "-" OR C$ = "*" OR C$ = "/" THEN LET P$ = P$ + "O": GOTO 250
230 IF C$ = "(" OR C$ = ")" THEN LET P$ = P$ + C$: GOTO 250
240 LET P$ = P$ + "N"
250 NEXT I
260 RESTORE
270 FOR I = 1 TO 11
280 READ T$
290 IF T$ = P$ THEN LET I = 11
300 NEXT I
310 IF T$ < > P$ THEN INVERSE : PRINT "BAD CONSTRUCTION!"G$M$: NORMAL : GOTO 60
320 FOR I = 1 TO LEN (F$)
330 FOR J = 1 TO 10
340 IF ( MID$ (F$,I,1) = MID$ (I$,J,1)) AND MID$ (F$,I,1) > "0" AND MID$ (F$,I,1) < = "9" THEN LET I$ = MID$ (I$,1,J - 1) + " " + MID$ (I$,J + 1, LEN (I$))
350 NEXT J,I
370 IF MID$ (I$,1,4) < > " " THEN INVERSE : PRINT "INVALID ARGUMENTS!"G$M$: NORMAL : GOTO 60
380 GOSUB 600: REM LET R = VAL(F$)
390 PRINT R" ";
400 IF R < > 24 THEN INVERSE : PRINT "WRONG!"G$M$: NORMAL : GOTO 60
410 INVERSE : PRINT "CORRECT!"M$: NORMAL : GOTO 10
420 DATA"NONONON"
430 DATA"(NON)ONON"
440 DATA"NONO(NON)"
450 DATA"NO(NO(NON))"
460 DATA"((NON)ON)ON"
470 DATA"NO(NON)ON"
480 DATA"(NON)O(NON)"
485 DATA"NO((NON)ON)"
490 DATA"(NONON)ON"
495 DATA"(NO(NON))ON"
500 DATA"NO(NONON)"
600 REMGET BASIC TO EVALUATE OUR EXPRESSION
605 A$ = "R=" + F$: GOSUB 1440
610 FOR I = 1 TO LEN (A$)
615 REMSIMPLE TOKEN TRANSLATION
620 B = ASC ( MID$ (A$,I,1))
625 IF (B > 41 AND B < 48) OR B = 61 OR B = 94 THEN B = T(B)
630 POKE (AD + I - 1),B
635 NEXT
640 GOSUB 2000
645 REM GOSUB 1440:REM UNCOMMENT TO CLEAR EVALUATION LINE AFTER USE
650 RETURN
1200 M$ = CHR$ (13)
1210 G$ = CHR$ (7)
1220 HOME
1230 PRINT SPC( 16)"24 GAME"
1240 PRINT M$" THE GOAL OF THIS GAME IS TO FORMULATE"
1250 PRINT M$" AN ARITHMETIC EXPRESSION THAT"
1260 PRINT M$" EVALUATES TO A VALUE OF 24, HOWEVER"
1270 PRINT M$" YOU MAY USE ONLY THE FOUR NUMBERS"
1280 PRINT M$" GIVEN AT RANDOM BY THE COMPUTER AND"
1290 PRINT M$" THE STANDARD ARITHMETIC OPERATIONS OF"
1300 PRINT M$" ADD, SUBTRACT, MULTIPLY, AND DIVIDE."
1310 PRINT M$" EACH DIGIT MUST BE USED BY ITSELF. "
1320 PRINT M$" (E.G. IF GIVEN 1, 2, 3, 4, YOU CANNOT"
1330 PRINT M$" COMBINE 1 AND 2 TO MAKE 12.)"
1340 PRINT M$
1350 PRINT "INITIALIZING...";
1360 HTAB 1
1400 DIM T(94)
1401 T( ASC ("+")) = 200: REM $C8
1402 T( ASC ("-")) = 201: REM $C9
1403 T( ASC ("*")) = 202: REM $CA
1404 T( ASC ("/")) = 203: REM $CB
1405 T( ASC ("=")) = 208: REM $D0
1406 T( ASC ("^")) = 204: REM $CC
1409 REMLOCATE LINE 2005 IN RAM
1410 LH = BH:LL = BL:NH = 0:NL = 0
1415 AD = LH * 256 + LL
1420 LH = PEEK (AD + 1):LL = PEEK (AD)
1425 NL = PEEK (AD + 2):NH = PEEK (AD + 3):N = NH * 256 + NL
1430 IF N < > 2005 THEN GOTO 1415
1435 AD = AD + 4: RETURN
1440 FOR J = AD TO AD + 12: POKE J, ASC (":"): NEXT
1445 RETURN
2000 REMPUT 13 COLONS ON THE NEXT LINE
2005 :::::::::::::
2010 RETURN
|
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.
The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.
The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.
Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row
n
{\displaystyle n}
corresponds to integer
n
{\displaystyle n}
, and each column
C
{\displaystyle C}
in row
m
{\displaystyle m}
from left to right corresponds to the number of names beginning with
C
{\displaystyle C}
.
A function
G
(
n
)
{\displaystyle G(n)}
should return the sum of the
n
{\displaystyle n}
-th row.
Demonstrate this function by displaying:
G
(
23
)
{\displaystyle G(23)}
,
G
(
123
)
{\displaystyle G(123)}
,
G
(
1234
)
{\displaystyle G(1234)}
, and
G
(
12345
)
{\displaystyle G(12345)}
.
Optionally note that the sum of the
n
{\displaystyle n}
-th row
P
(
n
)
{\displaystyle P(n)}
is the integer partition function.
Demonstrate this is equivalent to
G
(
n
)
{\displaystyle G(n)}
by displaying:
P
(
23
)
{\displaystyle P(23)}
,
P
(
123
)
{\displaystyle P(123)}
,
P
(
1234
)
{\displaystyle P(1234)}
, and
P
(
12345
)
{\displaystyle P(12345)}
.
Extra credit
If your environment is able, plot
P
(
n
)
{\displaystyle P(n)}
against
n
{\displaystyle n}
for
n
=
1
…
999
{\displaystyle n=1\ldots 999}
.
Related tasks
Partition function P
| #Ol | Ol |
(define (nine-billion-names row column)
(cond
((<= row 0) 0)
((<= column 0) 0)
((< row column) 0)
((= row 1) 1)
(else
(let ((addend (nine-billion-names (- row 1) (- column 1)))
(augend (nine-billion-names (- row column) column)))
(+ addend augend)))))
(define (print-row row)
(for-each (lambda (x)
(display (nine-billion-names row x))
(display " "))
(iota row 1)))
(define (print-triangle rows)
(for-each (lambda (x)
(print-row x)
(print))
(iota rows 1)))
(print-triangle 25)
|
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
staload UN = $UNSAFE
//
(* ****** ****** *)
staload "libc/SATS/stdio.sats"
(* ****** ****** *)
implement
main0() = let
var A: int
var B: int
val () =
$extfcall
(void, "scanf", "%d%d", addr@A, addr@B)
// end of [val]
in
println! ($UN.cast2int(A) + $UN.cast2int(B))
end // end of [main0]
(* ****** ****** *)
|
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.
| #SETL | SETL | program ackermann;
(for m in [0..3])
print(+/ [rpad('' + ack(m, n), 4): n in [0..6]]);
end;
proc ack(m, n);
return {[0,n+1]}(m) ? ack(m-1, {[0,1]}(n) ? ack(m, n-1));
end proc;
end program; |
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim lines = IO.File.ReadAllLines("days_of_week.txt")
Dim i = 0
For Each line In lines
i += 1
If line.Length > 0 Then
Dim days = line.Split()
If days.Length <> 7 Then
Throw New Exception("There aren't 7 days in line " + i)
End If
Dim temp As New Dictionary(Of String, Integer)
For Each d In days
If temp.ContainsKey(d) Then
Console.WriteLine(" ∞ {0}", line)
Continue For
End If
temp.Add(d, 1)
Next
Dim len = 1
Do
temp.Clear()
For Each d In days
Dim key As String
If len < d.Length Then
key = d.Substring(0, len)
Else
key = d
End If
If temp.ContainsKey(key) Then
Exit For
End If
temp.Add(key, 1)
Next
If temp.Count = 7 Then
Console.WriteLine("{0,2:D} {1}", len, line)
Exit Do
End If
len += 1
Loop
End If
Next
End Sub
End Module |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
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
| #CLU | CLU | ucase = proc (s: string) returns (string)
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
if c>='a' & c<='z' then
c := char$i2c(char$c2i(c) - 32)
end
array[char]$addh(rslt,c)
end
return(string$ac2s(rslt))
end ucase
abc = proc (s: string) returns (bool)
own collection: sequence[string] := sequence[string]$
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
blocks: array[string] := sequence[string]$s2a(collection)
for c: char in string$chars(ucase(s)) do
begin
for i: int in array[string]$indexes(blocks) do
if string$indexc(c, blocks[i]) ~= 0 then
blocks[i] := ""
exit found
end
end
return(false)
end
except when found: end
end
return(true)
end abc
start_up = proc ()
po: stream := stream$primary_output()
words: sequence[string] := sequence[string]$
["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]
for word: string in sequence[string]$elements(words) do
stream$puts(po, word || ": ")
if abc(word) then stream$putl(po, "yes")
else stream$putl(po, "no")
end
end
end start_up |
Subsets and Splits