task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
0 40 repeat var gap
( "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
"are$delineated$by$a$single$'dollar'$character,$write$a$program"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
"column$are$separated$by$at$least$one$space."
"Further,$allow$for$each$word$in$a$column$to$be$either$left$"
"justified,$right$justified,$or$center$justified$within$its$column." )
len var lines
def alignWords /# -1/0/1 for left/center/right #/
>ps
lines for
get len for >ps
tps get gap ps> get nip 1 +
tps -1 == if -1 * align else
tps 0 == if tostr align else
tps 1 == if align else
drop drop "Wrong!" exitfor
endif endif endif
print
endfor
drop
nl
endfor
ps> drop
enddef
lines for var i
i get "$" " " subst split
len for var j
j get len dup
gap j get rot
< if swap j set else swap drop endif var gap drop
endfor
i set
endfor
-1 alignWords nl
0 alignWords nl
1 alignWords nl
drop |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Red | Red | Red []
m: make map! [] 25000
maxx: 0
foreach word read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt [
sword: sort copy word ;; sorted characters of word
either find m sword [
append m/:sword word
maxx: max maxx length? m/:sword
] [
put m sword append copy [] word
]
]
foreach v values-of m [ if maxx = length? v [print v] ]
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Factor | Factor | USING: kernel math locals combinators ;
IN: ackermann
:: ackermann ( m n -- u )
{
{ [ m 0 = ] [ n 1 + ] }
{ [ n 0 = ] [ m 1 - 1 ackermann ] }
[ m 1 - m n 1 - ackermann ackermann ]
} cond ; |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Racket | Racket | #lang racket
(require math)
(define (proper-divisors n) (drop-right (divisors n) 1))
(define classes '(deficient perfect abundant))
(define (classify n)
(list-ref classes (add1 (sgn (- (apply + (proper-divisors n)) n)))))
(let ([N 20000])
(define t (make-hasheq))
(for ([i (in-range 1 (add1 N))])
(define c (classify i))
(hash-set! t c (add1 (hash-ref t c 0))))
(printf "The range between 1 and ~a has:\n" N)
(for ([c classes]) (printf " ~a ~a numbers\n" (hash-ref t c 0) c))) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PHP | PHP | <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
/**
Justify columns of textual tabular input where the record separator is the newline
and the field separator is a 'dollar' character.
justification can be L, R, or C; (Left, Right, or Centered).
Return the justified output as a string
*/
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = array();
foreach (explode("\n", $str) as $line)
$fieldsbyrow[] = explode('$', $line);
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
$result = '';
foreach ($fieldsbyrow as $fields)
$result .= implode(' ', $fields) . "\n";
return $result;
}
$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
foreach (array('L', 'R', 'C') as $j)
echo aligner($textinfile, $j);
?> |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX | /*REXX program finds words with the largest set of anagrams (of the same size). */
iFID= 'unixdict.txt' /*the dictionary input File IDentifier.*/
$=; !.=; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/
/* [↓] read the entire file (by lines)*/
do while lines(iFID) \== 0 /*Got any data? Then read a record. */
parse value linein(iFID) with @ . /*obtain a word from an input line. */
len=length(@); if len<3 then iterate /*onesies and twosies words can't win. */
if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */
uw=uw + 1 /*count of the (useable) words in file.*/
_=sortA(@) /*sort the letters in the word. */
!._=!._ @; #=words(!._) /*append it to !._; bump the counter. */
if #==most then $=$ _ /*append the sorted word──► max anagram*/
else if #>most then do; $=_; most=#; if len>ww then ww=len; end
end /*while*/ /*$ ◄── list of high count anagrams. */
say '─────────────────────────' uw "usable words in the dictionary file: " iFID
say
do m=1 for words($); z=subword($, m, 1) /*the high count of the anagrams. */
say ' ' left(word(!.z, 1), ww) ' [anagrams: ' subword(!.z, 2)"]"
end /*m*/ /*W is the maximum width of any word.*/
say
say '───── Found' words($) "words (each of which have" words(!.z)-1 'anagrams).'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortA: arg char 2 xx,@. /*get the first letter of arg; @.=null*/
@.char=char /*no need to concatenate the first char*/
/*[↓] sort/put letters alphabetically.*/
do length(xx); parse var xx char 2 xx; @[email protected] || char; end
/*reassemble word with sorted letters. */
return @.a || @.b || @.c || @.d || @.e || @.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||,
@.n || @.o || @.p || @.q || @.r || @.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z |
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.
| #Falcon | Falcon | function ackermann( m, n )
if m == 0: return( n + 1 )
if n == 0: return( ackermann( m - 1, 1 ) )
return( ackermann( m - 1, ackermann( m, n - 1 ) ) )
end
for M in [ 0:4 ]
for N in [ 0:7 ]
>> ackermann( M, N ), " "
end
>
end |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Raku | Raku | sub propdivsum (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
sum @l
}
say bag (1..20000).map: { propdivsum($_) <=> $_ } |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Picat | Picat | import util.
main =>
Text =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.",
Lines = split(Text,"\n"),
Lines = [Line1|_],
N = len(split(strip(Line1,"$ "), "$")), % number of columns
WidthArr = {0 : _ in 1..N},
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
WidthArr[I] := max(WidthArr[I], len(Word))
end
end,
foreach (I in 1..N)
WidthArr[I] := WidthArr[I]+1 % separate cols by at least one space
end,
foreach (Align in [left, right, center])
output_lines(Lines,N,WidthArr,Align),
nl,nl
end.
output_lines(Lines,N,WidthArr,Align) =>
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
output_word(Word,WidthArr[I],Align)
end,
nl
end.
output_word(Word,Width,left) =>
printf("%-*s",Width,Word).
output_word(Word,Width,right) =>
printf("%*s",Width,Word).
output_word(Word,Width,_) =>
Pad = len(Word)-Width,
Pad1 is Pad div 2,
Pad2 is Pad-Pad1,
printf("%*s%s%*s",Pad1,"",Word,Pad2,"").
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ring | Ring |
# Project : Anagrams
load "stdlib.ring"
fn1 = "unixdict.txt"
fp = fopen(fn1,"r")
str = fread(fp, getFileSize(fp))
fclose(fp)
strlist = str2list(str)
anagram = newlist(len(strlist), 5)
anag = list(len(strlist))
result = list(len(strlist))
for x = 1 to len(result)
result[x] = 0
next
for x = 1 to len(anag)
anag[x] = 0
next
for x = 1 to len(anagram)
for y = 1 to 5
anagram[x][y] = 0
next
next
for n = 1 to len(strlist)
for m = 1 to len(strlist)
sum = 0
if len(strlist[n]) = 4 and len(strlist[m]) = 4 and n != m
for p = 1 to len(strlist[m])
temp1 = count(strlist[n], strlist[m][p])
temp2 = count(strlist[m], strlist[m][p])
if temp1 = temp2
sum = sum + 1
ok
next
if sum = 4
anag[n] = anag[n] + 1
if anag[n] < 6 and result[n] = 0 and result[m] = 0
anagram[n][anag[n]] = strlist[m]
result[m] = 1
ok
ok
ok
next
if anag[n] > 0
result[n] = 1
ok
next
for n = 1 to len(anagram)
flag = 0
for m = 1 to 5
if anagram[n][m] != 0
if m = 1
see strlist[n] + " "
flag = 1
ok
see anagram[n][m] + " "
ok
next
if flag = 1
see nl
ok
next
func getFileSize fp
c_filestart = 0
c_fileend = 2
fseek(fp,0,c_fileend)
nfilesize = ftell(fp)
fseek(fp,0,c_filestart)
return nfilesize
func count(astring,bstring)
cnt = 0
while substr(astring,bstring) > 0
cnt = cnt + 1
astring = substr(astring,substr(astring,bstring)+len(string(sum)))
end
return cnt
|
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.
| #FALSE | FALSE | [$$[%
\$$[%
1-\$@@a;! { i j -> A(i-1, A(i, j-1)) }
1]?0=[
%1 { i 0 -> A(i-1, 1) }
]?
\1-a;!
1]?0=[
%1+ { 0 j -> j+1 }
]?]a: { j i }
3 3 a;! . { 61 } |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #REXX | REXX | /*REXX program counts the number of abundant/deficient/perfect numbers within a range.*/
parse arg low high . /*obtain optional arguments from the CL*/
high=word(high low 20000,1); low= word(low 1,1) /*obtain the LOW and HIGH values.*/
say center('integers from ' low " to " high, 45, "═") /*display a header.*/
!.= 0 /*define all types of sums to zero. */
do j=low to high; $= sigma(j) /*get sigma for an integer in a range. */
if $<j then !.d= !.d + 1 /*Less? It's a deficient number.*/
else if $>j then !.a= !.a + 1 /*Greater? " " abundant " */
else !.p= !.p + 1 /*Equal? " " perfect " */
end /*j*/ /* [↑] IFs are coded as per likelihood*/
say ' the number of perfect numbers: ' right(!.p, length(high) )
say ' the number of abundant numbers: ' right(!.a, length(high) )
say ' the number of deficient numbers: ' right(!.d, length(high) )
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sigma: procedure; parse arg x; if x<2 then return 0; odd=x // 2 /* // ◄──remainder.*/
s= 1 /* [↓] only use EVEN or ODD integers.*/
do k=2+odd by 1+odd while k*k<x /*divide by all integers up to √x. */
if x//k==0 then s= s + k + x % k /*add the two divisors to (sigma) sum. */
end /*k*/ /* [↑] % is the REXX integer division*/
if k*k==x then return s + k /*Was X a square? If so, add √ x */
return s /*return (sigma) sum of the divisors. */ |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | (let Sizes NIL # Build a list of sizes
(let Lines # and of lines
(make
(in "input.txt" # Reading input file
(while (split (line) "$") # delimited by '$'
(let (L (link (mapcar pack @)) S Sizes)
(setq Sizes # Maintain sizes
(make
(while (or L S)
(link
(max
(inc (length (pop 'L)))
(pop 'S) ) ) ) ) ) ) ) ) )
(for L Lines # Print lines
(prinl (apply align L (mapcar - Sizes))) ) # left aligned
(prinl)
(for L Lines
(prinl (apply align L Sizes)) ) # right aligned
(prinl)
(for L Lines
(prinl (apply center L Sizes)) ) ) ) # and centered |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ruby | Ruby | require 'open-uri'
anagram = Hash.new {|hash, key| hash[key] = []} # map sorted chars to anagrams
URI.open('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
words = f.read.split
for word in words
anagram[word.split('').sort] << word
end
end
count = anagram.values.map {|ana| ana.length}.max
anagram.each_value do |ana|
if ana.length >= count
p ana
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.
| #Fantom | Fantom | class Main
{
// assuming m,n are positive
static Int ackermann (Int m, Int n)
{
if (m == 0)
return n + 1
else if (n == 0)
return ackermann (m - 1, 1)
else
return ackermann (m - 1, ackermann (m, n - 1))
}
public static Void main ()
{
(0..3).each |m|
{
(0..6).each |n|
{
echo ("Ackerman($m, $n) = ${ackermann(m, n)}")
}
}
}
} |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Ring | Ring |
n = 30
perfect(n)
func perfect n
for i = 1 to n
sum = 0
for j = 1 to i - 1
if i % j = 0 sum = sum + j ok
next
see i
if sum = i see " is a perfect number" + nl
but sum < i see " is a deficient number" + nl
else see " is a abundant number" + nl ok
next
|
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Ruby | Ruby | res = (1 .. 20_000).map{|n| n.proper_divisors.sum <=> n }.tally
puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}"
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FI | PL/I |
declare text character (300) varying;
declare word character (20) varying;
declare justification character (1);
declare k fixed binary;
declare input file, output file output;
open file (input) title ( '/CENTER.DAT,type(text),recsize(1000)' );
open file (output) title ( '/OUT.TXT,type(text),recsize(1000)' );
on endfile (input) stop;
display ('Specify whether justification is left, centered, or right');
display ('Reply with a single letter: L, C, or R');
get edit (justification) (A(1));
do forever;
get file (input) edit (text) (L);
put skip list (text);
text = trim(text, '$', '$');
do until (k = 0);
k = index(text, '$');
if k = 0 then /* last word in line */
word = text;
else
do;
word = substr(text, 1, k-1);
text = substr(text, k);
text = trim(text, '$');
end;
select (justification);
when ('C', 'c') word = center(word, maxlength(word));
when ('R', 'r') word = right (word, maxlength(word));
otherwise ; /* The default is left adjusted. */
end;
put file (output) edit (word) (a(maxlength(word)));
end;
put file (output) skip;
end;
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:"
mem$ = "CREATE TABLE anti(gram,ordr);
CREATE INDEX ord ON anti(ordr)"
#mem execute(mem$)
' read the file
a$ = httpGet$("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
' break the file words apart
i = 1
while i <> 0
j = instr(a$,chr$(10),i+1)
if j = 0 then exit while
a1$ = mid$(a$,i,j-i)
q = instr(a1$,"'")
if q > 0 then a1$ = left$(a1$,q) + mid$(a1$,q)
ln = len(a1$)
s$ = a1$
' Split the characters of the word and sort them
s = 1
while s = 1
s = 0
for k = 1 to ln -1
if mid$(s$,k,1) > mid$(s$,k+1,1) then
h$ = mid$(s$,k,1)
h1$ = mid$(s$,k+1,1)
s$ = left$(s$,k-1) + h1$ + h$ + mid$(s$,k+2)
s = 1
end if
next k
wend
mem$ = "INSERT INTO anti VALUES('";a1$;"','";ord$;"')"
#mem execute(mem$)
i = j +1
wend
' find all antigrams
mem$ = "SELECT count(*) as cnt,anti.ordr FROM anti GROUP BY ordr ORDER BY cnt desc"
#mem execute(mem$)
numDups = #mem ROWCOUNT() 'Get the number of rows
dim dups$(numDups)
for i = 1 to numDups
#row = #mem #nextrow()
cnt = #row cnt()
if i = 1 then maxCnt = cnt
if cnt < maxCnt then exit for
dups$(i) = #row ordr$()
next i
for i = 1 to i -1
mem$ = "SELECT anti.gram FROM anti
WHERE anti.ordr = '";dups$(i);"'
ORDER BY anti.gram"
#mem execute(mem$)
rows = #mem ROWCOUNT() 'Get the number of rows
for ii = 1 to rows
#row = #mem #nextrow()
gram$ = #row gram$()
print gram$;chr$(9);
next ii
print
next i
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
TestAckermann()
PAUSE
SUB TestAckermann()
FOR DIM m = 0 TO 3
FOR DIM n = 0 TO 10
PRINT AckermannF(m, n), " ";
NEXT
PRINT
NEXT
END SUB
FUNCTION AckermannF(m AS INTEGER, n AS INTEGER) AS INTEGER
IF NOT m THEN RETURN n + 1
IF NOT n THEN RETURN AckermannA(m - 1, 1)
RETURN AckermannC(m - 1, AckermannF(m, n - 1))
END FUNCTION
DYNC AckermannC(m AS INTEGER, n AS INTEGER) AS INTEGER |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Rust | Rust | fn main() {
// deficient starts at 1 because 1 is deficient but proper_divisors returns
// and empty Vec
let (mut abundant, mut deficient, mut perfect) = (0u32, 1u32, 0u32);
for i in 1..20_001 {
if let Some(divisors) = i.proper_divisors() {
let sum: u64 = divisors.iter().sum();
if sum < i {
deficient += 1
} else if sum > i {
abundant += 1
} else {
perfect += 1
}
}
}
println!("deficient:\t{:5}\nperfect:\t{:5}\nabundant:\t{:5}",
deficient, perfect, abundant);
}
|
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Scala | Scala | def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
def classifier(i: Int) = properDivisors(i).sum compare i
val groups = (1 to 20000).groupBy( classifier )
println("Deficient: " + groups(-1).length)
println("Abundant: " + groups(1).length)
println("Perfect: " + groups(0).length + " (" + groups(0).mkString(",") + ")") |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PowerShell | PowerShell |
$file =
@'
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
'@.Split("`n")
$arr = @()
$file | foreach {
$line = $_
$i = 0
$hash = [ordered]@{}
$line.split('$') | foreach{
$hash["$i"] = "$_"
$i++
}
$arr += @([pscustomobject]$hash)
}
$arr | Format-Table -HideTableHeaders -Wrap *
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead,BufReader};
use std::borrow::ToOwned;
extern crate unicode_segmentation;
use unicode_segmentation::{UnicodeSegmentation};
fn main () {
let file = BufReader::new(File::open("unixdict.txt").unwrap());
let mut map = HashMap::new();
for line in file.lines() {
let s = line.unwrap();
//Bytes: let mut sorted = s.trim().bytes().collect::<Vec<_>>();
//Codepoints: let mut sorted = s.trim().chars().collect::<Vec<_>>();
let mut sorted = s.trim().graphemes(true).map(ToOwned::to_owned).collect::<Vec<_>>();
sorted.sort();
map.entry(sorted).or_insert_with(Vec::new).push(s);
}
if let Some(max_len) = map.values().map(|v| v.len()).max() {
for anagram in map.values().filter(|v| v.len() == max_len) {
for word in anagram {
print!("{} ", word);
}
println!();
}
}
} |
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.
| #Fermat | Fermat | Func A(m,n) = if m = 0 then n+1 else if n = 0 then A(m-1,1) else A(m-1,A(m,n-1)) fi fi.;
A(3,8) |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Scheme | Scheme |
(define (classify n)
(define (sum_of_factors x)
(cond ((= x 1) 1)
((= (remainder n x) 0) (+ x (sum_of_factors (- x 1))))
(else (sum_of_factors (- x 1)))))
(cond ((or (= n 1) (< (sum_of_factors (floor (/ n 2))) n)) -1)
((= (sum_of_factors (floor (/ n 2))) n) 0)
(else 1)))
(define n_perfect 0)
(define n_abundant 0)
(define n_deficient 0)
(define (count n)
(cond ((= n 1) (begin (display "perfect ")
(display n_perfect)
(newline)
(display "abundant")
(display n_abundant)
(newline)
(display "deficinet")
(display n_perfect)
(newline)))
((equal? (classify n) 0) (begin (set! n_perfect (+ 1 n_perfect)) (display n) (newline) (count (- n 1))))
((equal? (classify n) 1) (begin (set! n_abundant (+ 1 n_abundant)) (count (- n 1))))
((equal? (classify n) -1) (begin (set! n_deficient (+ 1 n_deficient)) (count (- n 1))))))
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Prolog | Prolog | aligner :-
L ="Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.",
% read the lines and the words
% compute the length of the longuest word.
% LP is the list of lines,
% each line is a list of words
parse(L, 0, N, LP, []),
% we need to add 1 to aligned
N1 is N+1,
% words will be left aligned
sformat(AL, '~~w~~t~~~w|', [N1]),
% words will be centered
sformat(AC, '~~t~~w~~t~~~w|', [N1]),
% words will be right aligned
sformat(AR, '~~t~~w~~~w|', [N1]),
write('Left justified :'), nl,
maplist(affiche(AL), LP), nl,
write('Centered justified :'), nl,
maplist(affiche(AC), LP), nl,
write('Right justified :'), nl,
maplist(affiche(AR), LP), nl.
affiche(F, L) :-
maplist(my_format(F), L),
nl.
my_format(_F, [13]) :-
nl.
my_format(F, W) :-
string_to_atom(W,AW),
sformat(AF, F, [AW]),
write(AF).
parse([], Max, Max) --> [].
parse(T, N, Max) -->
{ parse_line(T, 0, N1, T1, L, []),
( N1 > N -> N2 = N1; N2 = N)},
[L],
parse(T1, N2, Max).
parse_line([], NF, NF, []) --> [].
parse_line([H|TF], NF, NF, TF) -->
{code_type(H, end_of_line), !},
[].
parse_line(T, N, NF, TF) -->
{ parse_word(T, 0, N1, T1, W, []),
( N1 > N -> N2 = N1; N2 = N)},
[W],
parse_line(T1, N2, NF, TF).
% 36 is the code of '$'
parse_word([36|T], N, N, T) -->
{!},
[].
parse_word([H|T], N, N, [H|T]) -->
{code_type(H, end_of_line), !},
[].
parse_word([], N, N, []) --> [].
parse_word([H|T], N1, NF, TF) -->
[H],
{N2 is N1 + 1},
parse_word(T, N2, NF, TF).
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | val src = io.Source fromURL "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
val vls = src.getLines.toList.groupBy(_.sorted).values
val max = vls.map(_.size).max
vls filter (_.size == max) map (_ mkString " ") mkString "\n" |
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.
| #Forth | Forth | : acker ( m n -- u )
over 0= IF nip 1+ EXIT THEN
swap 1- swap ( m-1 n -- )
dup 0= IF 1+ recurse EXIT THEN
1- over 1+ swap recurse recurse ; |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: sumProperDivisors (in integer: number) is func
result
var integer: sum is 0;
local
var integer: num is 0;
begin
if number >= 2 then
for num range 1 to number div 2 do
if number rem num = 0 then
sum +:= num;
end if;
end for;
end if;
end func;
const proc: main is func
local
var integer: sum is 0;
var integer: deficient is 0;
var integer: perfect is 0;
var integer: abundant is 0;
var integer: number is 0;
begin
for number range 1 to 20000 do
sum := sumProperDivisors(number);
if sum < number then
incr(deficient);
elsif sum = number then
incr(perfect);
else
incr(abundant);
end if;
end for;
writeln("Deficient: " <& deficient);
writeln("Perfect: " <& perfect);
writeln("Abundant: " <& abundant);
end func; |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Sidef | Sidef | func propdivsum(n) { n.sigma - n }
var h = Hash()
{|i| ++(h{propdivsum(i) <=> i} := 0) } << 1..20000
say "Perfect: #{h{0}} Deficient: #{h{-1}} Abundant: #{h{1}}" |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic | Declare max(a,b)
If OpenConsole()
Define a, i, x, y, maxlen
Dim txt.s(0)
Restore lines ; Get address of the first data block
Read.i a
ReDim txt(a)
For i=0 To a ; Read the raw data lines
Read.s txt(i)
txt(i)=Trim(txt(i),"$") ; Remove any bad '$' that may be useless in the end...
x=max(CountString(txt(i),"$"),x)
Next
y=a
Dim matrix.s(x,y) ; Set up a nice matrix to work with, each word cleanly separated
For x=0 To ArraySize(matrix(),1)
For y=0 To ArraySize(matrix(),2)
matrix(x,y)=StringField(txt(y),x+1,"$")
maxlen=max(maxlen,Len(matrix(x,y)))
Next
Next
If maxlen%2
maxlen+1 ; Just to make sure that 'centered' output looks nice....
EndIf
PrintN(#CRLF$+"---- Right ----")
For y=0 To ArraySize(matrix(),2)
For x=0 To ArraySize(matrix(),1)
Print(RSet(matrix(x,y),maxlen+1))
Next
PrintN("")
Next
PrintN(#CRLF$+"---- Left ----")
For y=0 To ArraySize(matrix(),2)
For x=0 To ArraySize(matrix(),1)
Print(LSet(matrix(x,y),maxlen+1))
Next
PrintN("")
Next
PrintN(#CRLF$+"---- Center ----")
For y=0 To ArraySize(matrix(),2)
For x=0 To ArraySize(matrix(),1)
a=maxlen-Len(matrix(x,y))
Print(LSet(RSet(matrix(x,y),maxlen-a/2),maxlen))
Next
PrintN("")
Next
PrintN(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
CloseConsole()
EndIf
Procedure max(x,y)
If x>=y
ProcedureReturn x
Else
ProcedureReturn y
EndIf
EndProcedure
DataSection
lines:
Data.i 5 ; e.g. 6-1 since first line is equal to 'zero'.
text:
Data.s "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Data.s "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Data.s "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
Data.s "column$are$separated$by$at$least$one$space."
Data.s "Further,$allow$for$each$word$in$a$column$oo$be$either$left$"
Data.s "justified,$right$justified,$or$center$justified$within$its$column."
EndDataSection |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scheme | Scheme |
(import (scheme base)
(scheme char)
(scheme file)
(scheme write)
(srfi 125) ; hash tables
(srfi 132)) ; sorting library
;; read in the words
(define (read-groups)
(with-input-from-file
"unixdict.txt"
(lambda ()
(let ((groups (hash-table string=?)))
(do ((line (read-line) (read-line)))
((eof-object? line) groups)
(let* ((key (list->string (list-sort char<? (string->list line))))
(val (hash-table-ref/default groups key '())))
(hash-table-set! groups key (cons line val))))))))
;; extract the longest values from given hash-table of groups
(define (largest-groups groups)
(define (find-largest grps n sofar)
(cond ((null? grps)
sofar)
((> (length (car grps)) n)
(find-largest (cdr grps) (length (car grps)) (list (car grps))))
((= (length (car grps)) n)
(find-largest (cdr grps) n (cons (car grps) sofar)))
(else
(find-largest (cdr grps) n sofar))))
(find-largest (hash-table-values groups) 0 '()))
;; print results
(for-each
(lambda (group)
(display "[ ")
(for-each (lambda (word) (display word) (display " ")) group)
(display "]\n"))
(list-sort (lambda (a b) (string<? (car a) (car b)))
(map (lambda (grp) (list-sort string<? grp))
(largest-groups (read-groups)))))
|
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.
| #Fortran | Fortran | PROGRAM EXAMPLE
IMPLICIT NONE
INTEGER :: i, j
DO i = 0, 3
DO j = 0, 6
WRITE(*, "(I10)", ADVANCE="NO") Ackermann(i, j)
END DO
WRITE(*,*)
END DO
CONTAINS
RECURSIVE FUNCTION Ackermann(m, n) RESULT(ack)
INTEGER :: ack, m, n
IF (m == 0) THEN
ack = n + 1
ELSE IF (n == 0) THEN
ack = Ackermann(m - 1, 1)
ELSE
ack = Ackermann(m - 1, Ackermann(m, n - 1))
END IF
END FUNCTION Ackermann
END PROGRAM EXAMPLE |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Swift | Swift | var deficients = 0 // sumPd < n
var perfects = 0 // sumPd = n
var abundants = 0 // sumPd > n
// 1 is deficient (no proper divisor)
deficients++
for i in 2...20000 {
var sumPd = 1 // 1 is a proper divisor of all integer above 1
var maxPdToTest = i/2 // the max divisor to test
for var j = 2; j < maxPdToTest; j++ {
if (i%j) == 0 {
// j is a proper divisor
sumPd += j
// New maximum for divisibility check
maxPdToTest = i / j
// To add to sum of proper divisors unless already done
if maxPdToTest != j {
sumPd += maxPdToTest
}
}
}
// Select type according to sum of Proper divisors
if sumPd < i {
deficients++
} else if sumPd > i {
abundants++
} else {
perfects++
}
}
println("There are \(deficients) deficient, \(perfects) perfect and \(abundants) abundant integers from 1 to 20000.") |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Tcl | Tcl | proc ProperDivisors {n} {
if {$n == 1} {return 0}
set divs 1
set sum 1
for {set i 2} {$i*$i <= $n} {incr i} {
if {! ($n % $i)} {
lappend divs $i
incr sum $i
if {$i*$i<$n} {
lappend divs [set d [expr {$n / $i}]]
incr sum $d
}
}
}
list $sum $divs
}
proc cmp {i j} { ;# analogous to [string compare], but for numbers
if {$i == $j} {return 0}
if {$i > $j} {return 1}
return -1
}
proc classify {k} {
lassign [ProperDivisors $k] p ;# we only care about the first part of the result
dict get {
1 abundant
0 perfect
-1 deficient
} [cmp $k $p]
}
puts "Classifying the integers in \[1, 20_000\]:"
set classes {} ;# this will be a dict
for {set i 1} {$i <= 20000} {incr i} {
set class [classify $i]
dict incr classes $class
}
# using [lsort] to order the dictionary by value:
foreach {kind count} [lsort -stride 2 -index 1 -integer $classes] {
puts "$kind: $count"
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | from itertools import zip_longest
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."""
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "gethttp.s7i";
include "strifile.s7i";
const type: anagramHash is hash [string] array string;
const func string: sort (in string: stri) is func
result
var string: sortedStri is "";
local
var integer: i is 0;
var integer: j is 0;
var char: ch is ' ';
begin
sortedStri := stri;
for i range 1 to length(sortedStri) do
for j range succ(i) to length(sortedStri) do
if sortedStri[i] > sortedStri[j] then
ch := sortedStri[i];
sortedStri @:= [i] sortedStri[j];
sortedStri @:= [j] ch;
end if;
end for;
end for;
end func;
const proc: main is func
local
var file: dictFile is STD_NULL;
var string: word is "";
var string: sortedLetters is "";
var anagramHash: anagrams is anagramHash.value;
var integer: length is 0;
var integer: maxLength is 0;
begin
dictFile := openStrifile(getHttp("wiki.puzzlers.org/pub/wordlists/unixdict.txt"));
while hasNext(dictFile) do
readln(dictFile, word);
sortedLetters := sort(word);
if sortedLetters in anagrams then
anagrams[sortedLetters] &:= word;
else
anagrams @:= [sortedLetters] [] (word);
end if;
length := length(anagrams[sortedLetters]);
if length > maxLength then
maxLength := length;
end if;
end while;
close(dictFile);
for sortedLetters range sort(keys(anagrams)) do
if length(anagrams[sortedLetters]) = maxLength then
writeln(join(anagrams[sortedLetters], ", "));
end if;
end for;
end func; |
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.
| #Free_Pascal | Free Pascal | ' version 28-10-2016
' compile with: fbc -s console
' to do A(4, 2) the stack size needs to be increased
' compile with: fbc -s console -t 2000
Function ackerman (m As Long, n As Long) As Long
If m = 0 Then ackerman = n +1
If m > 0 Then
If n = 0 Then
ackerman = ackerman(m -1, 1)
Else
If n > 0 Then
ackerman = ackerman(m -1, ackerman(m, n -1))
End If
End If
End If
End Function
' ------=< MAIN >=------
Dim As Long m, n
Print
For m = 0 To 4
Print Using "###"; m;
For n = 0 To 10
' A(4, 1) or higher will run out of stack memory (default 1M)
' change n = 1 to n = 2 to calculate A(4, 2), increase stack!
If m = 4 And n = 1 Then Exit For
Print Using "######"; ackerman(m, n);
Next
Print
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #TypeScript | TypeScript | function integer_classification(){
var sum:number=0, i:number,j:number;
var try:number=0;
var number_list:number[]={1,0,0};
for(i=2;i<=20000;i++){
try=i/2;
sum=1;
for(j=2;j<try;j++){
if (i%j)
continue;
try=i/j;
sum+=j;
if (j!=try)
sum+=try;
}
if (sum<i){
number_list[d]++;
continue;
}
else if (sum>i){
number_list[a]++;
continue;
}
number_list[p]++;
}
console.log('There are '+number_list[d]+ ' deficient , ' + 'number_list[p] + ' perfect and '+ number_list[a]+ ' abundant numbers
between 1 and 20000');
}
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #q | q | text:(
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$";
"are$delineated$by$a$single$'dollar'$character,$write$a$program";
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$";
"column$are$separated$by$at$least$one$space.";
"Further,$allow$for$each$word$in$a$column$to$be$either$left$";
"justified,$right$justified,$or$center$justified$within$its$column." )
ta:{[aln;txt] / tabulate aligned
sl:(count'')s:"$"vs/:txt; / strings and their lengths
cw:{rl#\:max x@/:\:til max rl:count each x}sl; / cell widths
ps:$[aln=`R;-1-cw;1+cw]$''s; / padded strings
ps:$[aln=`C;(neg(cw-sl)div 2)rotate''ps;ps]; / center
1,[;"\n\n"]"\n"sv raze each ps; } / print |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SETL | SETL | h := open('unixdict.txt', "r");
anagrams := {};
while not eof(h) loop
geta(h, word);
if word = om or word = "" then
continue;
end if;
sorted := insertion_sort(word);
anagrams{sorted} with:= word;
end loop;
max_size := 0;
max_words := {};
for words = anagrams{sorted} loop
size := #words;
if size > max_size then
max_size := size;
max_words := {words};
elseif size = max_size then
max_words with:= words;
end if;
end loop;
for w in max_words loop
print(w);
end loop;
-- GNU SETL has no built-in sort()
procedure insertion_sort(A);
for i in [2..#A] loop
v := A(i);
j := i-1;
while j >= 1 and A(j) > v loop
A(j+1) := A(j);
j := j - 1;
end loop;
A(j+1) := v;
end loop;
return A;
end procedure; |
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.
| #FreeBASIC | FreeBASIC | ' version 28-10-2016
' compile with: fbc -s console
' to do A(4, 2) the stack size needs to be increased
' compile with: fbc -s console -t 2000
Function ackerman (m As Long, n As Long) As Long
If m = 0 Then ackerman = n +1
If m > 0 Then
If n = 0 Then
ackerman = ackerman(m -1, 1)
Else
If n > 0 Then
ackerman = ackerman(m -1, ackerman(m, n -1))
End If
End If
End If
End Function
' ------=< MAIN >=------
Dim As Long m, n
Print
For m = 0 To 4
Print Using "###"; m;
For n = 0 To 10
' A(4, 1) or higher will run out of stack memory (default 1M)
' change n = 1 to n = 2 to calculate A(4, 2), increase stack!
If m = 4 And n = 1 Then Exit For
Print Using "######"; ackerman(m, n);
Next
Print
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #uBasic.2F4tH | uBasic/4tH | P = 0 : D = 0 : A = 0
For n= 1 to 20000
s = FUNC(_SumDivisors(n))-n
If s = n Then P = P + 1
If s < n Then D = D + 1
If s > n Then A = A + 1
Next
Print "Perfect: ";P;" Deficient: ";D;" Abundant: ";A
End
' Return the least power of a@ that does not divide b@
_LeastPower Param(2)
Local(1)
c@ = a@
Do While (b@ % c@) = 0
c@ = c@ * a@
Loop
Return (c@)
' Return the sum of the proper divisors of a@
_SumDivisors Param(1)
Local(4)
b@ = a@
c@ = 1
' Handle two specially
d@ = FUNC(_LeastPower (2,b@))
c@ = c@ * (d@ - 1)
b@ = b@ / (d@ / 2)
' Handle odd factors
For e@ = 3 Step 2 While (e@*e@) < (b@+1)
d@ = FUNC(_LeastPower (e@,b@))
c@ = c@ * ((d@ - 1) / (e@ - 1))
b@ = b@ / (d@ / e@)
Loop
' At this point, t must be one or prime
If (b@ > 1) c@ = c@ * (b@+1)
Return (c@) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #R | R | # Read in text
lines <- readLines(tc <- textConnection("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.")); close(tc)
#Split words by the dollar
words <- strsplit(lines, "\\$")
#Reformat
maxlen <- max(sapply(words, length))
words <- lapply(words, function(x) {length(x) <- maxlen; x})
block <- matrix(unlist(words), byrow=TRUE, ncol=maxlen)
block[is.na(block)] <- ""
leftjust <- format(block)
rightjust <- format(block, justify="right")
centrejust <- format(block, justify="centre")
# Print
print0 <- function(x) invisible(apply(x, 1, function(x) cat(x, "\n")))
print0(leftjust)
print0(rightjust)
print0(centrejust) |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Sidef | Sidef | func main(file) {
file.open_r(\var fh, \var err) ->
|| die "Can't open file `#{file}' for reading: #{err}\n";
var vls = fh.words.group_by{.sort}.values;
var max = vls.map{.len}.max;
vls.grep{.len == max}.each{.join("\t").say};
}
main(%f'/tmp/unixdict.txt'); |
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.
| #FunL | FunL | def
ackermann( 0, n ) = n + 1
ackermann( m, 0 ) = ackermann( m - 1, 1 )
ackermann( m, n ) = ackermann( m - 1, ackermann(m, n - 1) )
for m <- 0..3, n <- 0..4
printf( 'Ackermann( %d, %d ) = %d\n', m, n, ackermann(m, n) ) |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Vala | Vala | enum Classification {
DEFICIENT,
PERFECT,
ABUNDANT
}
void main() {
var i = 0; var j = 0;
var sum = 0; var try_max = 0;
int[] count_list = {1, 0, 0};
for (i = 2; i <= 20000; i++) {
try_max = i / 2;
sum = 1;
for (j = 2; j < try_max; j++) {
if (i % j != 0)
continue;
try_max = i / j;
sum += j;
if (j != try_max)
sum += try_max;
}
if (sum < i) {
count_list[Classification.DEFICIENT]++;
continue;
}
if (sum > i) {
count_list[Classification.ABUNDANT]++;
continue;
}
count_list[Classification.PERFECT]++;
}
print(@"There are $(count_list[Classification.DEFICIENT]) deficient,");
print(@" $(count_list[Classification.PERFECT]) perfect,");
print(@" $(count_list[Classification.ABUNDANT]) abundant numbers between 1 and 20000.\n");
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket |
#lang racket
(define (display-aligned text #:justify [justify 'left])
(define lines
(for/list ([line (regexp-split #rx"\n" text)])
(regexp-split #rx"\\$" line)))
(define width
(add1 (for*/fold ([m 0]) ([line lines] [word line])
(max m (string-length word)))))
(define spaces (make-string width #\space))
(for ([line lines])
(for* ([word line]
[strs (let ([spc (substring spaces (string-length word))])
(case justify
[(left) (list word spc)]
[(right) (list spc word)]
[(center) (let ([i (quotient (string-length spc) 2)])
(list (substring spc i)
word
(substring spc 0 i)))]))])
(display strs))
(newline)))
(define text
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.")
(display-aligned text)
(display-aligned #:justify 'right text)
(display-aligned #:justify 'center text)
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Simula | Simula | COMMENT COMPILE WITH
$ cim -m64 anagrams-hashmap.sim
;
BEGIN
COMMENT ----- CLASSES FOR GENERAL USE ;
! ABSTRACT HASH KEY TYPE ;
CLASS HASHKEY;
VIRTUAL:
PROCEDURE HASH IS
INTEGER PROCEDURE HASH;;
PROCEDURE EQUALTO IS
BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;;
BEGIN
END HASHKEY;
! ABSTRACT HASH VALUE TYPE ;
CLASS HASHVAL;
BEGIN
! THERE IS NOTHING REQUIRED FOR THE VALUE TYPE ;
END HASHVAL;
CLASS HASHMAP;
BEGIN
CLASS INNERHASHMAP(N); INTEGER N;
BEGIN
INTEGER PROCEDURE INDEX(K); REF(HASHKEY) K;
BEGIN
INTEGER I;
IF K == NONE THEN
ERROR("HASHMAP.INDEX: NONE IS NOT A VALID KEY");
I := MOD(K.HASH,N);
LOOP:
IF KEYTABLE(I) == NONE OR ELSE KEYTABLE(I).EQUALTO(K) THEN
INDEX := I
ELSE BEGIN
I := IF I+1 = N THEN 0 ELSE I+1;
GO TO LOOP;
END;
END INDEX;
! PUT SOMETHING IN ;
PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
BEGIN
INTEGER I;
IF V == NONE THEN
ERROR("HASHMAP.PUT: NONE IS NOT A VALID VALUE");
I := INDEX(K);
IF KEYTABLE(I) == NONE THEN BEGIN
IF SIZE = N THEN
ERROR("HASHMAP.PUT: TABLE FILLED COMPLETELY");
KEYTABLE(I) :- K;
VALTABLE(I) :- V;
SIZE := SIZE+1;
END ELSE
VALTABLE(I) :- V;
END PUT;
! GET SOMETHING OUT ;
REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
BEGIN
INTEGER I;
IF K == NONE THEN
ERROR("HASHMAP.GET: NONE IS NOT A VALID KEY");
I := INDEX(K);
IF KEYTABLE(I) == NONE THEN
GET :- NONE ! ERROR("HASHMAP.GET: KEY NOT FOUND");
ELSE
GET :- VALTABLE(I);
END GET;
PROCEDURE CLEAR;
BEGIN
INTEGER I;
FOR I := 0 STEP 1 UNTIL N-1 DO BEGIN
KEYTABLE(I) :- NONE;
VALTABLE(I) :- NONE;
END;
SIZE := 0;
END CLEAR;
! DATA MEMBERS OF CLASS HASHMAP ;
REF(HASHKEY) ARRAY KEYTABLE(0:N-1);
REF(HASHVAL) ARRAY VALTABLE(0:N-1);
INTEGER SIZE;
END INNERHASHMAP;
PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
BEGIN
IF IMAP.SIZE >= 0.75 * IMAP.N THEN
BEGIN
COMMENT RESIZE HASHMAP ;
REF(INNERHASHMAP) NEWIMAP;
REF(ITERATOR) IT;
NEWIMAP :- NEW INNERHASHMAP(2 * IMAP.N);
IT :- NEW ITERATOR(THIS HASHMAP);
WHILE IT.MORE DO
BEGIN
REF(HASHKEY) KEY;
KEY :- IT.NEXT;
NEWIMAP.PUT(KEY, IMAP.GET(KEY));
END;
IMAP.CLEAR;
IMAP :- NEWIMAP;
END;
IMAP.PUT(K, V);
END;
REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
GET :- IMAP.GET(K);
PROCEDURE CLEAR;
IMAP.CLEAR;
INTEGER PROCEDURE SIZE;
SIZE := IMAP.SIZE;
REF(INNERHASHMAP) IMAP;
IMAP :- NEW INNERHASHMAP(16);
END HASHMAP;
CLASS ITERATOR(H); REF(HASHMAP) H;
BEGIN
INTEGER POS,KEYCOUNT;
BOOLEAN PROCEDURE MORE;
MORE := KEYCOUNT < H.SIZE;
REF(HASHKEY) PROCEDURE NEXT;
BEGIN
INSPECT H.IMAP DO
BEGIN
WHILE KEYTABLE(POS) == NONE DO
POS := POS+1;
NEXT :- KEYTABLE(POS);
KEYCOUNT := KEYCOUNT+1;
POS := POS+1;
END;
END NEXT;
END ITERATOR;
COMMENT ----- PROBLEM SPECIFIC CLASSES ;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
BEGIN
INTEGER PROCEDURE HASH;
BEGIN
INTEGER I;
T.SETPOS(1);
WHILE T.MORE DO
I := 31*I+RANK(T.GETCHAR);
HASH := I;
END HASH;
BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;
EQUALTO := T = K QUA TEXTHASHKEY.T;
END TEXTHASHKEY;
HASHVAL CLASS TEXTVECTOR;
BEGIN
CLASS ARRAYHOLDER(N); INTEGER N;
BEGIN
TEXT ARRAY DATA(1:N);
END ARRAYHOLDER;
REF(ARRAYHOLDER) HOLDER;
INTEGER SIZE;
PROCEDURE DOUBLESIZE;
BEGIN
REF(ARRAYHOLDER) NEWHOLDER;
INTEGER I;
NEWHOLDER :- NEW ARRAYHOLDER(2 * HOLDER.N);
FOR I := 1 STEP 1 UNTIL HOLDER.N DO
NEWHOLDER.DATA(I) :- HOLDER.DATA(I);
HOLDER :- NEWHOLDER;
END;
PROCEDURE ADD(WORD); TEXT WORD;
BEGIN
SIZE := SIZE + 1;
IF SIZE > HOLDER.N THEN
DOUBLESIZE;
HOLDER.DATA(SIZE) :- WORD;
END;
HOLDER :- NEW ARRAYHOLDER(16);
END TEXTVECTOR;
TEXT PROCEDURE MAKEKEY(WORD); TEXT WORD;
BEGIN
TEXT KEY;
INTEGER I;
KEY :- BLANKS(WORD.LENGTH);
KEY.SETPOS(1);
FOR I := RANK('a') STEP 1 UNTIL RANK('z'),
RANK('0') STEP 1 UNTIL RANK('9') DO
BEGIN
WORD.SETPOS(1);
WHILE WORD.MORE DO
IF WORD.GETCHAR = CHAR(I) THEN
KEY.PUTCHAR(CHAR(I));
END;
MAKEKEY :- KEY;
END MAKEKEY;
REF(INFILE) INF;
REF(HASHMAP) MAP;
REF(HASHKEY) KEY;
REF(TEXTVECTOR) TVEC;
REF(ITERATOR) IT;
TEXT WORD;
INTEGER I, J, LONGEST;
MAP :- NEW HASHMAP;
INF :- NEW INFILE("unixdict.txt");
INF.OPEN(BLANKS(132));
WHILE NOT INF.LASTITEM DO
BEGIN
WORD :- COPY(INF.IMAGE).STRIP; INF.INIMAGE;
KEY :- NEW TEXTHASHKEY(MAKEKEY(WORD));
TVEC :- MAP.GET(KEY);
IF TVEC == NONE THEN
BEGIN
TVEC :- NEW TEXTVECTOR;
MAP.PUT(KEY, TVEC);
END;
TVEC.ADD(WORD);
END;
INF.CLOSE;
COMMENT FIND LONGEST ENTRIES ;
IT :- NEW ITERATOR(MAP);
WHILE IT.MORE DO
BEGIN
TVEC :- MAP.GET(IT.NEXT);
IF TVEC.SIZE > LONGEST THEN
LONGEST := TVEC.SIZE;
END;
COMMENT OUTPUT LONGEST ENTRIES ;
IT :- NEW ITERATOR(MAP);
WHILE IT.MORE DO
BEGIN
KEY :- IT.NEXT;
TVEC :- MAP.GET(KEY);
IF TVEC.SIZE = LONGEST THEN
BEGIN
OUTTEXT(KEY QUA TEXTHASHKEY.T);
OUTTEXT(":");
FOR J := 1 STEP 1 UNTIL TVEC.SIZE DO
INSPECT TVEC.HOLDER DO
BEGIN
OUTCHAR(' ');
OUTTEXT(DATA(J));
END;
OUTIMAGE;
END;
END;
END
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Futhark | Futhark |
fun ackermann(m: int, n: int): int =
if m == 0 then n + 1
else if n == 0 then ackermann(m-1, 1)
else ackermann(m - 1, ackermann(m, n-1))
|
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #VBA | VBA |
Option Explicit
Public Sub Nb_Classifications()
Dim A As New Collection, D As New Collection, P As New Collection
Dim n As Long, l As Long, s As String, t As Single
t = Timer
'Start
For n = 1 To 20000
l = SumPropers(n): s = CStr(n)
Select Case n
Case Is > l: D.Add s, s
Case Is < l: A.Add s, s
Case l: P.Add s, s
End Select
Next
'End. Return :
Debug.Print "Execution Time : " & Timer - t & " seconds."
Debug.Print "-------------------------------------------"
Debug.Print "Deficient := " & D.Count
Debug.Print "Perfect := " & P.Count
Debug.Print "Abundant := " & A.Count
End Sub
Private Function SumPropers(n As Long) As Long
'returns the sum of the proper divisors of n
Dim j As Long
For j = 1 To n \ 2
If n Mod j = 0 Then SumPropers = j + SumPropers
Next
End Function |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Raku | Raku | my @lines =
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
|.lines;
my @widths;
for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } }
for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } }
sub align($column_width, $word, $aligment = @*ARGS[0]) {
my $lr = $column_width - $word.chars;
my $c = $lr / 2;
given ($aligment) {
when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor }
when "right" { " " x $lr ~ $word }
default { $word ~ " " x $lr }
}
} |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Smalltalk | Smalltalk | list:= (FillInTheBlank request: 'myMessageBoxTitle') subStrings: String crlf.
dict:= Dictionary new.
list do: [:val|
(dict at: val copy sort ifAbsent: [dict at: val copy sort put: OrderedCollection new])
add: val.
].
sorted:=dict asSortedCollection: [:a :b| a size > b size]. |
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.
| #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn Ackerman( m as NSInteger, n as NSInteger ) as NSInteger
NSInteger result
select
case m == 0 : result = ( n + 1 )
case n == 0 : result = fn Ackerman( ( m - 1 ), 1 )
case else : result = fn Ackerman( ( m - 1 ), fn Ackerman( m, ( n - 1 ) ) )
end select
end fn = result
NSInteger m, n
CFMutableStringRef mutStr
mutStr = fn StringWithCapacity( 0 )
for m = 0 to 3
for n = 0 to 9
StringAppendString( mutStr, fn StringWithFormat( @"fn Ackerman( %ld, %ld ) = %ld\n", m, n, fn Ackerman( m, n ) ) )
next
next
NSLog( @"%@", mutStr )
HandleEvents
|
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #VBScript | VBScript | Deficient = 0
Perfect = 0
Abundant = 0
For i = 1 To 20000
sum = 0
For n = 1 To 20000
If n < i Then
If i Mod n = 0 Then
sum = sum + n
End If
End If
Next
If sum < i Then
Deficient = Deficient + 1
ElseIf sum = i Then
Perfect = Perfect + 1
ElseIf sum > i Then
Abundant = Abundant + 1
End If
Next
WScript.Echo "Deficient = " & Deficient & vbCrLf &_
"Perfect = " & Perfect & vbCrLf &_
"Abundant = " & Abundant |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function SumProperDivisors(number As Integer) As Integer
If number < 2 Then Return 0
Dim sum As Integer = 0
For i As Integer = 1 To number \ 2
If number Mod i = 0 Then sum += i
Next
Return sum
End Function
Sub Main()
Dim sum, deficient, perfect, abundant As Integer
For n As Integer = 1 To 20000
sum = SumProperDivisors(n)
If sum < n Then
deficient += 1
ElseIf sum = n Then
perfect += 1
Else
abundant += 1
End If
Next
Console.WriteLine("The classification of the numbers from 1 to 20,000 is as follows : ")
Console.WriteLine()
Console.WriteLine("Deficient = {0}", deficient)
Console.WriteLine("Perfect = {0}", perfect)
Console.WriteLine("Abundant = {0}", abundant)
End Sub
End Module |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #RapidQ | RapidQ |
Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "are$delineated$by$a$single$'dollar'$character,$write$a$program"
MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
MText.WriteLine "column$are$separated$by$at$least$one$space."
MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."
DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces
'Find column widths
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
next
next
'Create aligned wordlists
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
NrSpaces = ColWidth(y) - len(LWord)
'left align
TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
'Right align
TextRight = TextRight + Space$(NrSpaces+1) + LWord
'Center
TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
next
TextLeft = TextLeft + Newline
TextRight = TextRight + Newline
TextCenter = TextCenter + Newline
next
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SNOBOL4 | SNOBOL4 | * # Sort letters of word
define('sortw(str)a,i,j') :(sortw_end)
sortw a = array(size(str))
sw1 i = i + 1; str len(1) . a<i> = :s(sw1)
a = sort(a)
sw2 j = j + 1; sortw = sortw a<j> :s(sw2)f(return)
sortw_end
* # Count words in string
define('countw(str)') :(countw_end)
countw str break(' ') span(' ') = :f(return)
countw = countw + 1 :(countw)
countw_end
ana = table()
L1 wrd = input :f(L2) ;* unixdict.txt from stdin
sw = sortw(wrd); ana<sw> = ana<sw> wrd ' '
cw = countw(ana<sw>); max = gt(cw,max) cw
i = i + 1; terminal = eq(remdr(i,1000),0) wrd :(L1)
L2 kv = convert(ana,'array')
L3 j = j + 1; key = kv<j,1>; val = kv<j,2> :f(end)
output = eq(countw(val),max) key ': ' val :(L3)
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Function Ackermann(m As Float, n As Float) As Float
If m = 0 Then
Return n + 1
End If
If n = 0 Then
Return Ackermann(m - 1, 1)
End If
Return Ackermann(m - 1, Ackermann(m, n - 1))
End
Public Sub Main()
Dim m, n As Float
For m = 0 To 3
For n = 0 To 4
Print "Ackermann("; m; ", "; n; ") = "; Ackermann(m, n)
Next
Next
End |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Vlang | Vlang | fn p_fac_sum(i int) int {
mut sum := 0
for p := 1; p <= i/2; p++ {
if i%p == 0 {
sum += p
}
}
return sum
}
fn main() {
mut d := 0
mut a := 0
mut p := 0
for i := 1; i <= 20000; i++ {
j := p_fac_sum(i)
if j < i {
d++
} else if j == i {
p++
} else {
a++
}
}
println("There are $d deficient numbers between 1 and 20000")
println("There are $a abundant numbers between 1 and 20000")
println("There are $p perfect numbers between 1 and 20000")
} |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #VTL-2 | VTL-2 | 10 M=20000
20 I=1
30 :I)=0
40 I=I+1
50 #=M>I*30
60 I=1
70 J=I*2
80 :J)=:J)+I
90 J=J+I
100 #=M>J*80
110 I=I+1
120 #=M/2>I*70
130 D=0
140 P=0
150 A=0
160 I=1
170 #=:I)<I*230
180 #=:I)=I*210
190 A=A+1
200 #=240
210 P=P+1
220 #=240
230 D=D+1
240 I=I+1
250 #=M>I*170
260 ?=D
270 ?=" deficient"
280 ?=P
290 ?=" perfect"
300 ?=A
310 ?=" abundant" |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REBOL | REBOL | rebol [
Title: "Align Columns"
URL: http://rosettacode.org/wiki/Align_columns
]
specimen: {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.}
; Parse specimen into data grid.
data: copy []
foreach line parse specimen to-string lf [ ; Break into lines.
append/only data parse line "$" ; Break into columns.
]
; Compute independent widths for each column.
widths: copy [] insert/dup widths 0 length? data/1
foreach line data [
forall line [
i: index? line
widths/:i: max widths/:i length? line/1
]
]
pad: func [n /local x][x: copy "" insert/dup x " " n x]
; These formatting functions are passed as arguments to entable.
right: func [n s][rejoin [pad n - length? s s]]
left: func [n s][rejoin [s pad n - length? s]]
centre: func [n s /local h][
h: round/down (n - length? s) / 2
rejoin [pad h s pad n - h - length? s]
]
; Display data as table.
entable: func [data format] [
foreach line data [
forall line [
prin rejoin [format pick widths index? line line/1 " "]
]
print ""
]
]
; Format data table.
foreach i [left centre right] [
print ["^/Align" i "...^/"] entable data get i]
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Stata | Stata | import delimited http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, clear
mata
a=st_sdata(.,.)
n=rows(a)
for (i=1; i<=n; i++) a[i]=char(sort(ascii(a[i])',1)')
st_addvar(st_vartype(1),"group")
st_sstore(.,2,a)
end
bysort group (v1): gen k=_N
qui sum k
keep if k==r(max)
by group: replace k=_n
reshape wide v1, i(k) j(group) string
drop k
list, noobs noheader |
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.
| #Gambas | Gambas | Public Function Ackermann(m As Float, n As Float) As Float
If m = 0 Then
Return n + 1
End If
If n = 0 Then
Return Ackermann(m - 1, 1)
End If
Return Ackermann(m - 1, Ackermann(m, n - 1))
End
Public Sub Main()
Dim m, n As Float
For m = 0 To 3
For n = 0 To 4
Print "Ackermann("; m; ", "; n; ") = "; Ackermann(m, n)
Next
Next
End |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Wren | Wren | import "/math" for Int, Nums
var d = 0
var a = 0
var p = 0
for (i in 1..20000) {
var j = Nums.sum(Int.properDivisors(i))
if (j < i) {
d = d + 1
} else if (j == i) {
p = p + 1
} else {
a = a + 1
}
}
System.print("There are %(d) deficient numbers between 1 and 20000")
System.print("There are %(a) abundant numbers between 1 and 20000")
System.print("There are %(p) perfect numbers between 1 and 20000") |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Red | Red | Red [
Title: "Align Columns"
Original-Author: oofoe
]
text: {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.}
; Parse specimen into data grid.
data: copy []
foreach line split text lf [
append/only data split line "$"
]
; Compute independent widths for each column.
widths: copy []
foreach line data [
forall line [
i: index? line
if i > length? widths [append widths 0]
widths/:i: max widths/:i length? line/1
]
]
pad: function [n] [x: copy "" insert/dup x " " n x]
; These formatting functions are passed as arguments to entable.
right: func [n s][rejoin [pad n - length? s s]]
left: func [n s][rejoin [s pad n - length? s]]
centre: function [n s] [
d: n - length? s
h: round/down d / 2
rejoin [pad h s pad d - h]
]
; Display data as table.
entable: func [data format] [
foreach line data [
forall line [
prin rejoin [format pick widths index? line line/1 " "]
]
print ""
]
]
; Format data table.
foreach i [left centre right] [
print [newline "Align" i "..." newline] entable data get i] |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SuperCollider | SuperCollider | (
var text, words, sorted, dict = IdentityDictionary.new, findMax;
File.use("unixdict.txt".resolveRelative, "r", { |f| text = f.readAllString });
words = text.split(Char.nl);
sorted = words.collect { |each|
var key = each.copy.sort.asSymbol;
dict[key] ?? { dict[key] = [] };
dict[key] = dict[key].add(each)
};
findMax = { |dict|
var size = 0, max = [];
dict.keysValuesDo { |key, val|
if(val.size == size) { max = max.add(val) } {
if(val.size > size) { max = []; size = val.size }
}
};
max
};
findMax.(dict)
) |
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.
| #GAP | GAP | ack := function(m, n)
if m = 0 then
return n + 1;
elif (m > 0) and (n = 0) then
return ack(m - 1, 1);
elif (m > 0) and (n > 0) then
return ack(m - 1, ack(m, n - 1));
else
return fail;
fi;
end; |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #XPL0 | XPL0 | int CntD, CntP, CntA, Num, Div, Sum;
[CntD:= 0; CntP:= 0; CntA:= 0;
for Num:= 1 to 20000 do
[Sum:= if Num = 1 then 0 else 1;
for Div:= 2 to Num-1 do
if rem(Num/Div) = 0 then
Sum:= Sum + Div;
case of
Sum < Num: CntD:= CntD+1;
Sum > Num: CntA:= CntA+1
other CntP:= CntP+1;
];
Text(0, "Deficient: "); IntOut(0, CntD); CrLf(0);
Text(0, "Perfect: "); IntOut(0, CntP); CrLf(0);
Text(0, "Abundant: "); IntOut(0, CntA); CrLf(0);
] |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Yabasic | Yabasic | clear screen
Deficient = 0
Perfect = 0
Abundant = 0
For j=1 to 20000
sump = sumprop(j)
If sump < j Then
Deficient = Deficient + 1
ElseIf sump = j Then
Perfect = Perfect + 1
ElseIf sump > j Then
Abundant = Abundant + 1
End If
Next j
PRINT "Number deficient: ",Deficient
PRINT "Number perfect: ",Perfect
PRINT "Number abundant: ",Abundant
sub sumprop(num)
local i, sum, root
if num>1 then
sum=1
root=sqrt(num)
for i=2 to root
if mod(num,i) = 0 then
sum=sum+i
if (i*i)<>num sum=sum+num/i
end if
next i
end if
return sum
end sub |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX | /*REXX*/
z.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
z.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
z.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
z.4 = "column$are$separated$by$at$least$one$space."
z.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
z.6 = "justified,$right$justified,$or$center$justified$within$its$column."
word. = ""
width. = 0
maxcol = 0
do row = 1 to 6
line = z.row
do col = 1 by 1 until length(line) = 0
parse var line word.row.col "$" line
if length(word.row.col) > width.col then width.col = length(word.row.col)
end
if col > maxcol then maxcol = col
end
say "align left:"
say
do row = 1 to 6
out = ""
do col = 1 to maxcol
out = out || left(word.row.col,width.col+1)
end
say out
end
say
say "align right:"
say
do row = 1 to 6
out = ""
do col = 1 to maxcol
out = out || right(word.row.col,width.col+1)
end
say out
end
say
say "align center:"
say
do row = 1 to 6
out = ""
do col = 1 to maxcol
out = out || center(word.row.col,width.col+1)
end
say out
end |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Swift | Swift | import Foundation
let wordsURL = NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!
let wordsstring = try NSString(contentsOfURL:wordsURL , encoding: NSUTF8StringEncoding)
let allwords = wordsstring.componentsSeparatedByString("\n")
let words = allwords//[0..<100] // used to limit the size while testing
extension String {
var charactersAscending : String {
return String(Array(characters).sort())
}
}
var charsToWords = [String:Set<String>]()
var biggest = 0
var biggestlists = [Set<String>]()
for thisword in words {
let chars = thisword.charactersAscending
var knownwords = charsToWords[chars] ?? Set<String>()
knownwords.insert(thisword)
charsToWords[chars] = knownwords
if knownwords.count > biggest {
biggest = knownwords.count
biggestlists = [knownwords]
}
else if knownwords.count == biggest {
biggestlists.append(knownwords)
}
}
print("Found \(biggestlists.count) sets of anagrams with \(biggest) members each")
for (i, thislist) in biggestlists.enumerate() {
print("set \(i): \(thislist.sort())")
}
|
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.
| #Genyris | Genyris | def A (m n)
cond
(equal? m 0)
+ n 1
(equal? n 0)
A (- m 1) 1
else
A (- m 1)
A m (- n 1) |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #zkl | zkl | fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }
fcn classify(n){
p:=properDivs(n).sum();
return(if(p<n) -1 else if(p==n) 0 else 1);
}
const rangeMax=20_000;
classified:=[1..rangeMax].apply(classify);
perfect :=classified.filter('==(0)).len();
abundant :=classified.filter('==(1)).len();
println("Deficient=%d, perfect=%d, abundant=%d".fmt(
classified.len()-perfect-abundant, perfect, abundant)); |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET nd=1: LET np=0: LET na=0
20 FOR i=2 TO 20000
30 LET sum=1
40 LET max=i/2
50 LET n=2: LET l=max-1
60 IF n>l THEN GO TO 90
70 IF i/n=INT (i/n) THEN LET sum=sum+n: LET max=i/n: IF max<>n THEN LET sum=sum+max: LET l=max-1
80 LET n=n+1: GO TO 60
90 IF sum<i THEN LET nd=nd+1: GO TO 120
100 IF sum=i THEN LET np=np+1: GO TO 120
110 LET na=na+1
120 NEXT i
130 PRINT "Number deficient: ";nd
140 PRINT "Number perfect: ";np
150 PRINT "Number abundant: ";na |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ruby | Ruby | J2justifier = {Left: :ljust, Right: :rjust, Center: :center}
=begin
Justify columns of textual tabular input where the record separator is the newline
and the field separator is a 'dollar' character.
justification can be Symbol; (:Left, :Right, or :Center).
Return the justified output as a string
=end
def aligner(infile, justification = :Left)
fieldsbyrow = infile.map {|line| line.strip.split('$')}
# pad to same number of fields per record
maxfields = fieldsbyrow.map(&:length).max
fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)}
# calculate max fieldwidth per column
colwidths = fieldsbyrow.transpose.map {|column|
column.map(&:length).max
}
# pad fields in columns to colwidth with spaces
justifier = J2justifier[justification]
fieldsbyrow.map {|row|
row.zip(colwidths).map {|field, width|
field.send(justifier, width)
}.join(" ")
}.join("\n")
end
require 'stringio'
textinfile = <<END
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
END
for align in [:Left, :Right, :Center]
infile = StringIO.new(textinfile)
puts "\n# %s Column-aligned output:" % align
puts aligner(infile, align)
end
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | package require Tcl 8.5
package require http
set url http://wiki.puzzlers.org/pub/wordlists/unixdict.txt
set response [http::geturl $url]
set data [http::data $response]
http::cleanup $response
set max 0
array set anagrams {}
foreach line [split $data \n] {
foreach word [split $line] {
set anagram [join [lsort [split $word ""]] ""]
lappend anagrams($anagram) $word
set max [::tcl::mathfunc::max $max [llength $anagrams($anagram)]]
}
}
foreach key [array names anagrams] {
if {[llength $anagrams($key)] == $max} {
puts $anagrams($key)
}
} |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #GML | GML | ///ackermann(m,n)
var m, n;
m = argument0;
n = argument1;
if(m=0)
{
return (n+1)
}
else if(n == 0)
{
return (ackermann(m-1,1,1))
}
else
{
return (ackermann(m-1,ackermann(m,n-1,2),1))
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Run_BASIC | Run BASIC | theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" _
+ "are$delineated$by$a$single$'dollar'$character,$write$a$program" _
+ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"_
+ "column$are$separated$by$at$least$one$space." _
+ "Further,$allow$for$each$word$in$a$column$to$be$either$left$" _
+ "justified,$right$justified,$or$center$justified$within$its$column."
x = shoTable(theString$,"left",6)
x = shoTable(theString$,"right",6)
x = shoTable(theString$,"center",6)
end
FUNCTION shoTable(theString$,align$,across)
print "------------ align:";align$;" -- across:";across;" ------------"
dim siz(across)
b$ = " "
while word$(theString$,i+1,"$") <> ""
siz(i mod across) = max(siz(i mod across),len(word$(theString$,i + 1,"$")))
i = i + 1
wend
for i = 0 to across - 1
siz(i) = siz(i) + 1
if siz(i) and 1 then siz(i) = siz(i) + 1
next i
i = 0
a$ = word$(theString$,i+1,"$")
while a$ <> ""
s = siz(i mod across) - len(a$)
if align$ = "right" then a$ = left$(b$,s);a$
if align$ = "left" then a$ = a$;left$(b$,s)
if align$ = "center" then a$ = left$(b$,int(s / 2));a$;left$(b$,int(s / 2) + (s and 1))
print "|";a$;
i = i + 1
if i mod across = 0 then print "|"
a$ = word$(theString$,i+1,"$")
wend
print
end function |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Transd | Transd | #lang transd
MainModule: {
_start: (λ
(with fs FileStream() words String()
(open fs "/mnt/proj/tmp/unixdict.txt")
(textin fs words)
( -|
(split words)
(group-by (λ s String() -> String() (sort (cp s))))
(regroup-by (λ v Vector<String>() -> Int() (size v)))
(max-element)
(snd)
(textout)
)
))
} |
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.
| #gnuplot | gnuplot | A (m, n) = m == 0 ? n + 1 : n == 0 ? A (m - 1, 1) : A (m - 1, A (m, n - 1))
print A (0, 4)
print A (1, 4)
print A (2, 4)
print A (3, 4) |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | use std::iter::{repeat, Extend};
enum AlignmentType {
Left,
Center,
Right,
}
fn get_column_widths(text: &str) -> Vec<usize> {
let mut widths = Vec::new();
for line in text
.lines()
.map(|s| s.trim_matches(' ').trim_end_matches('$'))
{
let lens = line.split('$').map(|s| s.chars().count());
for (idx, len) in lens.enumerate() {
if idx < widths.len() {
widths[idx] = std::cmp::max(widths[idx], len);
} else {
widths.push(len);
}
}
}
widths
}
fn align_columns(text: &str, alignment: AlignmentType) -> String {
let widths = get_column_widths(text);
let mut result = String::new();
for line in text
.lines()
.map(|s| s.trim_matches(' ').trim_end_matches('$'))
{
for (s, w) in line.split('$').zip(widths.iter()) {
let blank_count = w - s.chars().count();
let (pre, post) = match alignment {
AlignmentType::Left => (0, blank_count),
AlignmentType::Center => (blank_count / 2, (blank_count + 1) / 2),
AlignmentType::Right => (blank_count, 0),
};
result.extend(repeat(' ').take(pre));
result.push_str(s);
result.extend(repeat(' ').take(post));
result.push(' ');
}
result.push_str("\n");
}
result
}
fn main() {
let text = r#"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."#;
println!("{}", align_columns(text, AlignmentType::Left));
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", align_columns(text, AlignmentType::Center));
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", align_columns(text, AlignmentType::Right));
} |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
DICT anagramm CREATE 99999
COMPILE
LOOP word=requestdata
-> ? : any character
charsInWord=STRINGS (word," ? ")
charString =ALPHA_SORT (charsInWord)
DICT anagramm APPEND/QUIET/COUNT charString,num,freq,word;" "
ENDLOOP
DICT anagramm UNLOAD charString,all,freq,anagrams
index =DIGIT_INDEX (freq)
reverseIndex =REVERSE (index)
freq =INDEX_SORT (freq,reverseIndex)
anagrams =INDEX_SORT (anagrams,reverseIndex)
charString =INDEX_SORT (charString,reverseIndex)
mostWords=SELECT (freq,1), adjust=MAX_LENGTH (charString)
LOOP cs=charString, f=freq, a=anagrams
IF (f<mostWords) EXIT
cs=CENTER (cs,-adjust)
PRINT cs," ",f,": ",a
ENDLOOP
ENDCOMPILE |
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.
| #Go | Go | func Ackermann(m, n uint) uint {
switch 0 {
case m:
return n + 1
case n:
return Ackermann(m - 1, 1)
}
return Ackermann(m - 1, Ackermann(m, n - 1))
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | object ColumnAligner {
val eol = System.getProperty("line.separator")
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
def splitter(line: String) = line split '$'
def getTable(filename: String) = getLines(filename) map splitter
def fieldWidths(fields: Array[String]) = fields map (_ length)
def columnWidths(txt: Iterator[Array[String]]) = (txt map fieldWidths).toList.transpose map (_ max)
def alignField(alignment: Char)(width: Int)(field: String) = alignment match {
case 'l' | 'L' => "%-"+width+"s" format field
case 'r' | 'R' => "%"+width+"s" format field
case 'c' | 'C' => val padding = (width - field.length) / 2; " "*padding+"%-"+(width-padding)+"s" format field
case _ => throw new IllegalArgumentException
}
def align(aligners: List[String => String])(fields: Array[String]) =
aligners zip fields map Function.tupled(_ apply _)
def alignFile(filename: String, alignment: Char) = {
def table = getTable(filename)
val aligners = columnWidths(table) map alignField(alignment)
table map align(aligners) map (_ mkString " ")
}
def printAlignedFile(filename: String, alignment: Char) {
alignFile(filename, alignment) foreach println
}
} |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | http_get_body() {
local host=$1
local uri=$2
exec 5<> /dev/tcp/$host/80
printf >&5 "%s\r\n" "GET $uri HTTP/1.1" "Host: $host" "Connection: close" ""
mapfile -t -u5
local lines=( "${MAPFILE[@]//$'\r'}" )
local i=0 found=0
for (( ; found == 0; i++ )); do
[[ -z ${lines[i]} ]] && (( found++ ))
done
printf "%s\n" "${lines[@]:i}"
exec 5>&-
}
declare -A wordlist
while read -r word; do
uniq_letters=( $(for ((i=0; i<${#word}; i++)); do echo "${word:i:1}"; done | sort) )
wordlist["${uniq_letters[*]}"]+="$word "
done < <( http_get_body wiki.puzzlers.org /pub/wordlists/unixdict.txt )
maxlen=0
maxwords=()
for key in "${!wordlist[@]}"; do
words=( ${wordlist[$key]} )
if (( ${#words[@]} > maxlen )); then
maxlen=${#words[@]}
maxwords=( "${wordlist["$key"]}" )
elif (( ${#words[@]} == maxlen )); then
maxwords+=( "${wordlist[$key]}" )
fi
done
printf "%s\n" "${maxwords[@]}" |
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.
| #Golfscript | Golfscript | {
:_n; :_m;
_m 0= {_n 1+}
{_n 0= {_m 1- 1 ack}
{_m 1- _m _n 1- ack ack}
if}
if
}:ack; |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 1)
(except (srfi 13) string-for-each string-map)
(srfi 14))
;; text is a list of lines, alignment is left/right/center
;; displays the aligned text in columns with a single space gap
(define (align-columns text alignment)
(define (split line) ; splits string on $ into list of strings
(string-tokenize line (char-set-complement (->char-set "$"))))
(define (extend lst n) ; extends list to length n, by adding "" to end
(append lst (make-list (- n (length lst)) "")))
(define (align-word word width) ; align single word to fit width
(case alignment
((left) (string-pad-right word width))
((right) (string-pad word width))
((center) (let ((rem (- width (string-length word))))
(string-pad-right (string-pad word (- width (truncate (/ rem 2))))
width)))))
;
(display alignment) (newline)
(let* ((text-list (map split text))
(max-line-len (fold (lambda (text val) (max (length text) val)) 0 text-list))
(text-lines (map (lambda (line) (extend line max-line-len)) text-list))
(min-col-widths (map (lambda (col)
(fold (lambda (line val)
(max (string-length (list-ref line col))
val))
0
text-lines))
(iota max-line-len))))
(map (lambda (line)
(map (lambda (word width)
(display (string-append (align-word word width)
" ")))
line min-col-widths)
(newline))
text-lines))
(newline))
;; show example
(define *example*
'("Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
"are$delineated$by$a$single$'dollar'$character,$write$a$program"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
"column$are$separated$by$at$least$one$space."
"Further,$allow$for$each$word$in$a$column$to$be$either$left$"
"justified,$right$justified,$or$center$justified$within$its$column."))
(align-columns *example* 'left)
(align-columns *example* 'center)
(align-columns *example* 'right)
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ursala | Ursala | #import std
#show+
anagrams = mat` * leql$^&h eql|=@rK2tFlSS ^(~&,-<&)* unixdict_dot_txt |
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.
| #Groovy | Groovy | def ack ( m, n ) {
assert m >= 0 && n >= 0 : 'both arguments must be non-negative'
m == 0 ? n + 1 : n == 0 ? ack(m-1, 1) : ack(m-1, ack(m, n-1))
} |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #sed | sed |
#!/bin/sed -nrf
# Format: <master-pattern>\n<line1>\n<line1-as-pattern>\n<line2>\n<line2-as-pattern>...
# After reading whole file <master-pattern> contains max number of fields of max width each.
# If no $ at start or end of a line -- add them
/^\$/! s/^/$/
/\$$/! s/$/$/
# First line saved as three lines in hold space:
# <line1-as-pattern>\n<line1>\n<line1-as-pattern>
1{
h
s/[^$]/ /g
H
G
x
# Restart -- go to next line
b
}
# For lines 2,3,...
H
# Current line -> pattern
# (each character replaced by constant symbol (e.g. space) so that we can count them)
s/[^$]/ /g
H
G
# Add two markers
s/\$/1$/
s/(\n[^$]*)\$/\12$/
# Compare patterns
:cmp
s/(1\$([^$\n]*)([^$\n]*)[^2]*2\$\2)/\1\3/
/1\$\n/ bout
# Advance markers
s/1(\$[^12$\n]*)/\11/
s/2(\$[^12$\n]*)/\12/
# Add one more field
/^[^2]*2\$\n/{ s/^([^2]*)2\$\n/\12$$\n/; }
bcmp
:out
# Remove first line
s/[^\n]*\n//
# Remove 2$-marker
s/2\$/$/
x
${
# We are on the last line -- start printing
x;
# Add a line for aligned string
s/^/\n/
:nextline
# Add marker again (only one this time)
s/\$/1$/
:align
# 1. look up missing spaces,
# 2. put first word of 2nd line before first newline adding missing spaces
# 3. cut first word of 2nd and 3rd lines.
# Replace \5\3 by \3\5 for RIGHT ALIGNMENT
s/(\n[^\n]*)1\$([^$\n]*)([^$\n]*)\$([^\n]*\n)\$([^$\n]*)([^\n]*\n)\$\2\$/\5\3 \1$\2\31$\4\6$/
talign
# We ate 2nd and 3rd lines completely, except newlines -- remove them
s/\$\n\$\n\$\n/$\n/
# Print the first line in pattern space
P
# ... and remove it
s/^[^\n]*//
# Remove marker
s/1\$/$/
# If no more lines -- exit
/\$\n\$$/q
bnextline
}
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #VBA | VBA |
Option Explicit
Public Sub Main_Anagram()
Dim varReturn
Dim temp
Dim strContent As String
Dim strFile As String
Dim Num As Long
Dim i As Long
Dim countTime As Single
'Open & read txt file
Num = FreeFile
strFile = "C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt"
Open strFile For Input As #Num
strContent = Input(LOF(1), #Num)
Close #Num
Debug.Print UBound(Split(strContent, vbCrLf)) + 1 & " words, in the dictionary"
countTime = Timer
'Compute
varReturn = Anagrams(strContent)
'Return
Debug.Print "The anagram set(s) with the greatest number of words (namely " & UBound(varReturn, 2) & ") is : "
Debug.Print ""
For i = LBound(varReturn, 1) To UBound(varReturn, 1)
ReDim temp(LBound(varReturn, 2) To UBound(varReturn, 2))
For Num = LBound(varReturn, 2) To UBound(varReturn, 2)
temp(Num) = varReturn(i, Num)
Next
SortOneDimArray temp, LBound(temp), UBound(temp)
Debug.Print Mid(Join(temp, ", "), 3)
Next i
Debug.Print ""
Debug.Print "Time to go : " & Timer - countTime & " seconds."
End Sub
Private Function Anagrams(strContent As String) As Variant
Dim arrList
Dim arrTemp() As String
Dim arrReturn() As String
Dim Num As Long
Dim lngCountTemp As Long
Dim lngCount As Long
Dim i As Long
'Put the content of txt file in an One Dim Array
arrList = Split(strContent, vbCrLf)
ReDim arrTemp(0 To UBound(arrList, 1), 0 To 2)
'Transfer Datas in a 2nd Array Multi-Dim
'Col 0 = words with letters sorted
'Col 1 = words
'Col 2 = Number of same words with letters sorted in the list
For Num = LBound(arrList) To UBound(arrList)
arrTemp(Num, 0) = SortLetters(CStr(arrList(Num)), Chr(0))
arrTemp(Num, 1) = CStr(arrList(Num))
Next
SortTwoDimArray arrTemp, LBound(arrTemp, 1), UBound(arrTemp, 1), 0
For Num = LBound(arrTemp, 1) To UBound(arrTemp, 1)
arrTemp(Num, 2) = NbIf(arrTemp(Num, 0), arrTemp, Num, 0)
If arrTemp(Num, 2) > lngCountTemp Then lngCountTemp = arrTemp(Num, 2)
Next
'return
ReDim arrReturn(0 To lngCountTemp, 0)
For Num = LBound(arrTemp, 1) To UBound(arrTemp, 1)
If lngCountTemp = arrTemp(Num, 2) Then
ReDim Preserve arrReturn(0 To lngCountTemp, 0 To lngCount)
For i = 0 To lngCountTemp - 1
arrReturn(i, lngCount) = arrTemp(Num + i, 1)
Next i
lngCount = lngCount + 1
End If
Next Num
Anagrams = Transposition(arrReturn)
End Function
Private Function SortLetters(s As String, sep As String) As String
Dim temp
temp = Split(StrConv(s, vbUnicode), sep)
SortOneDimArray temp, LBound(temp), UBound(temp)
SortLetters = Join(temp, sep)
End Function
Private Function NbIf(strValue As String, arr As Variant, lngInd As Long, Optional lngColumn As Long) As Long
Dim i As Long
Dim lngCount As Long
For i = lngInd To UBound(arr, 1)
If arr(i, lngColumn) = strValue Then
lngCount = lngCount + 1
Else
Exit For
End If
Next i
NbIf = lngCount
End Function
Private Function Transposition(ByRef myArr As Variant) As Variant
Dim tabl
Dim i As Long
Dim j As Long
ReDim tabl(LBound(myArr, 2) To UBound(myArr, 2), LBound(myArr, 1) To UBound(myArr, 1))
For i = LBound(myArr, 1) To UBound(myArr, 1)
For j = LBound(myArr, 2) To UBound(myArr, 2)
tabl(j, i) = myArr(i, j)
Next j
Next i
Transposition = tabl
Erase tabl
End Function
Private Sub SortOneDimArray(ByRef myArr As Variant, mini As Long, Maxi As Long)
Dim i As Long
Dim j As Long
Dim Pivot As Variant
Dim temp As Variant
On Error Resume Next
i = mini: j = Maxi
Pivot = myArr((mini + Maxi) \ 2)
While i <= j
While myArr(i) < Pivot And i < Maxi: i = i + 1: Wend
While Pivot < myArr(j) And j > mini: j = j - 1: Wend
If i <= j Then
temp = myArr(i)
myArr(i) = myArr(j)
myArr(j) = temp
i = i + 1: j = j - 1
End If
Wend
If (mini < j) Then Call SortOneDimArray(myArr, mini, j)
If (i < Maxi) Then Call SortOneDimArray(myArr, i, Maxi)
End Sub
Private Sub SortTwoDimArray(ByRef myArr As Variant, mini As Long, Maxi As Long, Optional Colonne As Long = 0)
Dim i As Long
Dim j As Long
Dim Pivot As Variant
Dim myArrTemp As Variant
Dim ColTemp As Long
On Error Resume Next
i = mini: j = Maxi
Pivot = myArr((mini + Maxi) \ 2, Colonne)
While i <= j
While myArr(i, Colonne) < Pivot And i < Maxi: i = i + 1: Wend
While Pivot < myArr(j, Colonne) And j > mini: j = j - 1: Wend
If i <= j Then
ReDim myArrTemp(LBound(myArr, 2) To UBound(myArr, 2))
For ColTemp = LBound(myArr, 2) To UBound(myArr, 2)
myArrTemp(ColTemp) = myArr(i, ColTemp)
myArr(i, ColTemp) = myArr(j, ColTemp)
myArr(j, ColTemp) = myArrTemp(ColTemp)
Next ColTemp
Erase myArrTemp
i = i + 1: j = j - 1
End If
Wend
If (mini < j) Then Call SortTwoDimArray(myArr, mini, j, Colonne)
If (i < Maxi) Then Call SortTwoDimArray(myArr, i, Maxi, Colonne)
End Sub |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Hare | Hare | use fmt;
fn ackermann(m: u64, n: u64) u64 = {
if (m == 0) {
return n + 1;
};
if (n == 0) {
return ackermann(m - 1, 1);
};
return ackermann(m - 1, ackermann(m, n - 1));
};
export fn main() void = {
for (let m = 0u64; m < 4; m += 1) {
for (let n = 0u64; n < 10; n += 1) {
fmt::printfln("A({}, {}) = {}", m, n, ackermann(m, n))!;
};
fmt::println()!;
};
}; |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const array string: inputLines is [] (
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column.");
const func array integer: computeColumnWidths (in array string: inputLines) is func
result
var array integer: columnWidths is 0 times 0;
local
var string: line is "";
var array string: lineFields is 0 times "";
var integer: index is 0;
begin
for line range inputLines do
lineFields := split(line, "$");
if length(lineFields) > length(columnWidths) then
columnWidths &:= (length(lineFields) - length(columnWidths)) times 0;
end if;
for index range 1 to length(lineFields) do
if length(lineFields[index]) > columnWidths[index] then
columnWidths[index] := length(lineFields[index]);
end if;
end for;
end for;
end func;
const func string: center (in string: stri, in integer: length) is
return ("" lpad (length - length(stri)) div 2 <& stri) rpad length;
const proc: main is func
local
var array integer: columnWidths is 0 times 0;
var string: line is "";
var array string: lineFields is 0 times "";
var integer: index is 0;
begin
columnWidths := computeColumnWidths(inputLines);
for line range inputLines do
lineFields := split(line, "$");
for index range 1 to length(lineFields) do
# write(lineFields[index] rpad columnWidths[index] <& " "); # Left justify
# write(lineFields[index] lpad columnWidths[index] <& " "); # Right justify
write(center(lineFields[index], columnWidths[index]) <& " ");
end for;
writeln;
end for;
end func; |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #VBScript | VBScript |
Const adInteger = 3
Const adVarChar = 200
function charcnt(s,ch)
charcnt=0
for i=1 to len(s)
if mid(s,i,1)=ch then charcnt=charcnt+1
next
end function
set fso=createobject("Scripting.Filesystemobject")
dim a(122)
sfn=WScript.ScriptFullName
sfn= Left(sfn, InStrRev(sfn, "\"))
set f=fso.opentextfile(sfn & "unixdict.txt",1)
'words to dictionnary using acronym as key
set d=createobject("Scripting.Dictionary")
while not f.AtEndOfStream
erase a :cnt=0
s=trim(f.readline)
'tally chars
for i=1 to len(s)
n=asc(mid(s,i,1))
a(n)=a(n)+1
next
'build the anagram
k=""
for i= 48 to 122
if a(i) then k=k & string(a(i),chr(i))
next
'add to dict
if d.exists(k) then
b=d(k)
d(k)=b & " " & s
else
d(k)=s
end if
wend
'copy dictionnary to recorset to be able to sort it .Add nr of items as a new field
Set rs = CreateObject("ADODB.Recordset")
rs.Fields.Append "anag", adVarChar, 30
rs.Fields.Append "items", adInteger
rs.Fields.Append "words", adVarChar, 200
rs.open
for each k in d.keys
rs.addnew
rs("anag")=k
s=d(k)
rs("words")=s
rs("items")=charcnt(s," ")+1
rs.update
next
d.removeall
'do the query
rs.sort="items DESC, anag ASC"
rs.movefirst
it=rs("items")
while rs("items")=it
wscript.echo rs("items") & " (" &rs("anag") & ") " & rs("words")
rs.movenext
wend
rs.close
|
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.
| #Haskell | Haskell | ack :: Int -> Int -> Int
ack 0 n = succ n
ack m 0 = ack (pred m) 1
ack m n = ack (pred m) (ack m (pred n))
main :: IO ()
main = mapM_ print $ uncurry ack <$> [(0, 0), (3, 4)] |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Shiny | Shiny | text: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'
align: action text; position;
# split text into 2D array of lines and words
lines : { for text.split ~\$?\r?\n~ { for a.split '$' a end } end }
# calculate max required width for each column
widths: { for lines for a here[b]: a.length.max here[b]? ends }
spaces: action out ("%%%ds" in).format '' end
# formatting functions
left: action word; width;
pad: width-word.length
print "%s%s " word spaces pad
end
right: action word; width;
pad: width-word.length
print "%s%s " spaces pad word
end
center: action word; width;
pad: (width-word.length)/2
print "%s%s%s " spaces pad.floor word spaces pad.ceil
end
if position.match ~^(left|center|right)$~ for lines
for a local[position] a widths[b] end say ''
ends say ''
end
align text 'left'
align text 'center'
align text 'right' |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Vedit_macro_language | Vedit macro language | File_Open("|(PATH_ONLY)\unixdict.txt")
Repeat(ALL) {
Reg_Copy_Block(10, CP, EOL_Pos) // original word
Call("SORT_LETTERS") // sort letters of the word
EOL
IC(' ') Reg_Ins(10) // add the original word at eol
Line(1, ERRBREAK)
}
Sort(0, File_Size) // sort list according to anagrams
BOF
Search("|F") Search(' ') // first word in the list
Reg_Copy_Block(10, BOL_Pos, CP+1) // reg 10 = sorted anagram word
Reg_Copy_Block(11, CP, EOL_Pos) // reg 11 = list of words in current group
Reg_Empty(12) // reg 12 = list of words in largest groups
Reg_Set(13, "
")
#1 = 1 // words in this group
#2 = 2 // words in largest group found
Repeat(ALL) {
Line(1, ERRBREAK)
if (Match(@10, ADVANCE) == 0) { // same group as previous word?
Reg_Copy_Block(11, CP-1, EOL_Pos, APPEND) // add word to this group
#1++
} else { // different anagram group
Search(" ", ERRBREAK)
if (#1 == #2) { // same size as the largest?
Reg_Set(12, @13, APPEND) // append newline
Reg_Set(12, @11, APPEND) // append word list
}
if (#1 > #2) { // new larger size of group
Reg_Set(12, @11) // replace word list
#2 = #1
}
Reg_Copy_Block(10, BOL_Pos, CP+1)
Reg_Copy_Block(11, CP, EOL_Pos) // first word of new group
#1 = 1
}
}
Buf_Quit(OK) // close word list file
Buf_Switch(Buf_Free) // output results in a new edit buffer
Reg_Ins(12) // display all groups of longest anagram words
Return
////////////////////////////////////////////////////////////////////
//
// Sort characters in current line using Insertion sort
//
:SORT_LETTERS:
GP(EOL_pos) #9 = Cur_Col-1
for (#1 = 2; #1 <= #9; #1++) {
Goto_Col(#1) #8 = Cur_Char
#2 = #1
while (#2 > 1) {
#7 = Cur_Char(-1)
if (#7 <= #8) { break }
Ins_Char(#7, OVERWRITE)
#2--
Goto_Col(#2)
}
Ins_Char(#8, OVERWRITE)
}
return |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Haxe | Haxe | class RosettaDemo
{
static public function main()
{
Sys.print(ackermann(3, 4));
}
static function ackermann(m : Int, n : Int)
{
if (m == 0)
{
return n + 1;
}
else if (n == 0)
{
return ackermann(m-1, 1);
}
return ackermann(m-1, ackermann(m, n-1));
}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.