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,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Yabasic | Yabasic | c$ = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3"
c$ = c$ + " compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate"
c$ = c$ + " 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2"
c$ = c$ + " forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load"
c$ = c$ + " locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2"
c$ = c$ + " msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3"
c$ = c$ + " refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left"
c$ = c$ + " 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"
c$ = upper$(c$)
dim chunk$(1)
n = token(c$, chunk$())
dim lonc(n)
for i = 1 to n - 1
v = val(chunk$(i + 1))
if v then
lonc(i) = v
chunk$(i + 1) = ""
else
lonc(i) = len(chunk$(i))
end if
next
inp$ = "riG rePEAT copies put mo rest types fup. 6 poweRin"
inp$ = upper$(inp$)
dim w$(1)
x = token(inp$, w$())
dim lonw(x)
for i = 1 to x : lonw(i) = len(w$(i)) : next
for j = 1 to x
p$ = ""
for i = 1 to n
lc$ = left$(chunk$(i), lonw(j)) : lw$ = w$(j)
if (lw$ = lc$) and (lonc(i) <= lonw(j)) p$ = chunk$(i) : break
next
if p$ = "" p$ = "*error*"
r$ = r$ + " " + p$
next
print r$ |
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)
| #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn SumOfProperDivisors( n as NSUInteger ) as NSUinteger
NSUinteger sum = 1
cln for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
end fn = sum
NSUinteger n, c
cln for (n = 1, c = 0; c < 25; n += 2 ) if ( n < SumOfProperDivisors( n ) ) NSLog( @"%2lu: %lu", ++c, n );
cln for ( ; c < 1000; n += 2 ) if ( n < SumOfProperDivisors( n ) ) c ++;
NSLog( @"\nThe one thousandth abundant odd number is: %lu\n", n )
cln for ( n = 1000000001 ;; n += 2 ) if ( n < SumOfProperDivisors( n ) ) break;
NSLog( @"The first abundant odd number above one billion is: %lu\n", n )
HandleEvents
|
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# solve the 4 rings or 4 squares puzzle #
# we need to find solutions to the equations: a + b = b + c + d = d + e + f = f + g #
# where a, b, c, d, e, f, g in lo : hi ( not necessarily unique ) #
# depending on show, the solutions will be printed or not #
PROC four rings = ( INT lo, hi, BOOL unique, show )VOID:
BEGIN
INT solutions := 0;
BOOL allow duplicates = NOT unique;
# calculate field width for printinhg solutions #
INT width := -1;
INT max := ABS IF ABS lo > ABS hi THEN lo ELSE hi FI;
WHILE max > 0 DO
width -:= 1;
max OVERAB 10
OD;
# find solutions #
FOR a FROM lo TO hi DO
FOR b FROM lo TO hi DO
IF allow duplicates OR a /= b THEN
INT t = a + b;
FOR c FROM lo TO hi DO
IF allow duplicates OR ( a /= c AND b /= c ) THEN
FOR d FROM lo TO hi DO
IF allow duplicates OR ( a /= d AND b /= d AND c /= d )
THEN
IF b + c + d = t THEN
FOR e FROM lo TO hi DO
IF allow duplicates
OR ( a /= e AND b /= e AND c /= e AND d /= e )
THEN
FOR f FROM lo TO hi DO
IF allow duplicates
OR ( a /= f AND b /= f AND c /= f AND d /= f AND e /= f )
THEN
IF d + e + f = t THEN
FOR g FROM lo TO hi DO
IF allow duplicates
OR ( a /= g AND b /= g AND c /= g AND d /= g AND e /= g AND f /= g )
THEN
IF f + g = t THEN
solutions +:= 1;
IF show THEN
print( ( whole( a, width ), whole( b, width )
, whole( c, width ), whole( d, width )
, whole( e, width ), whole( f, width )
, whole( g, width ), newline
)
)
FI
FI
FI
OD # g #
FI
FI
OD # f #
FI
OD # e #
FI
FI
OD # d #
FI
OD # c #
FI
OD # b #
OD # a # ;
print( ( whole( solutions, 0 )
, IF unique THEN " unique" ELSE " non-unique" FI
, " solutions in "
, whole( lo, 0 )
, " to "
, whole( hi, 0 )
, newline
, newline
)
)
END # four rings # ;
# find the solutions as required for the task #
four rings( 1, 7, TRUE, TRUE );
four rings( 3, 9, TRUE, TRUE );
four rings( 0, 9, FALSE, FALSE )
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
| #D | D | import std.stdio, std.bigint, std.algorithm, std.range;
auto cumu(in uint n) {
__gshared cache = [[1.BigInt]];
foreach (l; cache.length .. n + 1) {
auto r = [0.BigInt];
foreach (x; 1 .. l + 1)
r ~= r.back + cache[l - x][min(x, l - x)];
cache ~= r;
}
return cache[n];
}
auto row(in uint n) {
auto r = n.cumu;
return n.iota.map!(i => r[i + 1] - r[i]);
}
void main() {
writeln("Rows:");
foreach (x; 1 .. 11)
writefln("%2d: %s", x, x.row);
writeln("\nSums:");
foreach (x; [23, 123, 1234])
writeln(x, " ", x.cumu.back);
} |
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
| #Action.21 | Action! | BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
BYTE i
FOR i=1 TO s(0)
DO
IF s(i)=c THEN
err^=0 RETURN (i)
FI
OD
err^=1
RETURN (0)
INT FUNC Decode(CHAR ARRAY s BYTE start,stop BYTE POINTER err)
CHAR ARRAY tmp(20),tmp2(20)
INT value
IF s(start)='+ THEN
start==+1
FI
SCopyS(tmp,s,start,stop)
value=ValI(tmp)
;Check if conversion failed
IF value=0 AND s(start)#'0 THEN
err^=1 RETURN (0)
FI
;Check if value is out of range
IF value<-1000 OR value>1000 THEN
err^=1 RETURN (0)
FI
err^=0
RETURN (value)
PROC Main()
CHAR ARRAY s(20)
BYTE pos,err,err2,value
INT a,b,sum
DO
PrintE("Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit")
InputS(s)
IF s(0)=1 AND (s(1)='Q OR s(1)='q) THEN
EXIT
FI
pos=Find(s,' ,@err)
IF err=0 THEN
a=Decode(s,1,pos-1,@err)
b=Decode(s,pos+1,s(0),@err2)
err=err OR err2
FI
IF err=0 THEN
sum=a+b
PrintF("Their sum is %I%E",sum)
ELSE
PrintE("Invalid input!")
FI
PutE();
OD
RETURN |
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.
| #PARI.2FGP | PARI/GP | package AbstractFoo;
use strict;
sub frob { die "abstract" }
sub baz { die "abstract" }
sub frob_the_baz {
my $self = shift;
$self->frob($self->baz());
}
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.
| #Pascal_and_Object_Pascal | Pascal and Object Pascal | package AbstractFoo;
use strict;
sub frob { die "abstract" }
sub baz { die "abstract" }
sub frob_the_baz {
my $self = shift;
$self->frob($self->baz());
}
1; |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Quackery | Quackery | forward is ackermann ( m n --> r )
[ over 0 = iff
[ nip 1 + ] done
dup 0 = iff
[ drop 1 - 1
ackermann ] done
over 1 - unrot 1 -
ackermann ackermann ] resolves ackermann ( m n --> r )
3 10 ackermann echo |
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
| #Ksh | Ksh |
#!/bin/ksh
# Abbreviations, automatic
# # Variables:
#
dow_file='../dow'
typeset -T Dow_T=(
typeset -a -h "Week day name array" dow
typeset -si -h "minimum length abbreviation" minabv
function init_dow {
_.minabv=$1
_.dow=( $2 )
}
function print_wk {
typeset i ; typeset -si i
printf "(%d) " ${_.minabv}
for((i=0; i<${#_.dow[*]}; i++)); do
printf "%${_.minabv}s " ${_.dow[i]:0:${_.minabv}}
done
printf "\n"
}
)
# # Functions:
#
# # Function _file2arr(fn, arr) - read file fn into arr
#
function _file2arr {
typeset _fn ; _fn="$1"
typeset _arr ; nameref _arr="$2"
typeset _i ; typeset -si _i=0
while read; do
_arr[_i++]="$REPLY"
done < ${_fn}
}
# # Function _minabbr(buff) - return the min length abbr for items in buff
#
function _minabbr {
typeset _buf ; _buf="$1"
typeset _i _flg ; typeset -si _i=0 _cnt
typeset _item _list _abr
until (( _cnt == 7 )); do
unset _list
_cnt=0
(( _i++ ))
for _item in ${_buf}; do
_abr=${_item:0:${_i}}
[[ ${_abr} == @(${_list}) ]] && break
_list+="${_abr}|"
(( _cnt++ ))
done
done
echo ${_i}
}
######
# main #
######
typeset -a dow langs
_file2arr "${dow_file}" dow
for ((i=0; i<${#dow[*]}; i++)); do
(( ! ${#dow[i]} )) && { print "Blank Input, line $((i+1))" ; continue ;}
alen=$(_minabbr "${dow[i]}")
Dow_T langs[i]
langs[i].init_dow ${alen} "${dow[i]}"
(( $((RANDOM%100+1))<=5 )) && { printf "%d. " $((i+1)) ; langs[i].print_wk ;}
done |
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
| #Lua | Lua | function split(line)
local wa = {}
for i in string.gmatch(line, "%S+") do
table.insert(wa, i)
end
return wa
end
-- main
local file = assert(io.open("days_of_week.txt", "r"))
io.input(file)
local line_num = 0
while true do
local line = io.read()
if line == nil then break end
line_num = line_num + 1
if string.len(line) > 0 then
local days = split(line)
if #days ~= 7 then
error("There aren't 7 days in line "..line_num)
end
local temp = {}
for i,day in pairs(days) do
if temp[day] ~= nil then
io.stderr:write(" ∞ "..line.."\n")
else
temp[day] = true
end
end
local length = 1
while length < 50 do
temp = {}
local count = 0
for i,day in pairs(days) do
local key = string.sub(day, 0, length)
if temp[key] ~= nil then break end
temp[key] = true
count = count + 1
end
if count == 7 then
print(string.format("%2d %s", length, line))
break
end
length = length + 1
end
end
end |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program problemABC.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ TRUE, 1
.equ FALSE, 0
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre1: .asciz "Can_make_word: @ \n"
szMessTrue: .asciz "True.\n"
szMessFalse: .asciz "False.\n"
szCarriageReturn: .asciz "\n"
szTablBloc: .asciz "BO"
.asciz "XK"
.asciz "DQ"
.asciz "CP"
.asciz "NA"
.asciz "GT"
.asciz "RE"
.asciz "TG"
.asciz "QD"
.asciz "FS"
.asciz "JW"
.asciz "HU"
.asciz "VI"
.asciz "AN"
.asciz "OB"
.asciz "ER"
.asciz "FS"
.asciz "LY"
.asciz "PC"
.asciz "ZM"
.equ NBBLOC, (. - szTablBloc) / 3
szWord1: .asciz "A"
szWord2: .asciz "BARK"
szWord3: .asciz "BOOK"
szWord4: .asciz "TREAT"
szWord5: .asciz "COMMON"
szWord6: .asciz "SQUAD"
szWord7: .asciz "CONFUSE"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
itabTopBloc: .skip 4 * NBBLOC
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszWord1
bl traitBlock @ control word
ldr r0,iAdrszWord2
bl traitBlock @ control word
ldr r0,iAdrszWord3
bl traitBlock @ control word
ldr r0,iAdrszWord4
bl traitBlock @ control word
ldr r0,iAdrszWord5
bl traitBlock @ control word
ldr r0,iAdrszWord6
bl traitBlock @ control word
ldr r0,iAdrszWord7
bl traitBlock @ control word
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszWord1: .int szWord1
iAdrszWord2: .int szWord2
iAdrszWord3: .int szWord3
iAdrszWord4: .int szWord4
iAdrszWord5: .int szWord5
iAdrszWord6: .int szWord6
iAdrszWord7: .int szWord7
/******************************************************************/
/* traitement */
/******************************************************************/
/* r0 contains word */
traitBlock:
push {r1,lr} @ save registers
mov r1,r0
ldr r0,iAdrszMessTitre1 @ insertion word in message
bl strInsertAtCharInc
bl affichageMess @ display title message
mov r0,r1
bl controlBlock @ control
cmp r0,#TRUE @ ok ?
bne 1f
ldr r0,iAdrszMessTrue @ yes
bl affichageMess
b 100f
1: @ no
ldr r0,iAdrszMessFalse
bl affichageMess
100:
pop {r1,lr}
bx lr @ return
iAdrszMessTitre1: .int szMessTitre1
iAdrszMessFalse: .int szMessFalse
iAdrszMessTrue: .int szMessTrue
/******************************************************************/
/* control if letters are in block */
/******************************************************************/
/* r0 contains word */
controlBlock:
push {r1-r9,lr} @ save registers
mov r5,r0 @ save word address
ldr r4,iAdritabTopBloc
ldr r6,iAdrszTablBloc
mov r2,#0
mov r3,#0
1: @ init table top block used
str r3,[r4,r2,lsl #2]
add r2,r2,#1
cmp r2,#NBBLOC
blt 1b
mov r2,#0
2: @ loop to load letters
ldrb r3,[r5,r2]
cmp r3,#0
beq 10f @ end
and r3,r3,#0xDF @ transform in capital letter
mov r8,#0
3: @ begin loop control block
ldr r7,[r4,r8,lsl #2] @ block already used ?
cmp r7,#0
bne 5f @ yes
add r9,r8,r8,lsl #1 @ no -> index * 3
ldrb r7,[r6,r9] @ first block letter
cmp r3,r7 @ equal ?
beq 4f
add r9,r9,#1
ldrb r7,[r6,r9] @ second block letter
cmp r3,r7 @ equal ?
beq 4f
b 5f
4:
mov r7,#1 @ top block
str r7,[r4,r8,lsl #2] @ block used
add r2,r2,#1
b 2b @ next letter
5:
add r8,r8,#1
cmp r8,#NBBLOC
blt 3b
mov r0,#FALSE @ no letter find on block -> false
b 100f
10: @ all letters are ok
mov r0,#TRUE
100:
pop {r1-r9,lr}
bx lr @ return
iAdritabTopBloc: .int itabTopBloc
iAdrszTablBloc: .int szTablBloc
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Abbreviations,_simple | Abbreviations, simple | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
For this task, the following command table will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above command table:
it can be thought of as one long literal string (with blanks at end-of-lines)
it may have superfluous blanks
it may be in any case (lower/upper/mixed)
the order of the words in the command table must be preserved as shown
the user input(s) may be in any case (upper/lower/mixed)
commands will be restricted to the Latin alphabet (A ──► Z, a ──► z)
a command is followed by an optional number, which indicates the minimum abbreviation
A valid abbreviation is a word that has:
at least the minimum length of the word's minimum number in the command table
compares equal (regardless of case) to the leading characters of the word in the command table
a length not longer than the word in the command table
ALT, aLt, ALTE, and ALTER are all abbreviations of ALTER 3
AL, ALF, ALTERS, TER, and A aren't valid abbreviations of ALTER 3
The 3 indicates that any abbreviation for ALTER must be at least three characters
Any word longer than five characters can't be an abbreviation for ALTER
o, ov, oVe, over, overL, overla are all acceptable abbreviations for overlay 1
if there isn't a number after the command, then there isn't an abbreviation permitted
Task
The command table needn't be verified/validated.
Write a function to validate if the user "words" (given as input) are valid (in the command table).
If the word is valid, then return the full uppercase version of that "word".
If the word isn't valid, then return the lowercase string: *error* (7 characters).
A blank input (or a null input) should return a null string.
Show all output here.
An example test case to be used for this task
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #zkl | zkl | commands:=Data(0,String, // "add\01\0alter\0..."
#<<<
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"
.toUpper().split());
#<<<
var szs=Dictionary(); // [<index>:<length> ...]
n:=0; while(n<commands.len()){
cmd,nc := commands.readString(n), n + cmd.len() + 1;
len:=commands.readString(nc);
if(len.matches("[0-9]*")){ szs[n]=len.toInt(); n=nc+len.len()+1 }
else { szs[n]=cmd.len(); n=nc; }
}
testText:="riG rePEAT copies put mo rest types "
" fup. 6 poweRin";
testText.split().apply('wrap(w){
w=w.toUpper(); n:=0;
while(True){ // check for length requirement and, if there, verify
n=commands.find(w,n);
if(Void==n) return("*error*"); // end of loop if no match
c:=commands.readString(n);
if(w.len()>=szs.find(n,99999)) return(c);
n+=c.len();
}
}).concat(" ").println(); |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).
Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.
To make things more interesting, this task is specifically about finding odd abundant numbers.
Task
Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
References
OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| #Go | Go | package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
} |
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
| #AppleScript | AppleScript | use framework "Foundation" -- for basic NSArray sort
on run
unlines({"rings(true, enumFromTo(1, 7))\n", ¬
map(show, (rings(true, enumFromTo(1, 7)))), ¬
"\nrings(true, enumFromTo(3, 9))\n", ¬
map(show, (rings(true, enumFromTo(3, 9)))), ¬
"\nlength(rings(false, enumFromTo(0, 9)))\n", ¬
show(|length|(rings(false, enumFromTo(0, 9))))})
end run
-- RINGS -----------------------------------------------------------------------
-- rings :: noRepeatedDigits -> DigitList -> Lists of solutions
-- rings :: Bool -> [Int] -> [[Int]]
on rings(u, digits)
set ds to reverse_(sort(digits))
set h to head(ds)
-- QUEEN -------------------------------------------------------------------
script queen
on |λ|(q)
script
on |λ|(x)
x + q ≤ h
end |λ|
end script
set ts to filter(result, ds)
if u then
set bs to delete_(q, ts)
else
set bs to ds
end if
-- LEFT BISHOP and its ROOK-----------------------------------------
script leftBishop
on |λ|(lb)
set lRook to lb + q
if lRook > h then
{}
else
if u then
set rbs to difference(ts, {q, lb, lRook})
else
set rbs to ds
end if
-- RIGHT BISHOP and its ROOK ---------------------------
script rightBishop
on |λ|(rb)
set rRook to rb + q
if (rRook > h) or (u and (rRook = lb)) then
{}
else
set rookDelta to lRook - rRook
if u then
set ks to difference(ds, ¬
{q, lb, rb, rRook, lRook})
else
set ks to ds
end if
-- KNIGHTS LEFT AND RIGHT ------------------
script knights
on |λ|(k)
set k2 to k + rookDelta
if elem(k2, ks) and ((not u) or ¬
notElem(k2, ¬
{lRook, k, lb, q, rb, rRook})) then
{{lRook, k, lb, q, rb, k2, rRook}}
else
{}
end if
end |λ|
end script
concatMap(knights, ks)
end if
end |λ|
end script
concatMap(rightBishop, rbs)
end if
end |λ|
end script
concatMap(leftBishop, bs)
end |λ|
end script
concatMap(queen, ds)
end rings
-- GENERIC FUNCTIONS -----------------------------------------------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lst to {}
set lng to length of xs
tell mReturn(f)
repeat with i from 1 to lng
set lst to (lst & |λ|(contents of item i of xs, i, xs))
end repeat
end tell
return lst
end concatMap
-- delete :: Eq a => a -> [a] -> [a]
on delete_(x, xs)
set mbIndex to elemIndex(x, xs)
set lng to length of xs
if mbIndex is not missing value then
if lng > 1 then
if mbIndex = 1 then
items 2 thru -1 of xs
else if mbIndex = lng then
items 1 thru -2 of xs
else
tell xs to items 1 thru (mbIndex - 1) & ¬
items (mbIndex + 1) thru -1
end if
else
{}
end if
else
xs
end if
end delete_
-- difference :: [a] -> [a] -> [a]
on difference(xs, ys)
script mf
on except(a, y)
if a contains y then
my delete_(y, a)
else
a
end if
end except
end script
foldl(except of mf, xs, ys)
end difference
-- elem :: Eq a => a -> [a] -> Bool
on elem(x, xs)
xs contains x
end elem
-- elemIndex :: a -> [a] -> Maybe Int
on elemIndex(x, xs)
set lng to length of xs
repeat with i from 1 to lng
if x = (item i of xs) then return i
end repeat
return missing value
end elemIndex
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- head :: [a] -> a
on head(xs)
if length of xs > 0 then
item 1 of xs
else
missing value
end if
end head
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- notElem :: Eq a => a -> [a] -> Bool
on notElem(x, xs)
xs does not contain x
end notElem
-- reverse_ :: [a] -> [a]
on |reverse|:xs
if class of xs is text then
(reverse of characters of xs) as text
else
reverse of xs
end if
end |reverse|:
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
script serialized
on |λ|(v)
show(v)
end |λ|
end script
"[" & intercalate(", ", map(serialized, e)) & "]"
else if c = record then
script showField
on |λ|(kv)
set {k, ev} to kv
"\"" & k & "\":" & show(ev)
end |λ|
end script
"{" & intercalate(", ", ¬
map(showField, zip(allKeys(e), allValues(e)))) & "}"
else if c = date then
"\"" & iso8601Z(e) & "\""
else if c = text then
"\"" & e & "\""
else if (c = integer or c = real) then
e as text
else if c = class then
"null"
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- sort :: [a] -> [a]
on sort(xs)
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
end sort
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines |
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
| #Dart | Dart | import 'dart:math';
List<BigInt> partitions(int n) {
var cache = List<List<BigInt>>.filled(1, List<BigInt>.filled(1, BigInt.from(1)), growable: true);
for(int length = cache.length; length < n + 1; length++) {
var row = List<BigInt>.filled(1, BigInt.from(0), growable: true);
for(int index = 1; index < length + 1; index++) {
var partAtIndex = row[row.length - 1] + cache[length - index][min(index, length - index)];
row.add(partAtIndex);
}
cache.add(row);
}
return cache[n];
}
List<BigInt> row(int n) {
var parts = partitions(n);
return List<BigInt>.generate(n, (int index) => parts[index + 1] - parts[index]);
}
void printRows({int min = 1, int max = 11}) {
int maxDigits = max.toString().length;
print('Rows:');
for(int i in List.generate(max - min, (int index) => index + min)) {
print((' ' * (maxDigits - i.toString().length)) + '$i: ${row(i)}');
}
}
void printSums(List<int> args) {
print('Sums:');
for(int i in args) {
print('$i: ${partitions(i)[i]}');
}
} |
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
| #Dyalect | Dyalect | var cache = [[1]]
func namesOfGod(n) {
for l in cache.Length()..n {
var r = [0]
if l == 1 {
r.Add(r[r.Length() - 1] + cache[0][0])
} else {
for x in 1..l {
r.Add(r[r.Length() - 1] + cache[l - x][min(x, l-x)])
}
}
cache.Add(r)
}
return cache[n]
}
func row(n) {
let r = namesOfGod(n)
var xs = []
for i in 0..<n {
xs.Add(r[i + 1] - r[i])
}
return xs
}
for x in 1..25 {
print("\(x): \(row(x))")
} |
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
| #Ada | Ada | -- Standard I/O Streams
with Ada.Integer_Text_Io;
procedure APlusB is
A, B : Integer;
begin
Ada.Integer_Text_Io.Get (Item => A);
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB; |
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.
| #Perl | Perl | package AbstractFoo;
use strict;
sub frob { die "abstract" }
sub baz { die "abstract" }
sub frob_the_baz {
my $self = shift;
$self->frob($self->baz());
}
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.
| #Phix | Phix | abstract class job
integer id
-- procedure test(); -- (the ; makes it an abstract method)
procedure show()
printf(1,"this is job:%d\n",id)
end procedure
end class
--job j = new({1}) -- compilation error: "abstract class"
class errand extends job
end class
errand e = new({2})
e.show()
|
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.
| #R | R | ackermann <- function(m, n) {
if ( m == 0 ) {
n+1
} else if ( n == 0 ) {
ackermann(m-1, 1)
} else {
ackermann(m-1, ackermann(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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
(*This function gives all 'heads' of str of length 1 to maxLength. Since the input data was formatted to use underscores in place of spaces, there is an edge case where distinct abbreviations derived from the input data would actually not be distinct in the 'real' abbreviations. See further comments below regarding the difference between my output and the output of other solutions.*)
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
(*Given a list of words (weekday names), this function expands each to its abbreviations and then picks the first 'column' that contains no duplicates. The failure case isn't really needed for this specific data, but I included it for completeness.*)
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
(*This function gives the minimum number of characters to distinguish the words (weekday names). It assumes data is a space separated list of weekday names (i.e. one line of the input data). I would prefer to ignore blank lines, but the spec says to return an empty string. Since all of the abbreviations should be the same length because of the padding done by Abbreviations, I could have just selected the first item rather than taking the Max of the StringLength. However, the implmenetation of Abbreviations was very specific to the format of the input data, and so using Max seemed a bit safer and more general.*)
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
|
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
| #Nim | Nim |
import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
# Extract the day names and store them in a sorted list of sequences of runes.
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
# Build the abbreviations and store them in a set.
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
# All abbreviations are different: fine!
break
inc index
echo index + 1, " ", line
else:
echo line
|
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
| #Arturo | Arturo | blocks: map [
[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]
] => [ join map & => [to :string]]
charInBlock: function [ch,bl][
loop.with:'i bl 'b ->
if contains? b upper ch [
return i
]
return ø
]
canMakeWord?: function [wrd][
ref: new blocks
loop split wrd 'chr [
cib: charInBlock chr ref
if? cib = ø [ return false ]
else [ ref: remove ref .index cib ]
]
return true
]
loop ["A" "BaRk" "bOoK" "tReAt" "CoMmOn" "SqUaD" "cONfUsE"] 'wrd
-> print [wrd "=>" canMakeWord? wrd] |
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)
| #Groovy | Groovy | class Abundant {
static List<Integer> divisors(int n) {
List<Integer> divs = new ArrayList<>()
divs.add(1)
List<Integer> divs2 = new ArrayList<>()
int i = 2
while (i * i < n) {
if (n % i == 0) {
int j = (int) (n / i)
divs.add(i)
if (i != j) {
divs2.add(j)
}
}
i++
}
Collections.reverse(divs2)
divs.addAll(divs2)
return divs
}
static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) {
int count = countFrom
int n = searchFrom
while (count < countTo) {
List<Integer> divs = divisors(n)
int tot = divs.stream().reduce(Integer.&sum).orElse(0)
if (tot > n) {
count++
if (!printOne || count >= countTo) {
String s = divs.stream()
.map(Integer.&toString)
.reduce { a, b -> a + " + " + b }
.orElse("")
if (printOne) {
System.out.printf("%d < %s = %d\n", n, s, tot)
} else {
System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot)
}
}
}
n += 2
}
return n
}
static void main(String[] args) {
int max = 25
System.out.printf("The first %d abundant odd numbers are:\n", max)
int n = abundantOdd(1, 0, 25, false)
System.out.println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
System.out.println("\nThe first abundant odd number above one billion is:")
abundantOdd((int) (1e9 + 1), 0, 1, true)
}
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program square4.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBBOX, 7
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessDeb: .ascii "a="
sMessValeur_a: .fill 11, 1, ' ' @ size => 11
.ascii "b="
sMessValeur_b: .fill 11, 1, ' ' @ size => 11
.ascii "c="
sMessValeur_c: .fill 11, 1, ' ' @ size => 11
.ascii "d="
sMessValeur_d: .fill 11, 1, ' ' @ size => 11
.ascii "\n"
.ascii "e="
sMessValeur_e: .fill 11, 1, ' ' @ size => 11
.ascii "f="
sMessValeur_f: .fill 11, 1, ' ' @ size => 11
.ascii "g="
sMessValeur_g: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n************************\n"
sMessNbSolution: .ascii "Number of solutions :"
sMessCounter: .fill 11, 1, ' ' @ size => 11
.asciz "\n\n\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
iValues_a: .skip 4 * NBBOX
iValues_b: .skip 4 * NBBOX - 1
iValues_c: .skip 4 * NBBOX - 2
iValues_d: .skip 4 * NBBOX - 3
iValues_e: .skip 4 * NBBOX - 4
iValues_f: .skip 4 * NBBOX - 5
iValues_g: .skip 4 * NBBOX - 6
iCounterSol: .skip 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r0,#1
mov r1,#7
mov r2,#3 @ 0 = rien 1 = display 2 = count 3 = les deux
bl searchPb
mov r0,#3
mov r1,#9
mov r2,#3 @ 0 = rien 1 = display 2 = count 3 = les deux
bl searchPb
mov r0,#0
mov r1,#9
mov r2,#2 @ 0 = rien 1 = display 2 = count 3 = les deux
bl prepSearchNU
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* search problèm value not unique */
/******************************************************************/
/* r0 contains start digit */
/* r1 contains end digit */
/* r2 contains action (0 display 1 count) */
prepSearchNU:
push {r3-r12,lr} @ save registers
mov r5,#0 @ counter
mov r12,r0 @ a
1:
mov r11,r0 @ b
2:
mov r10,r0 @ c
3:
mov r9,r0 @ d
4:
add r4,r12,r11 @ a + b reference
add r3,r11,r10
add r3,r9 @ b + c + d
cmp r4,r3
bne 10f
mov r8,r0 @ e
5:
mov r7,r0 @ f
6:
add r3,r9,r8
add r3,r7 @ d + e + f
cmp r3,r4
bne 9f
mov r6,r0 @ g
7:
add r3,r7,r6 @ f + g
cmp r3,r4
bne 8f @ not OK
@ OK
add r5,#1 @ increment counter
8:
add r6,#1 @ increment g
cmp r6,r1
ble 7b
9:
add r7,#1 @ increment f
cmp r7,r1
ble 6b
add r8,#1 @ increment e
cmp r8,r1
ble 5b
10:
add r9,#1 @ increment d
cmp r9,r1
ble 4b
add r10,#1 @ increment c
cmp r10,r1
ble 3b
add r11,#1 @ increment b
cmp r11,r1
ble 2b
add r12,#1 @ increment a
cmp r12,r1
ble 1b
@ end
tst r2,#0b10 @ print count ?
beq 100f
mov r0,r5 @ counter
ldr r1,iAdrsMessCounter
bl conversion10
ldr r0,iAdrsMessNbSolution
bl affichageMess
100:
pop {r3-r12,lr} @ restaur registers
bx lr @return
iAdrsMessCounter: .int sMessCounter
iAdrsMessNbSolution: .int sMessNbSolution
/******************************************************************/
/* search problem unique solution */
/******************************************************************/
/* r0 contains start digit */
/* r1 contains end digit */
/* r2 contains action (0 display 1 count) */
searchPb:
push {r0-r12,lr} @ save registers
@ init
ldr r3,iAdriValues_a @ area value a
mov r4,#0
1: @ loop init value a
str r0,[r3,r4,lsl #2]
add r4,#1
add r0,#1
cmp r0,r1
ble 1b
mov r5,#0 @ solution counter
mov r12,#-1
2:
add r12,#1 @ increment indice a
cmp r12,#NBBOX-1
bgt 90f
ldr r0,iAdriValues_a @ area value a
ldr r1,iAdriValues_b @ area value b
mov r2,r12 @ indice a
mov r3,#NBBOX @ number of origin values
bl prepValues
mov r11,#-1
3:
add r11,#1 @ increment indice b
cmp r11,#NBBOX - 2
bgt 2b
ldr r0,iAdriValues_b @ area value b
ldr r1,iAdriValues_c @ area value c
mov r2,r11 @ indice b
mov r3,#NBBOX -1 @ number of origin values
bl prepValues
mov r10,#-1
4:
add r10,#1
cmp r10,#NBBOX - 3
bgt 3b
ldr r0,iAdriValues_c
ldr r1,iAdriValues_d
mov r2,r10
mov r3,#NBBOX - 2
bl prepValues
mov r9,#-1
5:
add r9,#1
cmp r9,#NBBOX - 4
bgt 4b
@ control 2 firsts squares
ldr r0,iAdriValues_a
ldr r0,[r0,r12,lsl #2]
ldr r1,iAdriValues_b
ldr r1,[r1,r11,lsl #2]
add r4,r0,r1 @ a + b value first square
ldr r0,iAdriValues_c
ldr r0,[r0,r10,lsl #2]
add r7,r1,r0 @ b + c
ldr r1,iAdriValues_d
ldr r1,[r1,r9,lsl #2]
add r7,r1 @ b + c + d
cmp r7,r4 @ equal first square ?
bne 5b
ldr r0,iAdriValues_d
ldr r1,iAdriValues_e
mov r2,r9
mov r3,#NBBOX - 3
bl prepValues
mov r8,#-1
6:
add r8,#1
cmp r8,#NBBOX - 5
bgt 5b
ldr r0,iAdriValues_e
ldr r1,iAdriValues_f
mov r2,r8
mov r3,#NBBOX - 4
bl prepValues
mov r7,#-1
7:
add r7,#1
cmp r7,#NBBOX - 6
bgt 6b
ldr r0,iAdriValues_d
ldr r0,[r0,r9,lsl #2]
ldr r1,iAdriValues_e
ldr r1,[r1,r8,lsl #2]
add r3,r0,r1 @ d + e
ldr r1,iAdriValues_f
ldr r1,[r1,r7,lsl #2]
add r3,r1 @ de + e + f
cmp r3,r4 @ equal first square ?
bne 7b
ldr r0,iAdriValues_f
ldr r1,iAdriValues_g
mov r2,r7
mov r3,#NBBOX - 5
bl prepValues
mov r6,#-1
8:
add r6,#1
cmp r6,#NBBOX - 7
bgt 7b
ldr r0,iAdriValues_f
ldr r0,[r0,r7,lsl #2]
ldr r1,iAdriValues_g
ldr r1,[r1,r6,lsl #2]
add r3,r0,r1 @ f +g
cmp r4,r3 @ equal first square ?
bne 8b
add r5,#1 @ increment counter
ldr r0,[sp,#8] @ load action for two parameter in stack
tst r0,#0b1
beq 9f @ display solution ?
ldr r0,iAdriValues_a
ldr r0,[r0,r12,lsl #2]
ldr r1,iAdrsMessValeur_a
bl conversion10
ldr r0,iAdriValues_b
ldr r0,[r0,r11,lsl #2]
ldr r1,iAdrsMessValeur_b
bl conversion10
ldr r0,iAdriValues_c
ldr r0,[r0,r10,lsl #2]
ldr r1,iAdrsMessValeur_c
bl conversion10
ldr r0,iAdriValues_d
ldr r0,[r0,r9,lsl #2]
ldr r1,iAdrsMessValeur_d
bl conversion10
ldr r0,iAdriValues_e
ldr r0,[r0,r8,lsl #2]
ldr r1,iAdrsMessValeur_e
bl conversion10
ldr r0,iAdriValues_f
ldr r0,[r0,r7,lsl #2]
ldr r1,iAdrsMessValeur_f
bl conversion10
ldr r0,iAdriValues_g
ldr r0,[r0,r6,lsl #2]
ldr r1,iAdrsMessValeur_g
bl conversion10
ldr r0,iAdrsMessDeb
bl affichageMess
9:
b 8b @ suite
90:
ldr r0,[sp,#8] @ load action for two parameter in stack
tst r0,#0b10
beq 100f @ display counter ?
mov r0,r5
ldr r1,iAdrsMessCounter
bl conversion10
ldr r0,iAdrsMessNbSolution
bl affichageMess
100:
pop {r0-r12,lr} @ restaur registers
bx lr @return
iAdriValues_a: .int iValues_a
iAdriValues_b: .int iValues_b
iAdriValues_c: .int iValues_c
iAdriValues_d: .int iValues_d
iAdriValues_e: .int iValues_e
iAdriValues_f: .int iValues_f
iAdriValues_g: .int iValues_g
iAdrsMessValeur_a: .int sMessValeur_a
iAdrsMessValeur_b: .int sMessValeur_b
iAdrsMessValeur_c: .int sMessValeur_c
iAdrsMessValeur_d: .int sMessValeur_d
iAdrsMessValeur_e: .int sMessValeur_e
iAdrsMessValeur_f: .int sMessValeur_f
iAdrsMessValeur_g: .int sMessValeur_g
iAdrsMessDeb: .int sMessDeb
iAdriCounterSol: .int iCounterSol
/******************************************************************/
/* copy value area and substract value of indice */
/******************************************************************/
/* r0 contains the address of values origin */
/* r1 contains the address of values destination */
/* r2 contains value indice to substract */
/* r3 contains origin values number */
prepValues:
push {r1-r6,lr} @ save registres
mov r4,#0 @ indice origin value
mov r5,#0 @ indice destination value
1:
cmp r4,r2 @ substract indice ?
beq 2f @ yes -> jump
ldr r6,[r0,r4,lsl #2] @ no -> copy value
str r6,[r1,r5,lsl #2]
add r5,#1 @ increment destination indice
2:
add r4,#1 @ increment origin indice
cmp r4,r3 @ end ?
blt 1b
100:
pop {r1-r6,lr} @ restaur registres
bx lr @return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
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
| #Elixir | Elixir | defmodule God do
def g(n,g) when g == 1 or n < g, do: 1
def g(n,g) do
Enum.reduce(2..g, 1, fn q,res ->
res + (if q > n-g, do: 0, else: g(n-g,q))
end)
end
end
Enum.each(1..25, fn n ->
IO.puts Enum.map(1..n, fn g -> "#{God.g(n,g)} " end)
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
| #Erlang | Erlang |
-module(triangle).
-export([start/1]).
start(N)->
print(1,1,N).
print(N,N,N)->
1;
print(A,B,N) when A>=B->
io:format("~p ",[formula(A,B)]),
print(A,B+1,N);
print(A,B,N) when B>A->
io:format("~n"),
print(A+1,1,N).
formula(_,0)->
0;
formula(B,B)->
1;
formula(A,B) when B>A->
0;
formula(A1,B1)->
formula(A1-1,B1-1)+formula(A1-B1,B1).
|
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
| #Agena | Agena | scope
local f := trim( io.read() ) split " "; # read a line and split into fields
local a := tonumber( f[ 1 ] );
local b := tonumber( f[ 2 ] );
print( a + b )
epocs |
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.
| #PHP | PHP | abstract class Abs {
abstract public function method1($value);
abstract protected function method2($name);
function add($a, $b){
return 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.
| #PicoLisp | PicoLisp | # In PicoLisp there is no formal difference between abstract and concrete classes.
# There is just a naming convention where abstract classes start with a
# lower-case character after the '+' (the naming convention for classes).
# This tells the programmer that this class has not enough methods
# defined to survive on its own.
(class +abstractClass)
(dm someMethod> ()
(foo)
(bar) ) |
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.
| #Racket | Racket |
#lang racket
(define (ackermann m n)
(cond [(zero? m) (add1 n)]
[(zero? n) (ackermann (sub1 m) 1)]
[else (ackermann (sub1 m) (ackermann m (sub1 n)))]))
|
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
| #Objeck | Objeck | use System.IO.File;
use Collection;
class Abbreviations {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
Go(args[0]);
};
}
function : Go(file : String) ~ Nil {
reader := FileReader->New(file);
leaving {
reader->Close();
};
cache := StringMap->New();
line := reader->ReadString();
while(line <> Nil) {
if(line->Size() > 0) {
days := line->Split(" ");
cache->Empty();
each(i : days) {
day := days[i];
cache->Insert(day, IntHolder->New(1));
};
if(cache->Size() < 7) {
" ∞ {$line}"->PrintLine();
};
len := 1;
while(true) {
cache->Empty();
each(i : days) {
day := days[i];
sd : String;
if(len >= day->Size()) {
sd := day;
}
else {
sd := day->SubString(len);
};
count := cache->Find(sd)->As(IntHolder);
if(count = Nil) {
cache->Insert(sd, IntHolder->New(1));
}
else {
count->Inc();
};
};
if(cache->Size() = 7) {
"{$len} {$line}"->PrintLine();
break;
};
len += 1;
};
};
line := reader->ReadString();
};
}
} |
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
| #Astro | Astro | fun abc(s, ls):
if ls.isempty:
return true
for i in indices(list) where s[end] in list[i]:
return abc(s[:end-1], remove!(copy(list), at: i))
false
let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
let ls = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
for s in test:
print "($|>8|{s} ${abc(s, list)})" |
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)
| #Haskell | Haskell | import Data.List (nub)
divisorSum :: Integral a => a -> a
divisorSum n =
sum
. map (\i -> sum $ nub [i, n `quot` i])
. filter ((== 0) . (n `rem`))
$ takeWhile ((<= n) . (^ 2)) [1 ..]
oddAbundants :: Integral a => a -> [(a, a)]
oddAbundants n =
[ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ]
printAbundant :: (Int, Int) -> IO ()
printAbundant (n, s) =
putStrLn
$ show n
++ " with "
++ show s
++ " as the sum of all proper divisors."
main :: IO ()
main = do
putStrLn "The first 25 odd abundant numbers are:"
mapM_ printAbundant . take 25 $ oddAbundants 1
putStrLn "The 1000th odd abundant number is:"
printAbundant $ oddAbundants 1 !! 1000
putStrLn "The first odd abundant number above 1000000000 is:"
printAbundant . head . oddAbundants $ 10 ^ 9 |
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
| #AWK | AWK |
# syntax: GAWK -f 4-RINGS_OR_4-SQUARES_PUZZLE.AWK
# converted from C
BEGIN {
cmd = "SORT /+16"
four_squares(1,7,1,1)
four_squares(3,9,1,1)
four_squares(0,9,0,0)
four_squares(0,6,1,0)
four_squares(2,8,1,0)
exit(0)
}
function four_squares(plo,phi,punique,pshow) {
lo = plo
hi = phi
unique = punique
show = pshow
solutions = 0
print("")
if (show) {
print("A B C D E F G sum A+B B+C+D D+E+F F+G")
print("------------- --- -------------------")
}
acd()
close(cmd)
tmp = (unique) ? "unique" : "non-unique"
printf("%d-%d: %d %s solutions\n",lo,hi,solutions,tmp)
}
function acd() {
for (c=lo; c<=hi; c++) {
for (d=lo; d<=hi; d++) {
if (!unique || c != d) {
a = c + d
if (a >= lo && a <= hi && (!unique || (c != 0 && d != 0))) {
ge()
}
}
}
}
}
function bf() {
for (f=lo; f<=hi; f++) {
if (!unique || (f != a && f != c && f != d && f != g && f != e)) {
b = e + f - c
if (b >= lo && b <= hi && (!unique || (b != a && b != c && b != d && b != g && b != e && b != f))) {
solutions++
if (show) {
printf("%d %d %d %d %d %d %d %4d ",a,b,c,d,e,f,g,a+b) | cmd
printf("%d+%d ",a,b) | cmd
printf("%d+%d+%d ",b,c,d) | cmd
printf("%d+%d+%d ",d,e,f) | cmd
printf("%d+%d\n",f,g) | cmd
}
}
}
}
}
function ge() {
for (e=lo; e<=hi; e++) {
if (!unique || (e != a && e != c && e != d)) {
g = d + e
if (g >= lo && g <= hi && (!unique || (g != a && g != c && g != d && g != e))) {
bf()
}
}
}
}
|
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
| #Factor | Factor | USING: combinators io kernel math math.ranges memoize prettyprint
sequences ;
MEMO: p ( m n -- o )
{
{ [ dup zero? ] [ nip ] }
{ [ 2dup = ] [ 2drop 1 ] }
{ [ 2dup < ] [ 2drop 0 ] }
[ [ [ 1 - ] bi@ p ] [ [ - ] [ ] bi p + ] 2bi ]
} cond ;
: row ( n -- seq ) dup [1,b] [ p ] with map ;
: .row ( n -- ) row [ pprint bl ] each nl ;
: .triangle ( n -- ) [1,b] [ .row ] each ;
: G ( n -- sum ) row sum ;
25 .triangle nl
"Sums:" print { 23 123 1234 12345 } [ dup pprint bl G . ] each |
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
| #Forth | Forth | NEEDS -xopg
ANEW -nbnog \ The Nine Billion Names of God
.arbitrary.p
#100000 =: N
CREATE idx[ #23 , #123 , #1234 , #12345 , #20000 , #30000 , #40000 , #50000 , N , 0 ,
N GARRAY p
: CALC ( n -- )
0 LOCALS| d n |
n 1+ 1 ?DO I 3 * 1- I 2 */ n SWAP - TO d d 0< ?LEAVE
I 1 AND IF LET p[n]=p[n]+p[d]: ELSE LET p[n]=p[n]-p[d]: ENDIF
I -TO d d 0< ?LEAVE
I 1 AND IF LET p[n]=p[n]+p[d]: ELSE LET p[n]=p[n]-p[d]: ENDIF
LOOP ;
: .GOD ( -- )
0 LOCAL at
LET p[0]=1: N 1 DO I CALC
idx[ at CELL[] @ I = IF CR I 5 .R ." : " LET. p[I]:
1 +TO at
ENDIF
LOOP ;
: .ABOUT ( -- ) ." Try: .GOD" ;
|
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
| #Aime | Aime | file f;
list l;
f_affix(f, "/dev/stdin");
f_list(f, l, 0);
o_integer(atoi(l[0]) + atoi(l[1]));
o_newline(); |
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.
| #PowerShell | PowerShell |
#Requires -Version 5.0
Class Player
{
<#
Properties: Name, Team, Position and Number
#>
[string]$Name
[ValidateSet("Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
"Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
"Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
"Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
"Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
"Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
"Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
"Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks")]
[string]$Team
[ValidateSet("C","G","T","QB","RB","WR","TE","DT","DE","ILB","OLB","CB","S","K","H","LS","P","KOS","R")]
[string]$Position
[ValidateRange(0,99)]
[int]$Number
<#
Constructor: Creates a new Player object, with the specified Name, Team, Position and Number.
#>
Player([string]$Name, [string]$Team, [string]$Position, [int]$Number)
{
$this.Name = (Get-Culture).TextInfo.ToTitleCase("$Name")
$this.Team = (Get-Culture).TextInfo.ToTitleCase("$Team")
$this.Position = $Position.ToUpper()
$this.Number = $Number
}
<#
Methods: Trade the player to a different team (optional parameters for methods in PowerShell 5 classes are not available. Boo!!)
An overloaded method is a method with the same name as another method but in a different context,
in this case with different parameters.
#>
Trade([string]$NewTeam)
{
[string[]]$league = "Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
"Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
"Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
"Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
"Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
"Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
"Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
"Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks"
if ($NewTeam -in $league | Where-Object {$_ -notmatch $this.Team})
{
$this.Team = (Get-Culture).TextInfo.ToTitleCase("$NewTeam")
}
else
{
throw "Invalid Team"
}
}
Trade([string]$NewTeam, [int]$NewNumber)
{
[string[]]$league = "Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
"Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
"Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
"Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
"Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
"Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
"Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
"Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks"
if ($NewTeam -in $league | Where-Object {$_ -notmatch $this.Team})
{
$this.Team = (Get-Culture).TextInfo.ToTitleCase("$NewTeam")
}
else
{
throw "Invalid Team"
}
if ($NewNumber -in 0..99)
{
$this.Number = $NewNumber
}
else
{
throw "Invalid Number"
}
}
}
|
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.
| #Raku | Raku | sub A(Int $m, Int $n) {
if $m == 0 { $n + 1 }
elsif $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
| #Perl | Perl | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return '∞';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
} |
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
| #AutoHotkey | AutoHotkey | isWordPossible(blocks, word){
o := {}
loop, parse, blocks, `n, `r
o.Insert(A_LoopField)
loop, parse, word
if !(r := isWordPossible_contains(o, A_LoopField, word))
return 0
return 1
}
isWordPossible_contains(byref o, letter, word){
loop 2 {
for k,v in o
if Instr(v,letter)
{
StringReplace, op, v,% letter
if RegExMatch(op, "[" word "]")
sap := k
else added := 1 , sap := k
if added
return "1" o.remove(sap)
}
added := 1
}
} |
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)
| #J | J | NB. https://www.math.upenn.edu/~deturck/m170/wk3/lecture/sumdiv.html
s=: ([: */ [: ((<:@:(^ >:)/) % <:@:{.) __&q:)&>
assert 6045 -: s 1800
aliquot_sum=: -~ s
abundant=: < aliquot_sum
Filter=: (#~`)(`:6)
A=: abundant Filter 1 2 p. i. 260000 NB. a batch of abundant odd numbers
# A NB. more than 1000, it's enough.
1054
NB. the first odd abundant numbers
(,: aliquot_sum) 26 {. A
945 1575 2205 2835 3465 4095 4725 5355 5775 5985 6435 6615 6825 7245 7425 7875 8085 8415 8505 8925 9135 9555 9765 10395 11025 11655
975 1649 2241 2973 4023 4641 5195 5877 6129 6495 6669 7065 7063 7731 7455 8349 8331 8433 8967 8931 9585 9597 10203 12645 11946 12057
NB. the one thousandth abundant odd number
(,: aliquot_sum) 999 { A
492975
519361
k=: adverb def '1000 * m'
1x k k k
1000000000
abundant Filter (1x k k k) + 1 2x p. i. 10x k
1000000575 1000001475 1000001625 1000001835 1000002465 1000003095 1000003725 1000004355 1000004775 1000004985 1000005435 1000005615 1000005825 1000006245 1000006425 1000006875 1000007505 1000008765 1000009395 1000010025 1000010655 1000011285 1000011705 100...
(,: aliquot_sum) {. abundant Filter (1x k k k) + 1 2x p. i. 10x k
1000000575
1083561009
|
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).
| #11l | 11l | F select_count(game_count)
‘selects a random number if the game_count is less than 18. otherwise chooses the winning number’
Int t
I game_count < 18
t = random:(1..3)
E
t = 21 - game_count
print(‘The computer chooses #.’.format(t))
R t
F request_count()
‘request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.’
V t = ‘’
L
X.try
t = input(‘Your choice 1 to 3 :’)
I Int(t) C [1, 2, 3]
R Int(t)
E
print(‘Out of range, try again’)
X.catch
I t == ‘q’
R 0
E
print(‘Invalid Entry, try again’)
F start()
V game_count = 0
print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now #.".format(game_count))
V roundno = 1
L
print("\nROUND #.: \n".format(roundno))
V t = select_count(game_count)
game_count = game_count + t
print("Running total is now #.\n".format(game_count))
I game_count >= 21
print(‘So, commiserations, the computer has won!’)
R 0
t = request_count()
I t == 0
print(‘OK,quitting the game’)
R -1
game_count = game_count + t
print("Running total is now #.\n".format(game_count))
I game_count >= 21
print(‘So, congratulations, you've won!’)
R 1
roundno++
V c = 0
V m = 0
L
V o = start()
I o == -1
L.break
E
c += I o == 0 {1} E 0
m += I o == 1 {1} E 0
print(‘Computer wins #. game, human wins #. games’.format(c, m))
V t = input(‘Another game?(press y to continue):’)
I t != ‘y’
L.break |
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
| #Befunge | Befunge | 550" :woL">:#,_&>00p" :hgiH">:#,_&>1+10p" :)n/y( euqinU">:#,_>~>:4v
v!g03!:\*`\g01\!`\g00:p05:+g03:p04:_$30g1+:10g\`v1g<,+$p02%2_|#`*8<
>>+\30g-!+20g*!*00g\#v_$40g1+:10g\`^<<1g00p03<<<_$55+:,\."snoitul"v
v!`\g00::p07:+g04p06:<^<`\g01:+1g06$<_v#!\g00*!*g02++!-g05< v"so"<
>\10g\`*\:::30g-!\40g-!+\50g-!+\60g-! +60g::30g-!\40g-!+\^ >:#,_@
>0g50g.......55+,0vg02+1_80g1+:10g\`!^>>:80p60g+30g-:90p::00g\`!>>v
^9g03g04g06g08g07<_>>0>>^<<*!*g02++!-g07\+!-g06\+!-g05\+!-g04\!-<<\
>>10g\`*\:::::30g-!\40g-!+\50g-!+\60g-!+\70g-!+\80g-!+80g::::30g^^> |
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
| #FreeBASIC | FreeBASIC | ' version 03-11-2016
' compile with: fbc -s console
#Include Once "gmp.bi"
Sub partitions(max As ULong, p() As MpZ_ptr)
' based on Numericana code example
Dim As ULong a, b, i, k
Dim As Long j
Dim As Mpz_ptr s = Allocate(Len(__mpz_struct)) : Mpz_init(s)
Mpz_set_ui(p(0), 1)
For i = 1 To max
j = 1 : k = 1 : b = 2 : a = 5
While j > 0
' j = i - (3*k*k+k) \ 2
j = i - b : b = b + a : a = a + 3
If j >= 0 Then
If k And 1 Then Mpz_add(s, s, p(j)) Else Mpz_sub(s, s, p(j))
End If
j = j + k
If j >= 0 Then
If k And 1 Then Mpz_add(s, s, p(j)) Else Mpz_sub(s, s, p(j))
End If
k = k +1
Wend
Mpz_swap(p(i), s)
Next
Mpz_clear(s)
End Sub
' ------=< MAIN >=------
Dim As ULong n, k, max = 25 ' with max > 416 the numbers become
Dim As ULongInt p(max, max) ' to big for a 64bit unsigned integer
p(1, 1) = 1 ' fill the first 3 rows
p(2, 1) = 1 : p(2, 2) = 1
p(3, 1) = 1 : p(3, 2) = 1 : p(3, 3) = 1
For n = 4 To max ' fill the rest
For k = 1 To n
If k * 2 > n Then
p(n,k)= p(n-1,k-1)
Else
p(n,k) = p(n-1,k-1) + p(n-k, k)
End If
Next
Next
For n = 1 To 25 ' print the triangle
Print Space((max - n) * 2);
For k = 1 To n
Print Using "####"; p(n, k);
Next
Print
Next
Print : print
' calculate the integer partition
max = 123456 ' 1234567 takes about ten minutes
Dim As ZString Ptr ans
ReDim big_p(max) As Mpz_ptr
For n = 0 To max
big_p(n) = Allocate(Len(__mpz_struct)) : Mpz_init(big_p(n))
Next
partitions(max, big_p())
For n = 1 To Len(Str(max))
k = Val(Left(Str(max), n))
ans = Mpz_get_str (0, 10, big_p(k))
Print Space(10 - n); "P("; Str(k); ") = "; *ans
Next
For n = 0 To max
Mpz_clear(big_p(n))
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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
| #ALGOL_60 | ALGOL 60 | begin
comment A+B;
integer a,b;
ininteger(0,a); ininteger(0,b);
outinteger(1,a+b)
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.
| #Python | Python | class BaseQueue(object):
"""Abstract/Virtual Class
"""
def __init__(self):
self.contents = list()
raise NotImplementedError
def Enqueue(self, item):
raise NotImplementedError
def Dequeue(self):
raise NotImplementedError
def Print_Contents(self):
for i in self.contents:
print i, |
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.
| #Racket | Racket |
#lang racket
(define animal-interface (interface () say))
(define cat% (class* object% (animal-interface) (super-new))) ;; error
(define cat% (class* object% (animal-interface)
(super-new)
(define/public (say)
(display "meeeeew!"))))
(define tom (new cat%))
(send tom say)
|
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.
| #REBOL | REBOL | ackermann: func [m n] [
case [
m = 0 [n + 1]
n = 0 [ackermann m - 1 1]
true [ackermann m - 1 ackermann 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
| #Phix | Phix | constant lines = get_text("abbrev_auto.txt",GT_LF_STRIPPED)
for i=1 to length(lines) do
string li = lines[i]
if length(li) then
sequence days = split(li,no_empty:=true)
if length(days)!=7 then ?9/0 end if
integer len = 1
for j=1 to 7 do
for k=j+1 to 7 do
for m=1 to min(length(days[j]),length(days[k])) do
if days[j][m]!=days[k][m] then exit end if
len = max(len,m+1)
end for
end for
end for
printf(1,"%d: %s\n",{len,li})
end if
end for
|
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
| #AWK | AWK | #!/usr/bin/awk -f
# tested with mawk 1.3.3 on Raspberry Pi 3
# also GNU awk 3.1.5, busybox 1.21.1 and 1.27.1 on AMD Sempron 2800+
#
function setblocks() {
# key to the algorithm is the representation of a block
# each block is represented by 4 characters in the string "blocks"
# for example, the "BO" block becomes "-BO-"
#
blocks="-BO--XK--DQ--CP--NA--GT--RE--TG--QD--FS--JW--HU--VI--AN--OB--ER--FS--LY--PC--ZM-"
true=1
false=0
}
function found(letter){
#
# the function "found" scans for the letter on the top of a block
# using the pattern "-B", for example, to find a "B",
# returning "true" (or 1) if found
# if not found on the top, look on the bottoms using the pattern "B-"
# again returning "true" if found
# if the letter is found on either top or bottom, the 4 character block is set to "----"
# so that block is unavailable
# finally, if no available copy of letter is found,
# the function returns "false" (0)
position= index(blocks,"-" letter)
if (position > 0)
{
blocks = substr(blocks,1,position-1) "----" substr(blocks,position+4)
return true
}
position = index(blocks,letter "-")
if (position > 0)
{blocks = substr(blocks,1,position-3) "----" substr(blocks,position+2)
return true
}
return false
}
# awk's BEGIN statement allows for initialization before processing input;
# in this case, initializing the string "blocks"
#
BEGIN{
setblocks()
}
# in awk, the input record is contained in the string variable "$0"
# the main process checks each letter in turn to see if it is on a usable block,
# summing the values returned by "found"
# if the sum equals the number of input characters the word can be spelled with the blocks
# otherwise it is not possible
#
{
nchars=length($0)
possible=false
for (i=1;i<=nchars;i++){
possible=possible + found(substr($0,i,1))
}
if (possible==nchars) print $0 " is possible"
else print $0 " is not possible"
setblocks()
}
|
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)
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
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).
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game21_64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ HITTOTAL, 21
.equ BUFFERSIZE, 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRules: .ascii "21 Game\n"
.ascii "21 is a two player game, the game is played by choosing a number \n"
.ascii "(1, 2, or 3) to be added to the running total. The game is won by\n"
.ascii "the player whose chosen number causes the running total to reach \n"
.asciz "exactly 21. The running total starts at zero.\n\n\n"
szMessHumanChoice: .asciz "Enter your choice (1,2, 3 or type (q)uit to exit): "
szMessErrChoise: .asciz "invalid choice.\n "
szMessHumanBegin: .asciz "The first move is human move.\n"
szMessPiBegin: .asciz "The first move is Raspberry pi. \n"
szMessHumanWon: .asciz "You won. \n"
szMessHumanLost: .asciz "You lost. \n"
szMessTotal: .asciz "The running total is @ \n"
szMessPiChoice: .asciz "Raspberry choice is @ \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
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRules
bl affichageMess
1:
mov x10,#0 // total = 0
mov x0,#100
bl genereraleas
cmp x0,#50
blt 2f
ldr x0,qAdrszMessHumanBegin // human begin
bl affichageMess
b 4f
2: // Rasp begin
ldr x0,qAdrszMessPiBegin
bl affichageMess
mov x0,#1
3: // rasp turn
add x10,x10,x0
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
ldr x0,qAdrszMessPiChoice
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess
cmp x10,#HITTOTAL
bne 4f
ldr x0,qAdrszMessHumanLost
bl affichageMess
b 12f
4: // display current total
mov x0,x10
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
ldr x0,qAdrszMessTotal
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess
5: // human turn
ldr x0,qAdrszMessHumanChoice
bl affichageMess
bl saisie
cmp x0,#'q' // quit ?
beq 100f
cmp x0,#'Q'
beq 100f
cmp x0,#'1'
add x9,x10,1
csel x10,x9,x10,eq
beq 6f
cmp x0,#'2'
add x9,x10,2
csel x10,x9,x10,eq
beq 6f
cmp x0,#'3'
add x9,x10,3
csel x10,x9,x10,eq
beq 6f
ldr x0,qAdrszMessErrChoise
bl affichageMess
b 5b
6:
cmp x10,#HITTOTAL // total = maxi ?
beq 11f // yes -> human won
cmp x10,#5 // else compute rasp number
mov x9,5 // compare total and optimun
7:
cmp x10,x9
ble 8f
add x9,x9,4
b 7b
8:
sub x0,x9,x10 // compute number rasp
9: // control number rasp
cmp x0,#0
ble 10f
cmp x0,#3
ble 3b
10: // if not ok, generate random number
mov x0,#2
bl genereraleas
add x0,x0,#1
b 3b // and loop
11: // display human won
ldr x0,qAdrszMessHumanWon
bl affichageMess
12: // 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
qAdrszMessHumanBegin: .quad szMessHumanBegin
qAdrszMessPiBegin: .quad szMessPiBegin
qAdrszMessPiChoice: .quad szMessPiChoice
qAdrszMessTotal: .quad szMessTotal
qAdrszMessHumanChoice: .quad szMessHumanChoice
qAdrszMessHumanLost: .quad szMessHumanLost
qAdrszMessHumanWon: .quad szMessHumanWon
qAdrszMessNewGame: .quad szMessNewGame
qAdrszMessErrChoise: .quad szMessErrChoise
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* string saisie */
/******************************************************************/
/* x0 return the first character of human entry */
saisie:
stp x1,lr,[sp,-16]! // save registers
stp x2,x8,[sp,-16]! // save registers
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 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsBuffer: .quad sBuffer
/***************************************************/
/* Generation random number */
/***************************************************/
/* x0 contains limit */
genereraleas:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
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
udiv x3,x2,x0
msub x0,x3,x0,x2 // résult = remainder
100: // end function
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/*****************************************************/
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
| #C | C |
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int a,b,c,d,e,f,g;
int lo,hi,unique,show;
int solutions;
void
bf()
{
for (f = lo;f <= hi; f++)
if ((!unique) ||
((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))
{
b = e + f - c;
if ((b >= lo) && (b <= hi) &&
((!unique) || ((b != a) && (b != c) &&
(b != d) && (b != g) && (b != e) && (b != f))))
{
solutions++;
if (show)
printf("%d %d %d %d %d %d %d\n",a,b,c,d,e,f,g);
}
}
}
void
ge()
{
for (e = lo;e <= hi; e++)
if ((!unique) || ((e != a) && (e != c) && (e != d)))
{
g = d + e;
if ((g >= lo) && (g <= hi) &&
((!unique) || ((g != a) && (g != c) &&
(g != d) && (g != e))))
bf();
}
}
void
acd()
{
for (c = lo;c <= hi; c++)
for (d = lo;d <= hi; d++)
if ((!unique) || (c != d))
{
a = c + d;
if ((a >= lo) && (a <= hi) &&
((!unique) || ((c != 0) && (d != 0))))
ge();
}
}
void
foursquares(int plo,int phi, int punique,int pshow)
{
lo = plo;
hi = phi;
unique = punique;
show = pshow;
solutions = 0;
printf("\n");
acd();
if (unique)
printf("\n%d unique solutions in %d to %d\n",solutions,lo,hi);
else
printf("\n%d non-unique solutions in %d to %d\n",solutions,lo,hi);
}
main()
{
foursquares(1,7,TRUE,TRUE);
foursquares(3,9,TRUE,TRUE);
foursquares(0,9,FALSE,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
| #Frink | Frink |
class PartitionCount
{
// Array of elements
class var triangle = [[0],[0,1]]
// Array of cumulative sums in each row.
class var sumTriangle = [[1],[0,1]]
class calcRowsTo[toRow] :=
{
for row = length[triangle] to toRow
{
triangle@row = workrow = new array[[row+1],0]
sumTriangle@row = sumworkrow = new array[[row+1],0]
oversum = 0
for col = 1 to row
{
otherRow = row-col
sum = sumTriangle@otherRow@min[col,otherRow]
workrow@col = sum
oversum = oversum + sum
sumworkrow@col = oversum
}
}
}
class rowSum[row] :=
{
calcRowsTo[row]
return sumTriangle@row@row
}
}
PartitionCount.calcRowsTo[25]
for row=1 to 25
{
for col=1 to row
print[PartitionCount.triangle@row@col + " "]
println[]
}
// Test against Frink's built-in much faster partitionCount function that uses
// Euler's pentagonal method for counting partitions.
testRow[row] :=
{
sum = PartitionCount.rowSum[row]
println["$row\t$sum\t" + (sum == partitionCount[row] ? "correct" : "incorrect")]
}
println[]
testRow[23]
testRow[123]
testRow[1234]
testRow[12345]
|
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
| #GAP | GAP | PrintArray(List([1 .. 25], n -> List([1 .. n], k -> NrPartitions(n, k))));
[ [ 1 ],
[ 1, 1 ],
[ 1, 1, 1 ],
[ 1, 2, 1, 1 ],
[ 1, 2, 2, 1, 1 ],
[ 1, 3, 3, 2, 1, 1 ],
[ 1, 3, 4, 3, 2, 1, 1 ],
[ 1, 4, 5, 5, 3, 2, 1, 1 ],
[ 1, 4, 7, 6, 5, 3, 2, 1, 1 ],
[ 1, 5, 8, 9, 7, 5, 3, 2, 1, 1 ],
[ 1, 5, 10, 11, 10, 7, 5, 3, 2, 1, 1 ],
[ 1, 6, 12, 15, 13, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 6, 14, 18, 18, 14, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 7, 16, 23, 23, 20, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 7, 19, 27, 30, 26, 21, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 8, 21, 34, 37, 35, 28, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 8, 24, 39, 47, 44, 38, 29, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 9, 27, 47, 57, 58, 49, 40, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 9, 30, 54, 70, 71, 65, 52, 41, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 10, 33, 64, 84, 90, 82, 70, 54, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 10, 37, 72, 101, 110, 105, 89, 73, 55, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 11, 40, 84, 119, 136, 131, 116, 94, 75, 56, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 11, 44, 94, 141, 163, 164, 146, 123, 97, 76, 56, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 12, 48, 108, 164, 199, 201, 186, 157, 128, 99, 77, 56, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ],
[ 1, 12, 52, 120, 192, 235, 248, 230, 201, 164, 131, 100, 77, 56, 42, 30, 22, 15, 11, 7, 5, 3, 2, 1, 1 ] ]
List([23, 123, 1234, 12345], NrPartitions);
[ 1255, 2552338241, 156978797223733228787865722354959930,
69420357953926116819562977205209384460667673094671463620270321700806074195845953959951425306140971942519870679768681736 ] |
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
| #ALGOL_68 | ALGOL 68 | print((read int + read int)) |
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.
| #Raku | Raku |
use v6;
role A {
# must be filled in by the class it is composed into
method abstract() { ... };
# can be overridden in the class, but that's not mandatory
method concrete() { say '# 42' };
}
class SomeClass does A {
method abstract() {
say "# made concrete in class"
}
}
my $obj = SomeClass.new;
$obj.abstract();
$obj.concrete();
# output:
# made concrete in class
# 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.
| #ReScript | ReScript | let _m = Sys.argv[2]
let _n = Sys.argv[3]
let m = int_of_string(_m)
let n = int_of_string(_n)
let rec a = (m, n) =>
switch (m, n) {
| (0, n) => (n+1)
| (m, 0) => a(m-1, 1)
| (m, n) => a(m-1, a(m, n-1))
}
Js.log("ackermann(" ++ _m ++ ", " ++ _n ++ ") = "
++ string_of_int(a(m, n))) |
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
| #Picat | Picat |
import util.
max_length(Words) = Max =>
Lengths = [len(W): W in Words],
Max = max(Lengths).
min_abbr([]) = 0.
min_abbr(Line) = Min =>
Words = split(Line),
Max = max_length(Words),
I = 0,
Abbrevs = [],
Uniqs = [],
do
I := I + 1,
Abbrevs := [slice(W, 1, I): W in Words],
Uniqs := sort_remove_dups(Abbrevs)
while (I < Max, len(Abbrevs) > len(Uniqs)),
Min = I.
main(Args) =>
File = Args[1],
Reader = open(File),
while (not at_end_of_stream(Reader))
Line := read_line(Reader),
Min := min_abbr(Line),
if (Min > 0) then
printf("%d %s\n", Min, Line)
else
nl
end
end.
|
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
| #BaCon | BaCon | CONST info$ = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
WHILE TRUE
READ word$
IF NOT(LEN(word$)) THEN BREAK
block$ = info$
count = AMOUNT(block$)
FOR y = 1 TO LEN(word$)
FOR x = 1 TO AMOUNT(block$)
IF TALLY(TOKEN$(block$, x), MID$(UCASE$(word$), y, 1)) THEN
block$ = DEL$(block$, x)
BREAK
END IF
NEXT
NEXT
PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n"
WEND |
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)
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () => {
// abundantTuple :: Int -> [(Int, Int)]
const abundantTuple = n => {
// Either a list containing the tuple of N
// and its divisor sum (if n is abundant),
// or otherwise an empty list.
const x = divisorSum(n);
return n < x ? ([
Tuple(n)(x)
]) : [];
};
// divisorSum :: Int -> Int
const divisorSum = n => {
// Sum of the divisors of n.
const
floatRoot = Math.sqrt(n),
intRoot = Math.floor(floatRoot),
lows = filter(x => 0 === n % x)(
enumFromTo(1)(intRoot)
);
return sum(lows.concat(map(quot(n))(
intRoot === floatRoot ? (
lows.slice(1, -1)
) : lows.slice(1)
)));
};
// TEST ---------------------------------------
console.log(
'First 25 abundant odd numbers, with their divisor sums:'
)
console.log(unlines(map(showTuple)(
take(25)(
concatMapGen(abundantTuple)(
enumFromThen(1)(3)
)
)
)));
console.log(
'\n\n1000th abundant odd number, with its divisor sum:'
)
console.log(showTuple(
take(1)(drop(999)(
concatMapGen(abundantTuple)(
enumFromThen(1)(3)
)
))[0]
))
console.log(
'\n\nFirst abundant odd number above 10^9, with divisor sum:'
)
const billion = Math.pow(10, 9);
console.log(showTuple(
take(1)(
concatMapGen(abundantTuple)(
enumFromThen(1 + billion)(3 + billion)
)
)[0]
))
};
// GENERAL REUSABLE FUNCTIONS -------------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// concatMapGen :: (a -> [b]) -> Gen [a] -> Gen [b]
const concatMapGen = f =>
function*(xs) {
let
x = xs.next(),
v = undefined;
while (!x.done) {
v = f(x.value);
if (0 < v.length) {
yield v[0];
}
x = xs.next();
}
};
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = n => xs =>
Infinity > length(xs) ? (
xs.slice(n)
) : (take(n)(xs), xs);
// dropAround :: (a -> Bool) -> [a] -> [a]
// dropAround :: (Char -> Bool) -> String -> String
const dropAround = p => xs => dropWhile(p)(
dropWhileEnd(p)(xs)
);
// dropWhile :: (a -> Bool) -> [a] -> [a]
// dropWhile :: (Char -> Bool) -> String -> String
const dropWhile = p => xs => {
const lng = xs.length;
return 0 < lng ? xs.slice(
until(i => i === lng || !p(xs[i]))(
i => 1 + i
)(0)
) : [];
};
// dropWhileEnd :: (a -> Bool) -> [a] -> [a]
// dropWhileEnd :: (Char -> Bool) -> String -> String
const dropWhileEnd = p => xs => {
let i = xs.length;
while (i-- && p(xs[i])) {}
return xs.slice(0, i + 1);
};
// enumFromThen :: Int -> Int -> Gen [Int]
const enumFromThen = x =>
// A non-finite stream of integers,
// starting with x and y, and continuing
// with the same interval.
function*(y) {
const d = y - x;
let v = y + d;
yield x;
yield y;
while (true) {
yield v;
v = d + v;
}
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m => n =>
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = f => xs => xs.filter(f);
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = f => xs =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// quot :: Int -> Int -> Int
const quot = n => m => Math.floor(n / m);
// show :: a -> String
const show = JSON.stringify;
// showTuple :: Tuple -> String
const showTuple = tpl =>
'(' + enumFromTo(0)(tpl.length - 1)
.map(x => unQuoted(show(tpl[x])))
.join(',') + ')';
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => xs =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p => f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// unQuoted :: String -> String
const unQuoted = s =>
dropAround(x => 34 === x.codePointAt(0))(
s
);
// MAIN ---
return main();
})(); |
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).
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program game21.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ STDIN, 0 @ Linux input console
.equ READ, 3 @ Linux syscall
.equ HITTOTAL, 21
.equ BUFFERSIZE, 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRules: .ascii "21 Game\n"
.ascii "21 is a two player game, the game is played by choosing a number \n"
.ascii "(1, 2, or 3) to be added to the running total. The game is won by\n"
.ascii "the player whose chosen number causes the running total to reach \n"
.asciz "exactly 21. The running total starts at zero.\n\n\n"
szMessHumanChoice: .asciz "Enter your choice (1,2, 3 or type (q)uit to exit): "
szMessErrChoise: .asciz "invalid choice.\n "
szMessHumanBegin: .asciz "The first move is human move.\n"
szMessPiBegin: .asciz "The first move is Raspberry pi. \n"
szMessHumanWon: .asciz "You won. \n"
szMessHumanLost: .asciz "You lost. \n"
szMessTotal: .asciz "The running total is @ \n"
szMessPiChoice: .asciz "Raspberry choice if @ \n"
szMessNewGame: .asciz "New game (y/n) ? \n"
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessRules
bl affichageMess
1:
mov r10,#0 @ total = 0
mov r0,#100
bl genereraleas
cmp r0,#50
blt 2f
ldr r0,iAdrszMessHumanBegin @ human begin
bl affichageMess
b 4f
2: @ Rasp begin
ldr r0,iAdrszMessPiBegin
bl affichageMess
mov r0,#1
3: @ rasp turn
add r10,r10,r0
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
ldr r0,iAdrszMessPiChoice
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess
cmp r10,#HITTOTAL
bne 4f
ldr r0,iAdrszMessHumanLost
bl affichageMess
b 10f
4: @ display current total
mov r0,r10
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
ldr r0,iAdrszMessTotal
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess
5: @ human turn
ldr r0,iAdrszMessHumanChoice
bl affichageMess
bl saisie
cmp r0,#'q' @ quit ?
beq 100f
cmp r0,#'Q'
beq 100f
cmp r0,#'1'
addeq r10,r10,#1
beq 6f
cmp r0,#'2'
addeq r10,r10,#2
beq 6f
cmp r0,#'3'
addeq r10,r10,#3
beq 6f
ldr r0,iAdrszMessErrChoise
bl affichageMess
b 5b
6:
cmp r10,#HITTOTAL @ total = maxi ?
beq 9f @ yes -> human won
cmp r10,#5 @ else compute rasp number
rsble r0,r10,#5
ble 7f
cmp r10,#9
rsble r0,r10,#9
ble 7f
cmp r10,#13
rsble r0,r10,#13
ble 7f
cmp r10,#17
rsble r0,r10,#17
ble 7f
cmp r10,#21
rsble r0,r10,#21
ble 7f
7: @ control number rasp
cmp r0,#0
ble 8f
cmp r0,#3
ble 3b
8: @ if not ok, generate random number
mov r0,#2
bl genereraleas
add r0,r0,#1
b 3b @ and loop
9: @ display human won
ldr r0,iAdrszMessHumanWon
bl affichageMess
10: @ display new game ?
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszMessNewGame
bl affichageMess
bl saisie
cmp r0,#'y'
beq 1b
cmp r0,#'Y'
beq 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessRules: .int szMessRules
iAdrszMessHumanBegin: .int szMessHumanBegin
iAdrszMessPiBegin: .int szMessPiBegin
iAdrszMessPiChoice: .int szMessPiChoice
iAdrszMessTotal: .int szMessTotal
iAdrszMessHumanChoice: .int szMessHumanChoice
iAdrszMessHumanLost: .int szMessHumanLost
iAdrszMessHumanWon: .int szMessHumanWon
iAdrszMessNewGame: .int szMessNewGame
iAdrszMessErrChoise: .int szMessErrChoise
iAdrsZoneConv: .int sZoneConv
/******************************************************************/
/* string saisie */
/******************************************************************/
/* r0 return the first character of human entry */
saisie:
push {r1-r7,lr} @ save registers
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ request to read datas
svc 0 @ call system
ldr r1,iAdrsBuffer @ buffer address
ldrb r0,[r1] @ load first character
100:
pop {r1-r7,lr}
bx lr @ return
iAdrsBuffer: .int sBuffer
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
cmp r0,#0
beq 100f
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/*****************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.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
| #C.23 | C# | using System;
using System.Linq;
namespace Four_Squares_Puzzle {
class Program {
static void Main(string[] args) {
fourSquare(1, 7, true, true);
fourSquare(3, 9, true, true);
fourSquare(0, 9, false, false);
}
private static void fourSquare(int low, int high, bool unique, bool print) {
int count = 0;
if (print) {
Console.WriteLine("a b c d e f g");
}
for (int a = low; a <= high; ++a) {
for (int b = low; b <= high; ++b) {
if (notValid(unique, b, a)) continue;
int fp = a + b;
for (int c = low; c <= high; ++c) {
if (notValid(unique, c, b, a)) continue;
for (int d = low; d <= high; ++d) {
if (notValid(unique, d, c, b, a)) continue;
if (fp != b + c + d) continue;
for (int e = low; e <= high; ++e) {
if (notValid(unique, e, d, c, b, a)) continue;
for (int f = low; f <= high; ++f) {
if (notValid(unique, f, e, d, c, b, a)) continue;
if (fp != d + e + f) continue;
for (int g = low; g <= high; ++g) {
if (notValid(unique, g, f, e, d, c, b, a)) continue;
if (fp != f + g) continue;
++count;
if (print) {
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}", a, b, c, d, e, f, g);
}
}
}
}
}
}
}
}
if (unique) {
Console.WriteLine("There are {0} unique solutions in [{1}, {2}]", count, low, high);
}
else {
Console.WriteLine("There are {0} non-unique solutions in [{1}, {2}]", count, low, high);
}
}
private static bool notValid(bool unique, int needle, params int[] haystack) {
return unique && haystack.Any(p => p == needle);
}
}
} |
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
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
intMin := func(a, b int) int {
if a < b {
return a
} else {
return b
}
}
var cache = [][]*big.Int{{big.NewInt(1)}}
cumu := func(n int) []*big.Int {
for y := len(cache); y <= n; y++ {
row := []*big.Int{big.NewInt(0)}
for x := 1; x <= y; x++ {
cacheValue := cache[y-x][intMin(x, y-x)]
row = append(row, big.NewInt(0).Add(row[len(row)-1], cacheValue))
}
cache = append(cache, row)
}
return cache[n]
}
row := func(n int) {
e := cumu(n)
for i := 0; i < n; i++ {
fmt.Printf(" %v ", (big.NewInt(0).Sub(e[i+1], e[i])).Text(10))
}
fmt.Println()
}
fmt.Println("rows:")
for x := 1; x < 11; x++ {
row(x)
}
fmt.Println()
fmt.Println("sums:")
for _, num := range [...]int{23, 123, 1234, 12345} {
r := cumu(num)
fmt.Printf("%d %v\n", num, r[len(r)-1].Text(10))
}
} |
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
| #ALGOL_W | ALGOL W | begin
integer a, b;
read( a, b );
write( a + b )
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.
| #REBOL | REBOL | rebol [
Title: "Abstract Type"
URL: http://rosettacode.org/wiki/Abstract_type
]
; The "shape" class is an abstract class -- it defines the "pen"
; property and "line" method, but "size" and "draw" are undefined and
; unimplemented.
shape: make object! [
pen: "X"
size: none
line: func [count][loop count [prin self/pen] prin crlf]
draw: does [none]
]
; The "box" class inherits from "shape" and provides the missing
; information for drawing boxes.
box: make shape [
size: 10
draw: does [loop self/size [line self/size]]
]
; "rectangle" also inherits from "shape", but handles the
; implementation very differently.
rectangle: make shape [
size: 20x10
draw: does [loop self/size/y [line self/size/x]]
]
; Unlike some languages discussed, REBOL has absolutely no qualms
; about instantiating an "abstract" class -- that's how I created the
; derived classes of "rectangle" and "box", after all.
s: make shape [] s/draw ; Nothing happens.
print "A box:"
b: make box [pen: "O" size: 5] b/draw
print [crlf "A rectangle:"]
r: make rectangle [size: 32x5] r/draw |
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.
| #REXX | REXX | /*REXX program calculates and displays some values for the Ackermann function. */
/*╔════════════════════════════════════════════════════════════════════════╗
║ Note: the Ackermann function (as implemented here) utilizes deep ║
║ recursive and is limited by the largest number that can have ║
║ "1" (unity) added to a number (successfully and accurately). ║
╚════════════════════════════════════════════════════════════════════════╝*/
high=24
do j=0 to 3; say
do k=0 to high % (max(1, j))
call tell_Ack j, k
end /*k*/
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell_Ack: parse arg mm,nn; calls=0 /*display an echo message to terminal. */
#=right(nn,length(high))
say 'Ackermann('mm", "#')='right(ackermann(mm, nn), high),
left('', 12) 'calls='right(calls, high)
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
ackermann: procedure expose calls /*compute value of Ackermann function. */
parse arg m,n; calls=calls+1
if m==0 then return n+1
if n==0 then return ackermann(m-1, 1)
return ackermann(m-1, ackermann(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
| #Prolog | Prolog | minimum_abbreviation_length(Day_names, Min_length):-
sort(Day_names, Sorted_names),
minimum_abbreviation_length(Sorted_names, Min_length, 1).
minimum_abbreviation_length([_], Min_length, Min_length):- !.
minimum_abbreviation_length([Name1, Name2|Rest], Min_length, M1):-
common_prefix_length(Name1, Name2, Length),
M2 is max(M1, Length + 1),
minimum_abbreviation_length([Name2|Rest], Min_length, M2).
common_prefix_length(String1, String2, Length):-
string_chars(String1, Chars1),
string_chars(String2, Chars2),
common_prefix_length1(Chars1, Chars2, Length, 0).
common_prefix_length1([], _, Length, Length):-!.
common_prefix_length1(_, [], Length, Length):-!.
common_prefix_length1([C1|_], [C2|_], Length, Length):-
C1 \= C2,
!.
common_prefix_length1([C|Chars1], [C|Chars2], Length, L1):-
L2 is L1 + 1,
common_prefix_length1(Chars1, Chars2, Length, L2).
to_upper_case([], []):-!.
to_upper_case([String|S], [Upper_case|U]):-
string_upper(String, Upper_case),
to_upper_case(S, U).
process_line(""):-
nl,
!.
process_line(Line):-
split_string(Line, "\s\t", "\s\t", Day_names),
to_upper_case(Day_names, Upper),
minimum_abbreviation_length(Upper, Length),
writef('%w %w\n', [Length, Line]).
process_stream(Stream):-
read_line_to_string(Stream, String),
String \= end_of_file,
!,
process_line(String),
process_stream(Stream).
process_stream(_).
process_file(File):-
open(File, read, Stream),
process_stream(Stream),
close(Stream).
main:-
process_file("days_of_week.txt"). |
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
| #BASIC | BASIC |
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ABC_Problem '
' '
' Developed by A. David Garza Marín in VB-DOS for '
' RosettaCode. November 29, 2016. '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Comment the following line to run it in QB or QBasic
OPTION EXPLICIT ' Modify to OPTION _EXPLICIT for QB64
' SUBs and FUNCTIONs
DECLARE SUB doCleanBlocks ()
DECLARE FUNCTION ICanMakeTheWord (WhichWord AS STRING) AS INTEGER
DECLARE SUB doReadBlocks ()
' rBlock Data Type
TYPE regBlock
Block AS STRING * 2
Used AS INTEGER
END TYPE
' Initialize
CONST False = 0, True = NOT False, HMBlocks = 20
DATA "BO", "XK", "DQ", "CP", "NA", "GT","RE", "TG"
DATA "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER"
DATA "FS", "LY", "PC","ZM"
DIM rBlock(1 TO HMBlocks) AS regBlock
DIM i AS INTEGER, aWord AS STRING, YorN AS STRING
doReadBlocks ' Read the data in the blocks
'-------------- Main program cycle ------------------
CLS
PRINT "This program has the following blocks: ";
FOR i = 1 TO HMBlocks
PRINT rBlock(i).Block; "|";
NEXT i
PRINT : PRINT
PRINT "Please, write a word or a short sentence to see if the available"
PRINT "blocks can make it. If so, I will tell you."
DO
doCleanBlocks ' Clean all blocks
PRINT
INPUT "Which is the word"; aWord
aWord = LTRIM$(RTRIM$(aWord))
IF aWord <> "" THEN
IF ICanMakeTheWord(aWord) THEN
PRINT "Yes, i can make it."
ELSE
PRINT "No, I can't make it."
END IF
ELSE
PRINT "At least, you need to type a letter."
END IF
PRINT
PRINT "Do you want to try again (Y/N) ";
DO
YorN = INPUT$(1)
YorN = UCASE$(YorN)
LOOP UNTIL YorN = "Y" OR YorN = "N"
PRINT YorN
LOOP UNTIL YorN = "N"
' -------------- End of Main program ----------------
END
SUB doCleanBlocks ()
' Var
SHARED rBlock() AS regBlock
DIM i AS INTEGER
' Will clean the Used status of all blocks
FOR i = 1 TO HMBlocks
rBlock(i).Used = False
NEXT i
END SUB
SUB doReadBlocks ()
' Var
SHARED rBlock() AS regBlock
DIM i AS INTEGER
' Will read the block values from DATA
FOR i = 1 TO HMBlocks
READ rBlock(i).Block
NEXT i
END SUB
FUNCTION ICanMakeTheWord (WhichWord AS STRING) AS INTEGER ' Comment AS INTEGER to run in QBasic, QB64 and QuickBASIC
' Var
SHARED rBlock() AS regBlock
DIM i AS INTEGER, l AS INTEGER, j AS INTEGER, iYesICan AS INTEGER
DIM c AS STRING, sUWord AS STRING
' Will evaluate if can make the word
sUWord = UCASE$(WhichWord)
l = LEN(sUWord)
i = 0
DO
i = i + 1
iYesICan = False
c = MID$(sUWord, i, 1)
j = 0
DO
j = j + 1
IF NOT rBlock(j).Used THEN
iYesICan = (INSTR(rBlock(j).Block, c) > 0)
rBlock(j).Used = iYesICan
END IF
LOOP UNTIL j >= HMBlocks OR iYesICan
LOOP UNTIL i >= l OR NOT iYesICan
' The result will depend on the last value of
' iYesICan variable. If the last value is True
' is because the function found even the last
' letter analyzed.
ICanMakeTheWord = iYesICan
END FUNCTION
|
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)
| #jq | jq |
# The factors, unsorted
def factors:
. as $num
| reduce range(1; 1 + sqrt|floor) as $i
([];
if ($num % $i) == 0 then
($num / $i) as $r
| if $i == $r then . + [$i] else . + [$i, $r] end
else .
end) ;
def abundant_odd_numbers:
range(1; infinite; 2)
| (factors | add) as $sum
| select($sum > 2*.)
| [., $sum] ; |
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).
| #Arturo | Arturo | print "-----------------------------"
print " Welcome to 21 Game"
print "-----------------------------"
players: ["A" "B"]
currentPlayer: sample players
nextPlayer: first players -- currentPlayer
runningTotal: new 0
num: 0
getNum: function [][
result: strip input "Enter a number (1,2,3) / x to exit: "
if result="x" -> exit
return result
]
loop.forever @[currentPlayer nextPlayer] 'plays [
print ["Running total:" runningTotal]
print ["Player" plays "turn"]
num: getNum
while [or? [not? numeric? num][not? contains? 1..3 to :integer num]][
num: getNum
]
runningTotal: runningTotal + to :integer num
print ""
if runningTotal=21 [
print ["Running total is 21. Player" plays "won!"]
exit
]
]
|
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
| #C.2B.2B | C++ |
//C++14/17
#include <algorithm>//std::for_each
#include <iostream> //std::cout
#include <numeric> //std::iota
#include <vector> //std::vector, save solutions
#include <list> //std::list, for fast erase
using std::begin, std::end, std::for_each;
//Generates all the valid solutions for the problem in the specified range [from, to)
std::list<std::vector<int>> combinations(int from, int to)
{
if (from > to)
return {}; //Return nothing if limits are invalid
auto pool = std::vector<int>(to - from);//Here we'll save our values
std::iota(begin(pool), end(pool), from);//Populates pool
auto solutions = std::list<std::vector<int>>{}; //List for the solutions
//Brute-force calculation of valid values...
for (auto a : pool)
for (auto b : pool)
for (auto c : pool)
for (auto d : pool)
for (auto e : pool)
for (auto f : pool)
for (auto g : pool)
if ( a == c + d
&& b + c == e + f
&& d + e == g )
solutions.push_back({a, b, c, d, e, f, g});
return solutions;
}
//Filter the list generated from "combinations" and return only lists with no repetitions
std::list<std::vector<int>> filter_unique(int from, int to)
{
//Helper lambda to check repetitions:
//If the count is > 1 for an element, there must be a repetition inside the range
auto has_non_unique_values = [](const auto & range, auto target)
{
return std::count( begin(range), end(range), target) > 1;
};
//Generates all the solutions...
auto results = combinations(from, to);
//For each solution, find duplicates inside
for (auto subrange = cbegin(results); subrange != cend(results); ++subrange)
{
bool repetition = false;
//If some element is repeated, repetition becomes true
for (auto x : *subrange)
repetition |= has_non_unique_values(*subrange, x);
if (repetition) //If repetition is true, remove the current subrange from the list
{
results.erase(subrange); //Deletes subrange from solutions
--subrange; //Rewind to the last subrange analysed
}
}
return results; //Finally return remaining results
}
template <class Container> //Template for the sake of simplicity
inline void print_range(const Container & c)
{
for (const auto & subrange : c)
{
std::cout << "[";
for (auto elem : subrange)
std::cout << elem << ' ';
std::cout << "\b]\n";
}
}
int main()
{
std::cout << "Unique-numbers combinations in range 1-7:\n";
auto solution1 = filter_unique(1, 8);
print_range(solution1);
std::cout << "\nUnique-numbers combinations in range 3-9:\n";
auto solution2 = filter_unique(3,10);
print_range(solution2);
std::cout << "\nNumber of combinations in range 0-9: "
<< combinations(0, 10).size() << "." << std::endl;
return 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
| #Groovy | Groovy |
def partitions(c)
{
def p=[];
int k = 0;
p[k] = c;
int counter=0;
def counts=[];
for (i in 0..c-1)
{counts[i]=0;}
while (true)
{
counter++;
counts[p[0]-1]=counts[p[0]-1]+1;
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{ rem_val += p[k];
k--;}
if (k < 0) { break;}
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k+1] = rem_val;
k++;
}
println counts;
return counter;
}
static void main(String[] args)
{
for( i in 1..25 )
{partitions(i);}
}
|
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
| #Amazing_Hopper | Amazing Hopper |
#include <hbasic.h>
#import lib/input.bas.lib
#include include/input.h
Begin
Token Init
Cls
Locate(5,1),Print(Utf8$("Ingrese dos números, separados por espacio: "))
msg=""
LocCol(45),Let( msg := ReadString(msg))
Token Sep(" ")
Print("Suma : ", Token(1),Val(Token$(msg)) Plus (Token(2),Val(Token$(msg))), Newl)
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.
| #Red | Red | Red [
Title: "Abstract Type"
Original-Author: oofoe
]
; The "shape" class is an abstract class -- it defines the "pen"
; property and "line" method, but "size" and "draw" are undefined and
; unimplemented.
shape: make object! [
pen: "X"
size: none
line: func [count][loop count [prin self/pen] prin newline]
draw: does [none]
]
; The "box" class inherits from "shape" and provides the missing
; information for drawing boxes.
box: make shape [
size: 10
draw: does [loop self/size [line self/size]]
]
; "rectangle" also inherits from "shape", but handles the
; implementation very differently.
rectangle: make shape [
size: 20x10
draw: does [loop self/size/y [line self/size/x]]
]
; Unlike some languages discussed, REBOL has absolutely no qualms
; about instantiating an "abstract" class -- that's how I created the
; derived classes of "rectangle" and "box", after all.
print "An abstract shape (nothing):"
s: make shape [] s/draw ; Nothing happens.
print [newline "A box:"]
b: make box [pen: "O" size: 5] b/draw
print [newline "A rectangle:"]
r: make rectangle [size: 32x5] r/draw |
http://rosettacode.org/wiki/Abstract_type | Abstract type | Abstract type is a type without instances or without definition.
For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called interfaces. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).
The term abstract datatype also may denote a type, with an implementation provided by the programmer rather than directly by the language (a built-in or an inferred type). Here the word abstract means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.
It is important not to confuse this abstractness (of implementation) with one of the abstract type. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.
In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have abstract types that are not OO related and are not an abstractness too. These are pure abstract types without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.
Task: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.
| #ReScript | ReScript | type t |
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.
| #Ring | Ring | for m = 0 to 3
for n = 0 to 4
see "Ackermann(" + m + ", " + n + ") = " + Ackermann(m, n) + nl
next
next
func Ackermann m, n
if m > 0
if n > 0
return Ackermann(m - 1, Ackermann(m, n - 1))
but n = 0
return Ackermann(m - 1, 1)
ok
but m = 0
if n >= 0
return n + 1
ok
ok
Raise("Incorrect Numerical input !!!") |
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
| #PureBasic | PureBasic | EnableExplicit
#TZ="|"
#FZ="@"
#WORD_SEPARATOR=Chr(32)
Declare.i abbreviations(txt.s)
Define dataset.s, line_number.i, line_cache.s, result.i, word_index.i, word.s
If OpenConsole("abbreviations-automatic") And ReadFile(0,"./Data/days_of_the_week.txt")
dataset=ReadString(0,#PB_UTF8|#PB_File_IgnoreEOL) : CloseFile(0)
line_number=1
Repeat
line_cache=StringField(dataset,line_number,#LF$)
If Len(line_cache)=0
PrintN("")
Else
result=abbreviations(line_cache) : PrintN(RSet(Str(result),3)+": "+line_cache)
word_index=1
word=StringField(line_cache,word_index,#WORD_SEPARATOR)
If word : Print(Space(5)) : EndIf
While word
Print(LSet(Left(word,result),Len(word)+1))
word_index+1 : word=StringField(line_cache,word_index,#WORD_SEPARATOR)
Wend
PrintN("")
EndIf
line_number+1
Until line_number>CountString(dataset,#LF$)
Input()
EndIf
Procedure.b CompareLetters(sfield.s,letters.i,separator.s=#WORD_SEPARATOR)
Define word_index.i, buf.s
For word_index=1 To CountString(sfield,separator)+1
buf+LSet(Left(StringField(sfield,word_index,separator),letters),letters,#FZ)+#TZ
Next
For word_index=1 To CountString(buf,#TZ)
If CountString(buf,StringField(buf,word_index,#TZ))>1 : ProcedureReturn #True : EndIf
Next
ProcedureReturn #False
EndProcedure
Procedure.i abbreviations(txt.s)
Define letters.i=1
While CompareLetters(txt,letters) : letters+1 : Wend
ProcedureReturn letters
EndProcedure |
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
| #Batch_File | Batch File |
@echo off
::abc.bat
::
::Batch file to evaluate if a given string can be represented with a set of
::20 2-faced blocks.
::
::Check if a string was provided
if "%1"=="" goto ERROR
::Define blocks. Separate blocks by ':', and terminat with '::'
set "FACES=BO:XK:DQ:CP:NA:GT:RE:TG:QD:FS:JW:HU:VI:AN:OB:ER:FS:LY:PC:ZM::"
set INPUT=%1
set "COUNTER=0"
::The main loop steps through the input string, checking if an available
::block exists for each character
:LOOP_MAIN
::Get character, increase counter, and test if there are still characters
call set "char=%%INPUT:~%COUNTER%,1%%"
set /a "COUNTER+=1"
if "%CHAR%"=="" goto LOOP_MAIN_END
set "OFFSET=0"
:LOOP_2
::Read in two characters (one block)
call set "BLOCK=%%FACES%:~%OFFSET%,2%%"
::Test if the all blocks were checked. If so, no match was found
if "%BLOCK%"==":" goto FAIL
::Test if current input string character is in the current block
if /i "%BLOCK:~0,1%"=="%CHAR%" goto FOUND
if /i "%BLOCK:~1,1%"=="%CHAR%" goto FOUND
::Increase offset to point to the next block
set /a "OFFSET+=3"
goto LOOP_2
:LOOP_2_END
::If found, blank out the block used
:FOUND
call set "FACES=%%FACES:%BLOCK%:= :%%"
goto LOOP_MAIN
:LOOP_MAIN_END
echo %0: It is possible to write the '%INPUT%' with my blocks.
goto END
:FAIL
echo %0: It is NOT possible to write the '%INPUT%' with my blocks.
goto END
:ERROR
echo %0: Please enter a string to evaluate
echo.
:END
|
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)
| #Julia | Julia | using Primes
function propfact(n)
f = [one(n)]
for (p, x) in factor(n)
f = reduce(vcat, [f*p^i for i in 1:x], init=f)
end
pop!(f)
sort(f)
end
isabundant(n) = sum(propfact(n)) > n
prettyprintfactors(n) = (a = propfact(n); println("$n has proper divisors $a, these sum to $(sum(a))."))
function oddabundantsfrom(startingint, needed, nprint=0)
n = isodd(startingint) ? startingint : startingint + 1
count = one(n)
while count <= needed
if isabundant(n)
if nprint == 0
prettyprintfactors(n)
elseif nprint == count
prettyprintfactors(n)
end
count += 1
end
n += 2
end
end
println("First 25 abundant odd numbers:")
oddabundantsfrom(2, 25)
println("The thousandth abundant odd number:")
oddabundantsfrom(2, 1001, 1000)
println("The first abundant odd number greater than one billion:")
oddabundantsfrom(1000000000, 1)
|
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).
| #AutoHotkey | AutoHotkey | Gui, font, S16
Gui, add, Radio, vRadioC , Cake
Gui, add, Radio, vRadioE x+0 Checked, Easy
Gui, add, Radio, vRadioH x+0, Hard
Gui, add, text, xs vT, Total : 00
Gui, add, text, xs vComputer, Computer Dealt 00
Gui, add, text, xs Section, Player 1
loop, 3
Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index
Gui, add, button, xs vReset gReset, reset
Gui show,, 21 Game
Winners := [1,5,9,13,17,21]
gosub, reset
return
;-----------------------------------
reset:
total := 0
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
GuiControl,, Computer, % "Computer Waiting"
Loop 3
GuiControl, Enable, % "Player1_" A_Index
Random, rnd, 0, 1
if rnd
{
Loop 3
GuiControl, Disable, % "Player1_" A_Index
gosub ComputerTurn
}
return
;-----------------------------------
Total:
Added := SubStr(A_GuiControl, 9,1)
Total += Added
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
if (total >= 21)
{
MsgBox % "Player 1 Wins"
gosub reset
return
}
Loop 3
GuiControl, Disable, % "Player1_" A_Index
gosub, ComputerTurn
return
;-----------------------------------
ComputerTurn:
Gui, Submit, NoHide
Sleep 500
if RadioE
{
if (total < 13)
RadioC := true
else
RadioH := true
}
if RadioC
{
Random, Deal, 1, 3
total += Deal
}
if RadioH
{
for i, v in Winners
if (total >= v)
continue
else
{
Deal := v - total
if Deal > 3
Random, Deal, 1, 3
total += Deal
break
}
}
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
GuiControl,, Computer, % "Computer Dealt " Deal
if (total=21)
{
MsgBox Computer Wins
gosub, reset
}
else
Loop 3
GuiControl, Enable, % "Player1_" A_Index
return |
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
| #Clojure | Clojure | (use '[clojure.math.combinatorics]
(defn rings [r & {:keys [unique] :or {unique true}}]
(if unique
(apply concat (map permutations (combinations r 7)))
(selections r 7)))
(defn four-rings [low high & {:keys [unique] :or {unique true}}]
(for [[a b c d e f g] (rings (range low (inc high)) :unique unique)
:when (= (+ a b) (+ b c d) (+ d e f) (+ f g))] [a b c d e f g]))
|
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
| #Haskell | Haskell | import Data.List (mapAccumL)
cumu :: [[Integer]]
cumu = [1] : map (scanl (+) 0) rows
rows :: [[Integer]]
rows = snd $ mapAccumL f [] cumu where
f r row = (rr, new_row) where
new_row = map head rr
rr = map tailKeepOne (row:r)
tailKeepOne [x] = [x]
tailKeepOne (_:xs) = xs
sums n = cumu !! n !! n
--curiously, the following seems to be faster
--sums = sum . (rows!!)
main :: IO ()
main = do
mapM_ print $ take 10 rows
mapM_ (print.sums) [23, 123, 1234, 12345] |
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
| #ANTLR | ANTLR |
static Integer sumOfTwoNums(Integer A, Integer B) {
return A + B;
}
System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25));
'''Output'''
A = 50 and B = 25: 75
A = -50 and B = 25: -25
A = -50 and B = -25: -75
A = 50 and B = -25: 25
|
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.
| #REXX | REXX | require 'abstraction'
class AbstractQueue
abstract
def enqueue(object)
raise NotImplementedError
end
def dequeue
raise NotImplementedError
end
end
class ConcreteQueue < AbstractQueue
def enqueue(object)
puts "enqueue #{object.inspect}"
end
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.
| #Ruby | Ruby | require 'abstraction'
class AbstractQueue
abstract
def enqueue(object)
raise NotImplementedError
end
def dequeue
raise NotImplementedError
end
end
class ConcreteQueue < AbstractQueue
def enqueue(object)
puts "enqueue #{object.inspect}"
end
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Risc-V | Risc-V | ackermann: #x: a1, y: a2, return: a0
beqz a1, npe #case m = 0
beqz a2, mme #case m > 0 & n = 0
addi sp, sp, -8 #case m > 0 & n > 0
sw ra, 4(sp)
sw a1, 0(sp)
addi a2, a2, -1
jal ackermann
lw a1, 0(sp)
addi a1, a1, -1
mv a2, a0
jal ackermann
lw t0, 4(sp)
addi sp, sp, 8
jr t0, 0
npe:
addi a0, a2, 1
jr ra, 0
mme:
addi sp, sp, -4
sw ra, 0(sp)
addi a1, a1, -1
li a2, 1
jal ackermann
lw t0, 0(sp)
addi sp, sp, 4
jr t0, 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
| #Python | Python | def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
# Can't give true answer with unexpected number of entries
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
# Find the small slice length that gives list_size unique values
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7) |
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
| #BBC_BASIC | BBC BASIC | BLOCKS$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
PROCcan_make_word("A")
PROCcan_make_word("BARK")
PROCcan_make_word("BOOK")
PROCcan_make_word("TREAT")
PROCcan_make_word("COMMON")
PROCcan_make_word("SQUAD")
PROCcan_make_word("Confuse")
END
DEF PROCcan_make_word(word$)
LOCAL b$,p%
b$=BLOCKS$
PRINT word$ " -> ";
p%=INSTR(b$,CHR$(ASCword$ AND &DF))
WHILE p%>0 AND word$>""
MID$(b$,p%-1+(p% MOD 2),2)=".."
word$=MID$(word$,2)
p%=INSTR(b$,CHR$(ASCword$ AND &DF))
ENDWHILE
IF word$>"" PRINT "False" ELSE PRINT "True"
ENDPROC |
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)
| #Kotlin | Kotlin | fun divisors(n: Int): List<Int> {
val divs = mutableListOf(1)
val divs2 = mutableListOf<Int>()
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.add(i)
if (i != j) {
divs2.add(j)
}
}
i++
}
divs.addAll(divs2.reversed())
return divs
}
fun abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int {
var count = countFrom
var n = searchFrom
while (count < countTo) {
val divs = divisors(n)
val tot = divs.sum()
if (tot > n) {
count++
if (!printOne || count >= countTo) {
val s = divs.joinToString(" + ")
if (printOne) {
println("$n < $s = $tot")
} else {
println("%2d. %5d < %s = %d".format(count, n, s, tot))
}
}
}
n += 2
}
return n
}
fun main() {
val max = 25
println("The first $max abundant odd numbers are:")
val n = abundantOdd(1, 0, 25, false)
println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
println("\nThe first abundant odd number above one billion is:")
abundantOdd((1e9 + 1).toInt(), 0, 1, true)
} |
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).
| #AWK | AWK | # Game 21 - an example in AWK language for Rosseta Code.
BEGIN {
srand();
GOAL = 21;
best[0] = 1; best[1] = 1; best[2] = 3; best[3] = 2;
print\
"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";
newgame();
prompt();
}
/[123]/ {
move = strtonum($0);
if (move + total <= GOAL) {
update("human", strtonum($0));
update("ai", best[total % 4]);
}
else
invalid();
prompt();
}
/[^123]/ {
if ($0 == "quit") {
print "goodbye";
exit;
}
else {
invalid();
prompt();
}
}
function prompt(){
print "enter your choice (or type quit to exit): ";
}
function invalid(){
print "invalid move";
}
function newgame() {
print "\n---- NEW GAME ----\n";
print "\nThe running total is currently zero.\n";
total = 0;
if (rand() < 0.5) {
print "The first move is AI move.\n";
update("ai", best[total % 4]);
}
else
print "The first move is human move.\n";
}
function update(player, 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;
newgame();
}
} |
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
| #Common_Lisp | Common Lisp |
(defpackage four-rings
(:use common-lisp)
(:export display-solutions))
(in-package four-rings)
(defun correct-answer-p (a b c d e f g)
(let ((v (+ a b)))
(and (equal v (+ b c d))
(equal v (+ d e f))
(equal v (+ f g)))))
(defun combinations-if (func len unique min max)
(let ((results nil))
(labels ((inner (cur)
(if (eql (length cur) len)
(when (apply func (reverse cur))
(push cur results))
(dotimes (i (- max min))
(when (or (not unique)
(not (member (+ i min) cur)))
(inner (append (list (+ i min)) cur)))))))
(inner nil))
results))
(defun four-rings-solutions (low high unique)
(combinations-if #'correct-answer-p 7 unique low (1+ high)))
(defun display-solutions ()
(let ((letters '((a b c d e f g))))
(format t "Low 1, High 7, unique letters: ~%~{~{~3A~}~%~}~%"
(append letters (four-rings-solutions 1 7 t)))
(format t "Low 3, High 9, unique letters: ~%~{~{~3A~}~%~}~%"
(append letters (four-rings-solutions 3 9 t)))
(format t "Number of solutions for Low 0, High 9 non-unique:~%~A~%"
(length (four-rings-solutions 0 9 nil)))))
|
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
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
n := integer(!A) | 10
every r := 2 to (n+1) do write(right(r-1,2),": ",showList(row(r)))
write()
every r := 23 | 123 | 1234 | 12345 do write(r," ",cumu(r+1)[-1])
end
procedure cumu(n)
static cache
initial cache := [[1]]
every l := *cache to n do {
every (r := [0], x := !l) do put(r, r[-1]+cache[1+l-x][1+min(x,l-x)])
put(cache, r)
}
return cache[n]
end
procedure row(n)
return (r := cumu(n), [: (i := !(*r-1), r[i+1]-r[i]) :]) | r
end
procedure showList(A)
every (s := "[") ||:= (!A||", ")
return s[1:-2]||"]"
end |
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
| #Apex | Apex |
static Integer sumOfTwoNums(Integer A, Integer B) {
return A + B;
}
System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25));
'''Output'''
A = 50 and B = 25: 75
A = -50 and B = 25: -25
A = -50 and B = -25: -75
A = 50 and B = -25: 25
|
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.
| #Rust | Rust | trait Shape {
fn area(self) -> i32;
} |
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.
| #Scala | Scala | abstract class X {
type A
var B: A
val C: A
def D(a: A): A
}
trait Y {
val x: X
} |
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.
| #Ruby | Ruby | def ack(m, n)
if m == 0
n + 1
elsif n == 0
ack(m-1, 1)
else
ack(m-1, ack(m, n-1))
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
| #Racket | Racket | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5))) |
Subsets and Splits