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/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #D | D | import std.stdio;
void main() {
auto x = acc(1);
x(5);
acc(3);
writeln(x(2.3));
}
auto acc(U = real, T)(T initvalue) { // U is type of the accumulator
auto accum = cast(U)initvalue ;
return (U n) { return accum += n ; } ;
} |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Dart | Dart | makeAccumulator(s) => (n) => s += 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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program ackermann64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MMAXI, 4
.equ NMAXI, 10
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Result for @ @ : @ \n"
szMessError: .asciz "Overflow !!.\n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x3,#0
mov x4,#0
1:
mov x0,x3
mov x1,x4
bl ackermann
mov x5,x0
mov x0,x3
ldr x1,qAdrsZoneConv // else display odd message
bl conversion10 // call decimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
mov x6,x0
mov x0,x4
ldr x1,qAdrsZoneConv // else display odd message
bl conversion10 // call decimal conversion
mov x0,x6
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
mov x6,x0
mov x0,x5
ldr x1,qAdrsZoneConv // else display odd message
bl conversion10 // call decimal conversion
mov x0,x6
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
bl affichageMess
add x4,x4,#1
cmp x4,#NMAXI
blt 1b
mov x4,#0
add x3,x3,#1
cmp x3,#MMAXI
blt 1b
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
/***************************************************/
/* fonction ackermann */
/***************************************************/
// x0 contains a number m
// x1 contains a number n
// x0 return résult
ackermann:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
cmp x0,0
beq 5f
mov x3,-1
csel x0,x3,x0,lt // error
blt 100f
cmp x1,#0
csel x0,x3,x0,lt // error
blt 100f
bgt 1f
sub x0,x0,#1
mov x1,#1
bl ackermann
b 100f
1:
mov x2,x0
sub x1,x1,#1
bl ackermann
mov x1,x0
sub x0,x2,#1
bl ackermann
b 100f
5:
adds x0,x1,#1
bcc 100f
ldr x0,qAdrszMessError
bl affichageMess
mov x0,-1
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessError: .quad szMessError
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program numberClassif.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ NBDIVISORS, 1000
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n"
szMessError: .asciz "\033[31mError !!!\n"
szMessErrGen: .asciz "Error end program.\n"
szMessNbPrem: .asciz "This number is prime !!!.\n"
szMessResultFact: .asciz "@ "
szCarriageReturn: .asciz "\n"
/* datas message display */
szMessResult: .asciz "Number déficients : @ perfects : @ abundants : @ \n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
tbZoneDecom: .skip 4 * NBDIVISORS // facteur 4 octets
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: @ program start
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
mov r4,#1
mov r3,#0
mov r6,#0
mov r7,#0
mov r8,#0
ldr r9,iNBMAX
1:
mov r0,r4 @ number
//=================================
ldr r1,iAdrtbZoneDecom
bl decompFact @ create area of divisors
cmp r0,#0 @ error ?
blt 2f
lsl r5,r4,#1 @ number * 2
cmp r5,r1 @ compare number and sum
addeq r7,r7,#1 @ perfect
addgt r6,r6,#1 @ deficient
addlt r8,r8,#1 @ abundant
2:
add r4,r4,#1
cmp r4,r9
ble 1b
//================================
mov r0,r6 @ deficient
ldr r1,iAdrsZoneConv
bl conversion10 @ convert ascii string
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ and put in message
mov r5,r0
mov r0,r7 @ perfect
ldr r1,iAdrsZoneConv
bl conversion10 @ convert ascii string
mov r0,r5
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ and put in message
mov r5,r0
mov r0,r8 @ abundant
ldr r1,iAdrsZoneConv
bl conversion10 @ convert ascii string
mov r0,r5
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ and put in message
bl affichageMess
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszMessError: .int szMessError
iAdrszCarriageReturn: .int szCarriageReturn
iAdrtbZoneDecom: .int tbZoneDecom
iAdrszMessResult: .int szMessResult
iAdrsZoneConv: .int sZoneConv
iNBMAX: .int 20000
/******************************************************************/
/* factor decomposition */
/******************************************************************/
/* r0 contains number */
/* r1 contains address of divisors area */
/* r0 return divisors items in table */
/* r1 return the sum of divisors */
decompFact:
push {r3-r12,lr} @ save registers
cmp r0,#1
moveq r1,#1
beq 100f
mov r5,r1
mov r8,r0 @ save number
bl isPrime @ prime ?
cmp r0,#1
beq 98f @ yes is prime
mov r1,#1
str r1,[r5] @ first factor
mov r12,#1 @ divisors sum
mov r10,#1 @ indice divisors table
mov r9,#2 @ first divisor
mov r6,#0 @ previous divisor
mov r7,#0 @ number of same divisors
/* division loop */
2:
mov r0,r8 @ dividende
mov r1,r9 @ divisor
bl division @ r2 quotient r3 remainder
cmp r3,#0
beq 3f @ if remainder zero -> divisor
/* not divisor -> increment next divisor */
cmp r9,#2 @ if divisor = 2 -> add 1
addeq r9,#1
addne r9,#2 @ else add 2
b 2b
/* divisor compute the new factors of number */
3:
mov r8,r2 @ else quotient -> new dividende
cmp r9,r6 @ same divisor ?
beq 4f @ yes
mov r0,r5 @ table address
mov r1,r10 @ number factors in table
mov r2,r9 @ divisor
mov r3,r12 @ somme
mov r4,#0
bl computeFactors
mov r10,r1
mov r12,r0
mov r6,r9 @ new divisor
b 7f
4: @ same divisor
sub r7,r10,#1
5: @ search in table the first use of divisor
ldr r3,[r5,r7,lsl #2 ]
cmp r3,r9
subne r7,#1
bne 5b
@ and compute new factors after factors
sub r4,r10,r7 @ start indice
mov r0,r5
mov r1,r10
mov r2,r9 @ divisor
mov r3,r12
bl computeFactors
mov r12,r0
mov r10,r1
/* divisor -> test if new dividende is prime */
7:
cmp r8,#1 @ dividende = 1 ? -> end
beq 10f
mov r0,r8 @ new dividende is prime ?
mov r1,#0
bl isPrime @ the new dividende is prime ?
cmp r0,#1
bne 10f @ the new dividende is not prime
cmp r8,r6 @ else dividende is same divisor ?
beq 8f @ yes
mov r0,r5
mov r1,r10
mov r2,r8
mov r3,r12
mov r4,#0
bl computeFactors
mov r12,r0
mov r10,r1
mov r7,#0
b 11f
8:
sub r7,r10,#1
9:
ldr r3,[r5,r7,lsl #2 ]
cmp r3,r8
subne r7,#1
bne 9b
mov r0,r5
mov r1,r10
sub r4,r10,r7
mov r2,r8
mov r3,r12
bl computeFactors
mov r12,r0
mov r10,r1
b 11f
10:
cmp r9,r8 @ current divisor > new dividende ?
ble 2b @ no -> loop
/* end decomposition */
11:
mov r0,r10 @ return number of table items
mov r1,r12 @ return sum
mov r3,#0
str r3,[r5,r10,lsl #2] @ store zéro in last table item
b 100f
98: @ prime number
//ldr r0,iAdrszMessNbPrem
//bl affichageMess
add r1,r8,#1
mov r0,#0 @ return code
b 100f
99:
ldr r0,iAdrszMessError
bl affichageMess
mov r0,#-1 @ error code
b 100f
100:
pop {r3-r12,lr} @ restaur registers
bx lr
iAdrszMessNbPrem: .int szMessNbPrem
/* r0 table factors address */
/* r1 number factors in table */
/* r2 new divisor */
/* r3 sum */
/* r4 start indice */
/* r0 return sum */
/* r1 return number factors in table */
computeFactors:
push {r2-r6,lr} @ save registers
mov r6,r1 @ number factors in table
1:
ldr r5,[r0,r4,lsl #2 ] @ load one factor
mul r5,r2,r5 @ multiply
str r5,[r0,r1,lsl #2] @ and store in the table
add r3,r5
add r1,r1,#1 @ and increment counter
add r4,r4,#1
cmp r4,r6
blt 1b
mov r0,r3
100: @ fin standard de la fonction
pop {r2-r6,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/***************************************************/
/* check if a number is prime */
/***************************************************/
/* r0 contains the number */
/* r0 return 1 if prime 0 else */
@2147483647
@4294967297
@131071
isPrime:
push {r1-r6,lr} @ save registers
cmp r0,#0
beq 90f
cmp r0,#17
bhi 1f
cmp r0,#3
bls 80f @ for 1,2,3 return prime
cmp r0,#5
beq 80f @ for 5 return prime
cmp r0,#7
beq 80f @ for 7 return prime
cmp r0,#11
beq 80f @ for 11 return prime
cmp r0,#13
beq 80f @ for 13 return prime
cmp r0,#17
beq 80f @ for 17 return prime
1:
tst r0,#1 @ even ?
beq 90f @ yes -> not prime
mov r2,r0 @ save number
sub r1,r0,#1 @ exposant n - 1
mov r0,#3 @ base
bl moduloPuR32 @ compute base power n - 1 modulo n
cmp r0,#1
bne 90f @ if <> 1 -> not prime
mov r0,#5
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#7
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#11
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#13
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#17
bl moduloPuR32
cmp r0,#1
bne 90f
80:
mov r0,#1 @ is prime
b 100f
90:
mov r0,#0 @ no prime
100: @ fin standard de la fonction
pop {r1-r6,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/* */
/********************************************************/
/* r0 nombre */
/* r1 exposant */
/* r2 modulo */
/* r0 return result */
moduloPuR32:
push {r1-r7,lr} @ save registers
cmp r0,#0 @ verif <> zero
beq 100f
cmp r2,#0 @ verif <> zero
beq 100f @ TODO: v鲩fier les cas d erreur
1:
mov r4,r2 @ save modulo
mov r5,r1 @ save exposant
mov r6,r0 @ save base
mov r3,#1 @ start result
mov r1,#0 @ division de r0,r1 par r2
bl division32R
mov r6,r2 @ base <- remainder
2:
tst r5,#1 @ exposant even or odd
beq 3f
umull r0,r1,r6,r3
mov r2,r4
bl division32R
mov r3,r2 @ result <- remainder
3:
umull r0,r1,r6,r6
mov r2,r4
bl division32R
mov r6,r2 @ base <- remainder
lsr r5,#1 @ left shift 1 bit
cmp r5,#0 @ end ?
bne 2b
mov r0,r3
100: @ fin standard de la fonction
pop {r1-r7,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/***************************************************/
/* division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende */
/* r1 contains upper part dividende */
/* r2 contains divisor */
/* r0 return lower part quotient */
/* r1 return upper part quotient */
/* r2 return remainder */
division32R:
push {r3-r9,lr} @ save registers
mov r6,#0 @ init upper upper part remainder !!
mov r7,r1 @ init upper part remainder with upper part dividende
mov r8,r0 @ init lower part remainder with lower part dividende
mov r9,#0 @ upper part quotient
mov r4,#0 @ lower part quotient
mov r5,#32 @ bits number
1: @ begin loop
lsl r6,#1 @ shift upper upper part remainder
lsls r7,#1 @ shift upper part remainder
orrcs r6,#1
lsls r8,#1 @ shift lower part remainder
orrcs r7,#1
lsls r4,#1 @ shift lower part quotient
lsl r9,#1 @ shift upper part quotient
orrcs r9,#1
@ divisor sustract upper part remainder
subs r7,r2
sbcs r6,#0 @ and substract carry
bmi 2f @ n駡tive ?
@ positive or equal
orr r4,#1 @ 1 -> right bit quotient
b 3f
2: @ negative
orr r4,#0 @ 0 -> right bit quotient
adds r7,r2 @ and restaur remainder
adc r6,#0
3:
subs r5,#1 @ decrement bit size
bgt 1b @ end ?
mov r0,r4 @ lower part quotient
mov r1,r9 @ upper part quotient
mov r2,r7 @ remainder
100: @ function end
pop {r3-r9,lr} @ restaur registers
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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
| #AWK | AWK |
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
BEGIN {
colsep = " " # separator between columns
report("raw data")
}
{ printf("%s\n",$0)
arr[NR] = $0
n = split($0,tmp_arr,"$")
for (j=1; j<=n; j++) {
width = max(width,length(tmp_arr[j]))
}
}
END {
report("left justified")
report("right justified")
report("center justified")
exit(0)
}
function report(text, diff,i,j,l,n,r,tmp_arr) {
printf("\nreport: %s\n",text)
for (i=1; i<=NR; i++) {
n = split(arr[i],tmp_arr,"$")
if (tmp_arr[n] == "") { n-- }
for (j=1; j<=n; j++) {
if (text ~ /^[Ll]/) { # left
printf("%-*s%s",width,tmp_arr[j],colsep)
}
else if (text ~ /^[Rr]/) { # right
printf("%*s%s",width,tmp_arr[j],colsep)
}
else if (text ~ /^[Cc]/) { # center
diff = width - length(tmp_arr[j])
l = r = int(diff / 2)
if (diff != l + r) { r++ }
printf("%*s%s%*s%s",l,"",tmp_arr[j],r,"",colsep)
}
}
printf("\n")
}
}
function max(x,y) { return((x > y) ? x : y) }
|
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Groovy | Groovy | /**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
class Integrator {
interface Function {
double apply(double timeSinceStartInSeconds)
}
private final long start
private volatile boolean running
private Function func
private double t0
private double v0
private double sum
Integrator(Function func) {
this.start = System.nanoTime()
setFunc(func)
new Thread({ this.&integrate() }).start()
}
void setFunc(Function func) {
this.func = func
def temp = func.apply(0.0.toDouble())
v0 = temp
t0 = 0.0.doubleValue()
}
double getOutput() {
return sum
}
void stop() {
running = false
}
private void integrate() {
running = true
while (running) {
try {
Thread.sleep(1)
update()
} catch (InterruptedException ignored) {
return
}
}
}
private void update() {
double t1 = (System.nanoTime() - start) / 1.0e9
double v1 = func.apply(t1)
double rect = (t1 - t0) * (v0 + v1) / 2.0
this.sum += rect
t0 = t1
v0 = v1
}
static void main(String[] args) {
Integrator integrator = new Integrator({ t -> Math.sin(Math.PI * t) })
Thread.sleep(2000)
integrator.setFunc({ t -> 0.0.toDouble() })
Thread.sleep(500)
integrator.stop()
System.out.println(integrator.getOutput())
}
} |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | seq[n_] :=
NestList[If[# == 0, 0,
DivisorSum[#, # &, Function[div, div != #]]] &, n, 16];
class[seq_] :=
Which[Length[seq] < 2, "Non-terminating", MemberQ[seq, 0],
"Terminating", seq[[1]] == seq[[2]], "Perfect",
Length[seq] > 2 && seq[[1]] == seq[[3]], "Amicable",
Length[seq] > 3 && MemberQ[seq[[4 ;;]], seq[[1]]], "Sociable",
MatchQ[class[Rest[seq]], "Perfect" | "Aspiring"], "Aspiring",
MatchQ[class[Rest[seq]], "Amicable" | "Sociable" | "Cyclic"],
"Cyclic", True, "Non-terminating"];
notate[seq_] :=
Which[seq == {}, {},
MemberQ[Rest[seq],
seq[[1]]], {Prepend[TakeWhile[Rest[seq], # != seq[[1]] &],
seq[[1]]]}, True, Prepend[notate[Rest[seq]], seq[[1]]]];
Print[{#, class[seq[#]], notate[seq[#]] /. {0} -> 0}] & /@ {1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909,
562, 1064, 1488, 15355717786080}; |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #VBA | VBA | Option Explicit
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Declare Sub GetMem4 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Long)
Declare Sub PutMem1 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Byte)
Declare Sub PutMem2 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Integer)
Declare Sub PutMem4 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Long)
Sub Test()
Dim a As Long, ptr As Long, s As Long
a = 12345678
'Get and print address
ptr = VarPtr(a)
Debug.Print ptr
'Peek
Call GetMem4(ptr, s)
Debug.Print s
'Poke
Call PutMem4(ptr, 87654321)
Debug.Print a
End Sub |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Visual_Basic_.NET | Visual Basic .NET | Dim x = 5
Dim ptrX As IntPtr
ptrX = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(Integer)))
Marshal.StructureToPtr(5, ptrX, False)
Dim addressX = ptrX.ToInt64
|
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Wart | Wart | addr.x
=> 27975840 |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #FreeBASIC | FreeBASIC | 'METHOD -- Use the Pascal triangle to retrieve the coefficients
'UPPER LIMIT OF FREEBASIC ULONGINT GETS PRIMES UP TO 70
Sub string_split(s_in As String,char As String,result() As String)
Dim As String s=s_in,var1,var2
Dim As Integer n,pst
#macro split(stri,char,var1,var2)
pst=Instr(stri,char)
var1="":var2=""
If pst<>0 Then
var1=Mid(stri,1,pst-1)
var2=Mid(stri,pst+1)
Else
var1=stri
End If
Redim Preserve result(1 To 1+n-((Len(var1)>0)+(Len(var2)>0)))
result(n+1)=var1
#endmacro
Do
split(s,char,var1,var2):n=n+1:s=var2
Loop Until var2=""
Redim Preserve result(1 To Ubound(result)-1)
End Sub
'Get Pascal triangle components
Function pasc(n As Integer,flag As Integer=0) As String
n+=1
Dim As Ulongint V(n):V(1)=1ul
Dim As String s,sign
For r As Integer= 2 To n
s=""
For i As Integer = r To 1 Step -1
V(i) += V(i-1)
If i Mod 2=1 Then sign="" Else sign="-"
s+=sign+Str(V(i))+","
Next i
Next r
If flag Then 'formatted output
Dim As String i,i2,i3,g
Redim As String a(0)
string_split(s,",",a())
For n1 As Integer=1 To Ubound(a)
If Left(a(n1),1)="-" Then sign="" Else sign="+"
If n1=Ubound(a) Then i2="" Else i2=a(n1)
If n1=2 Then i3="x" Else i3="x^"+Str(n1-1)
If n1=1 Then i="":sign=" " Else i=i3
g+=sign+i2+i+" "
Next n1
g="(x-1)^"+Str(n-1)+" = "+g
Return g
End If
Return s
End Function
Function isprime(num As Integer) As Integer
Redim As String a(0)
string_split(pasc(num),",",a())
For n As Integer=Lbound(a)+1 To Ubound(a)-1
If (Valulng(Ltrim(a(n),"-"))) Mod num<>0 Then Return 0
Next n
Return -1
End Function
'====================================
'Formatted output
For n As Integer=1 To 9
Print pasc(n,1)
Next n
Print
'Limit of Freebasic Ulongint sets about 70 max
Print "Primes up to 70:"
For n As Integer=2 To 70
If isprime(n) Then Print n;
Next n
Sleep |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #Pascal | Pascal | program AdditivePrimes;
{$IFDEF FPC}
{$MODE DELPHI}{$CODEALIGN proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{$DEFINE DO_OUTPUT}
uses
sysutils;
const
RANGE = 500; // 1000*1000;//
MAX_OFFSET = 0; // 1000*1000*1000;//
type
tNum = array [0 .. 15] of byte;
tNumSum = record
dgtNum, dgtSum: tNum;
dgtLen, num: Uint32;
end;
tpNumSum = ^tNumSum;
function isPrime(n: Uint32): boolean;
const
wheeldiff: array [0 .. 7] of Uint32 = (+6, +4, +2, +4, +2, +4, +6, +2);
var
p: NativeUInt;
flipflop: Int32;
begin
if n < 64 then
EXIT(n in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61])
else
begin
IF (n AND 1 = 0) OR (n mod 3 = 0) OR (n mod 5 = 0) then
EXIT(false);
result := true;
p := 1;
flipflop := 6;
while result do
Begin
p := p + wheeldiff[flipflop];
if p * p > n then
BREAK;
result := n mod p <> 0;
flipflop := flipflop - 1;
if flipflop < 0 then
flipflop := 7;
end
end
end;
procedure IncNum(var NumSum: tNumSum; delta: Uint32);
const
BASE = 10;
var
carry, dg: Uint32;
le: Int32;
Begin
if delta = 0 then
EXIT;
le := 0;
with NumSum do
begin
num := num + delta;
repeat
carry := delta div BASE;
delta := delta - BASE * carry;
dg := dgtNum[le] + delta;
IF dg >= BASE then
Begin
dg := dg - BASE;
inc(carry);
end;
dgtNum[le] := dg;
inc(le);
delta := carry;
until carry = 0;
if dgtLen < le then
dgtLen := le;
// correct sum of digits // le is >= 1
delta := dgtSum[le];
repeat
dec(le);
delta := delta + dgtNum[le];
dgtSum[le] := delta;
until le = 0;
end;
end;
var
NumSum: tNumSum;
s: AnsiString;
i, k, cnt, Nr: NativeUInt;
ColWidth, MAXCOLUMNS, NextRowCnt: NativeUInt;
BEGIN
ColWidth := Trunc(ln(MAX_OFFSET + RANGE) / ln(10)) + 2;
MAXCOLUMNS := 80;
NextRowCnt := MAXCOLUMNS DIV ColWidth;
fillchar(NumSum, SizeOf(NumSum), #0);
NumSum.dgtLen := 1;
IncNum(NumSum, MAX_OFFSET);
setlength(s, ColWidth);
fillchar(s[1], ColWidth, ' ');
// init string
with NumSum do
Begin
For i := dgtLen - 1 downto 0 do
s[ColWidth - i] := AnsiChar(dgtNum[i] + 48);
// reset digits lenght to get the max changed digits since last update of string
dgtLen := 0;
end;
cnt := 0;
Nr := NextRowCnt;
For i := 0 to RANGE do
with NumSum do
begin
if isPrime(dgtSum[0]) then
if isPrime(num) then
Begin
cnt := cnt + 1;
dec(Nr);
// correct changed digits in string s
For k := dgtLen - 1 downto 0 do
s[ColWidth - k] := AnsiChar(dgtNum[k] + 48);
dgtLen := 0;
{$IFDEF DO_OUTPUT}
write(s);
if Nr = 0 then
begin
writeln;
Nr := NextRowCnt;
end;
{$ENDIF}
end;
IncNum(NumSum, 1);
end;
if Nr <> NextRowCnt then
write(#10);
writeln(cnt, ' additive primes found.');
END.
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Maple | Maple | AlmostPrimes:=proc(k, numvalues::posint:=10)
local aprimes, i, intfactors;
aprimes := Array([]);
i := 0;
do
i := i + 1;
intfactors := ifactors(i)[2];
intfactors := [seq(seq(intfactors[i][1], j=1..intfactors[i][2]),i = 1..numelems(intfactors))];
if numelems(intfactors) = k then
ArrayTools:-Append(aprimes,i);
end if;
until numelems(aprimes) = 10:
aprimes;
end proc:
<seq( AlmostPrimes(i), i = 1..5 )>; |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NN,KK)
ENTRY TO KPRIME.
F = 0
N = NN
THROUGH SCAN, FOR P=2, 1, F.GE.KK .OR. P*P.G.N
DIV WHENEVER N.E.N/P*P
N = N/P
F = F+1
TRANSFER TO DIV
END OF CONDITIONAL
SCAN CONTINUE
WHENEVER N.G.1, F = F+1
FUNCTION RETURN F.E.KK
END OF FUNCTION
VECTOR VALUES KFMT = $5(S1,2HK=,I1,S1)*$
VECTOR VALUES PFMT = $5(I4,S1)*$
PRINT FORMAT KFMT, 1, 2, 3, 4, 5
DIMENSION KPR(50)
THROUGH FNDKPR, FOR K=1, 1, K.G.5
C=0
THROUGH FNDKPR, FOR I=2, 1, C.GE.10
WHENEVER KPRIME.(I,K)
KPR(C*5+K) = I
C = C+1
END OF CONDITIONAL
FNDKPR CONTINUE
THROUGH OUT, FOR C=0, 1, C.GE.10
OUT PRINT FORMAT PFMT, KPR(C*5+1), KPR(C*5+2), KPR(C*5+3),
0 KPR(C*5+4), KPR(C*5+5)
END OF PROGRAM |
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
| #Elixir | Elixir | defmodule Anagrams do
def find(file) do
File.read!(file)
|> String.split
|> Enum.group_by(fn word -> String.codepoints(word) |> Enum.sort end)
|> Enum.group_by(fn {_,v} -> length(v) end)
|> Enum.max
|> print
end
defp print({_,y}) do
Enum.each(y, fn {_,e} -> Enum.sort(e) |> Enum.join(" ") |> IO.puts end)
end
end
Anagrams.find("unixdict.txt") |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Scala | Scala | object AngleDifference extends App {
private def getDifference(b1: Double, b2: Double) = {
val r = (b2 - b1) % 360.0
if (r < -180.0) r + 360.0 else if (r >= 180.0) r - 360.0 else r
}
println("Input in -180 to +180 range")
println(getDifference(20.0, 45.0))
println(getDifference(-45.0, 45.0))
println(getDifference(-85.0, 90.0))
println(getDifference(-95.0, 90.0))
println(getDifference(-45.0, 125.0))
println(getDifference(-45.0, 145.0))
println(getDifference(-45.0, 125.0))
println(getDifference(-45.0, 145.0))
println(getDifference(29.4803, -88.6381))
println(getDifference(-78.3251, -159.036))
println("Input in wider range")
println(getDifference(-70099.74233810938, 29840.67437876723))
println(getDifference(-165313.6666297357, 33693.9894517456))
println(getDifference(1174.8380510598456, -154146.66490124757))
println(getDifference(60175.77306795546, 42213.07192354373))
} |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
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 cxr)
(scheme file)
(scheme write)
(srfi 1) ; lists
(srfi 132)) ; sorting library
;; read in word list, and sort into decreasing length
(define (read-ordered-words)
(with-input-from-file
"unixdict.txt"
(lambda ()
(do ((line (read-line) (read-line))
(words '() (cons line words)))
((eof-object? line)
(list-sort (lambda (a b) (> (string-length a) (string-length b)))
words))))))
(define (find-deranged-words word-list)
(define (search words)
(let loop ((word-chars (let ((chars (map string->list words)))
(zip chars
(map (lambda (word) (list-sort char<? word))
chars)))))
(if (< (length word-chars) 2)
#f ; failed to find any
(let ((deranged-word ; seek a deranged version of the first word in word-chars
(find (lambda (chars)
(and (equal? (cadar word-chars) (cadr chars)) ; check it's an anagram?
(not (any char=? (caar word-chars) (car chars))))) ; and deranged?
word-chars)))
(if deranged-word ; if we got one, return it with the first word
(map list->string (list (caar word-chars) (car deranged-word)))
(loop (cdr word-chars)))))))
;
(let loop ((rem word-list))
(if (null? rem)
'()
(let* ((len (string-length (car rem)))
(deranged-words (search ; look through group of equal sized words
(take-while (lambda (word) (= len (string-length word)))
(cdr rem)))))
(if deranged-words
deranged-words
(loop (drop-while (lambda (word) (= len (string-length word)))
(cdr rem))))))))
(display (find-deranged-words (read-ordered-words))) (newline) |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #PostScript | PostScript | % primitive recursion
/pfact {
{1} {*} primrec}.
%linear recursion
/lfact {
{dup 0 eq}
{pop 1}
{dup pred}
{*}
linrec}.
% general recursion
/gfact {
{0 eq}
{succ}
{dup pred}
{i *}
genrec}.
% binary recursion
/fib {
{2 lt} {} {pred dup pred} {+} binrec}. |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Phixmonti | Phixmonti | def sumDivs
var n
1 var sum n sqrt
2 swap 2 tolist
for
var d
n d mod not if
sum d + n d / + var sum
endif
endfor
sum
enddef
2 20000 2 tolist for
var i
i sumDivs var m
m i > if
m sumDivs i == if i print "\t" print m print nl endif
endif
endfor
nl msec print " s" print |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #RLaB | RLaB |
//
// example: solve ODE for pendulum
//
// we first define the first derivative function for the solver
dudt = function(t, u, p)
{
// t-> time
// u->[theta, dtheta/dt ]
// p-> g/L, parameter
rval = zeros(2,1);
rval[1] = u[2];
rval[2] = -p[1] * sin(u[1]);
return rval;
};
// now we solve the problem
// physical parameters
L = 5; // (m), the length of the arm of the pendulum
p = mks.g / L; // RLaB has a built-in list 'mks' which contains large number of physical constants and conversion factors
T0 = 2*const.pi*sqrt(L/mks.g); // approximate period of the pendulum
// initial conditions
theta0 = 30; // degrees, initial angle of deflection of pendulum
u0 = [theta0*const.pi/180, 0]; // RLaB has a built-in list 'const' of mathematical constants.
// times at which we want solution
t = [0:4:1/64] * T0; // solve for 4 approximate periods with at time points spaced at T0/64
// prepare ODEIV solver
optsode = <<>>;
optsode.eabs = 1e-6; // relative error for step size
optsode.erel = 1e-6; // absolute error for step size
optsode.delta_t = 1e-6; // maximum dt that code is allowed
optsode.stdout = stderr(); // open the text console and in it print the results of each step of calculation
optsode.imethod = 5; // use method No. 5 from the odeiv toolkit, Runge-Kutta 8th order Prince-Dormand method
//optsode.phase_space = 0; // the solver returns [t, u1(t), u2(t)] which is default behavior
optsode.phase_space = 1; // the solver returns [t, u1(t), u2(t), d(u1)/dt(t), d(u2)/dt]
// solver do my bidding
y = odeiv(dudt, p, t, u0, optsode);
// Make an animation. We choose to use 'pgplot' rather then 'gnuplot' interface because the former is
// faster and thus less cache-demanding, while the latter can be very cache-demanding (it may slow your
// linux system quite down if one sends lots of plots for gnuplot to plot).
plwins (1); // we will use one pgplot-window
plwin(1); // plot to pgplot-window No. 1; necessary if using more than one pgplot window
plimits (-L,L, -1.25*L, 0.25*L);
xlabel ("x-coordinate");
ylabel ("z-coordinate");
plegend ("Arm");
for (i in 1:y.nr)
{
// plot a line between the pivot point at (0,0) and the current position of the pendulum
arm_line = [0,0; L*sin(y[i;2]), -L*cos(y[i;2])]; // this is because theta is between the arm and the z-coordinate
plot (arm_line);
sleep (0.1); // sleep 0.1 seconds between plots
}
|
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Latitude | Latitude | ;; This is the exception that will be thrown if an amb expression is
;; unsatisfiable.
AmbError ::= Exception clone tap {
self message := "Amb expression failed".
AmbError := self.
}.
;; The Amb object itself is primarily for internal use. It stores the
;; "next" backtracking point if an amb expression outright fails or
;; exhausts its possibilities at some point.
Amb ::= Object clone tap {
;; The default "next" point is to throw an exception. This will be
;; overridden in many cases, if there is an actual next handler to
;; jump to.
self nextHandler := { AmbError clone throw. }.
Amb := self.
}.
callAmb := {
;; We need an object which will be accessible from inside the
;; continuations that will store the next backtracking point which
;; will be called.
backtracker := Amb clone.
;; We define the dynamically-scoped method $amb which will try each
;; possibility that it is given. If all of those possibilities fail,
;; it will call the next handler.
$amb := {
takes '[cases].
;; This is the return point. We're going to try each element of
;; the cases variable (probably an array, but it could feasibly be
;; any collection type). For each element, we'll jump to this
;; point (which will wind up being the end of the $amb method). If
;; it ends up failing, the backtrack point will get called and
;; we'll try the next one.
callCC {
escapable.
;; Get the current backtrack point from the toplevel object and
;; store it within this continuation. The backtrack object's
;; current backtrack point will change as we make new attempts,
;; but this prevHandler variable is stored locally in this scope
;; and will not change, so we can always use it later.
prevHandler := #'(backtracker nextHandler).
;; We iterate over the collection to try each element.
cases visit {
takes '[curr].
callCC {
;; This inner continuation will be our new backtrack point.
;; We store the continuation object itself in the backtrack
;; object so that future $amb calls know to return to this
;; point if something goes wrong.
nextExit := #'$1.
backtracker nextHandler := { nextExit call (Nil). }.
;; Now we actually try the value by jumping to the end of
;; the $amb method and returning control to the caller.
return (curr).
}.
}.
;; If we exhaust each possibility, then that means every value
;; in the cases variable has been tried and has failed. So we
;; set the backtrack point back to what it was before we tried
;; all of these values, and then we jump back to that previous
;; backtrack point.
backtracker nextHandler := #'(prevHandler).
prevHandler.
;; prevHandler will always either perform a continuation jump
;; (if there is a new backtrack point to try) or throw an
;; exception (if we've exhausted all possibilities), so this
;; continuation block will never exit normally.
}.
}.
;; An instant failure at a point in an amb expression is equivalent
;; to an $amb call on an empty collection.
$fail := { $amb (Nil). }.
;; Now that the dynamic variables are in place, let's call the
;; block.
#'($1) call.
}. |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | accum n:
labda i:
set :n + n i
n
local :x accum 1
drop x 5
drop accum 3
!print x 2.3 |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Delphi | Delphi |
program Accumulator_factory;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Variants;
type
TFn = TFunc<variant, variant>;
function Foo(n: variant): TFn;
begin
Result :=
function(i: variant): variant
begin
n:= n + i;
Result := n;
end;
end;
begin
var x := Foo(1);
x(5);
Foo(3); // do nothing
Writeln(x(2.3));
Readln;
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.
| #ABAP | ABAP |
REPORT zhuberv_ackermann.
CLASS zcl_ackermann DEFINITION.
PUBLIC SECTION.
CLASS-METHODS ackermann IMPORTING m TYPE i
n TYPE i
RETURNING value(v) TYPE i.
ENDCLASS. "zcl_ackermann DEFINITION
CLASS zcl_ackermann IMPLEMENTATION.
METHOD: ackermann.
DATA: lv_new_m TYPE i,
lv_new_n TYPE i.
IF m = 0.
v = n + 1.
ELSEIF m > 0 AND n = 0.
lv_new_m = m - 1.
lv_new_n = 1.
v = ackermann( m = lv_new_m n = lv_new_n ).
ELSEIF m > 0 AND n > 0.
lv_new_m = m - 1.
lv_new_n = n - 1.
lv_new_n = ackermann( m = m n = lv_new_n ).
v = ackermann( m = lv_new_m n = lv_new_n ).
ENDIF.
ENDMETHOD. "ackermann
ENDCLASS. "zcl_ackermann IMPLEMENTATION
PARAMETERS: pa_m TYPE i,
pa_n TYPE i.
DATA: lv_result TYPE i.
START-OF-SELECTION.
lv_result = zcl_ackermann=>ackermann( m = pa_m n = pa_n ).
WRITE: / lv_result.
|
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
| #Arturo | Arturo | properDivisors: function [n]->
(factors n) -- n
abundant: new 0 deficient: new 0 perfect: new 0
loop 1..20000 'x [
s: sum properDivisors x
case [s]
when? [<x] -> inc 'deficient
when? [>x] -> inc 'abundant
else -> inc 'perfect
]
print ["Found" abundant "abundant,"
deficient "deficient and"
perfect "perfect numbers."] |
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
| #BaCon | BaCon |
DECLARE in$[] = { "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." }
OPTION DELIM "$"
CONST items = 6
SUB Print_In_Columns(style)
' Find widest column
FOR y = 0 TO items-1
FOR x = 1 TO AMOUNT(in$[y])
IF LEN(TOKEN$(in$[y], x)) > max THEN max = LEN(TOKEN$(in$[y], x))
NEXT
NEXT
' Print aligned
FOR y = 0 TO items-1
FOR x = 1 TO AMOUNT(in$[y])
PRINT ALIGN$(TOKEN$(in$[y], x), max+1, style);
NEXT
PRINT
NEXT
PRINT
END SUB
Print_In_Columns(0)
Print_In_Columns(1)
Print_In_Columns(2)
|
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Haskell | Haskell | module Integrator (
newIntegrator, input, output, stop,
Time, timeInterval
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, modifyMVar, readMVar)
import Control.Exception (evaluate)
import Data.Time (UTCTime)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
-- RC task
main = do let f = 0.5 {- Hz -}
t0 <- getCurrentTime
i <- newIntegrator
input i (\t -> sin(2*pi * f * timeInterval t0 t)) -- task step 1
threadDelay 2000000 {- µs -} -- task step 2
input i (const 0) -- task step 3
threadDelay 500000 {- µs -} -- task step 4
result <- output i
stop i
print result
---- Implementation ------------------------------------------------------
-- Utilities for working with the time type
type Time = UTCTime
type Func a = Time -> a
timeInterval t0 t1 = realToFrac $ diffUTCTime t1 t0
-- Type signatures of the module's interface
newIntegrator :: Fractional a => IO (Integrator a) -- Create an integrator
input :: Integrator a -> Func a -> IO () -- Set the input function
output :: Integrator a -> IO a -- Get the current value
stop :: Integrator a -> IO () -- Stop integration, don't waste CPU
-- Data structures
data Integrator a = Integrator (MVar (IntState a)) -- MVar is a thread-safe mutable cell
deriving Eq
data IntState a = IntState { func :: Func a, -- The current function
run :: Bool, -- Whether to keep going
value :: a, -- The current accumulated value
time :: Time } -- The time of the previous update
newIntegrator = do
now <- getCurrentTime
state <- newMVar $ IntState { func = const 0,
run = True,
value = 0,
time = now }
thread <- forkIO (intThread state) -- The state variable is shared between the thread
return (Integrator state) -- and the client interface object.
input (Integrator stv) f = modifyMVar_ stv (\st -> return st { func = f })
output (Integrator stv) = fmap value $ readMVar stv
stop (Integrator stv) = modifyMVar_ stv (\st -> return st { run = False })
-- modifyMVar_ takes an MVar and replaces its contents according to the provided function.
-- a { b = c } is record-update syntax: "the record a, except with field b changed to c"
-- Integration thread
intThread :: Fractional a => MVar (IntState a) -> IO ()
intThread stv = whileM $ modifyMVar stv updateAndCheckRun
-- modifyMVar is like modifyMVar_ but the function returns a tuple of the new value
-- and an arbitrary extra value, which in this case ends up telling whileM whether
-- to keep looping.
where updateAndCheckRun st = do
now <- getCurrentTime
let value' = integrate (func st) (value st) (time st) now
evaluate value' -- avoid undesired laziness
return (st { value = value', time = now }, -- updated state
run st) -- whether to continue
integrate :: Fractional a => Func a -> a -> Time -> Time -> a
integrate f value t0 t1 = value + (f t0 + f t1)/2 * dt
where dt = timeInterval t0 t1
-- Execute 'action' until it returns false.
whileM action = do b <- action; if b then whileM action else return () |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Nim | Nim |
import math
import strformat
from strutils import addSep
import times
type
# Classification categories.
Category = enum
Unknown
Terminating = "terminating"
Perfect = "perfect"
Amicable = "amicable"
Sociable = "sociable"
Aspiring = "aspiring"
Cyclic = "cyclic"
NonTerminating = "non-terminating"
# Aliquot sequence.
AliquotSeq = seq[int]
const Limit = 2^47 # Limit beyond which the category is considered to be "NonTerminating".
#---------------------------------------------------------------------------------------------------
proc sumProperDivisors(n: int): int =
## Compute the sum of proper divisors.*
if n == 1: return 0
result = 1
for d in 2..sqrt(n.toFloat).int:
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
#---------------------------------------------------------------------------------------------------
iterator aliquotSeq(n: int): int =
## Yield the elements of the aliquot sequence of "n".
## Stopped if the current value is null or equal to "n".
var k = n
while true:
k = sumProperDivisors(k)
yield k
#---------------------------------------------------------------------------------------------------
proc `$`(a: AliquotSeq): string =
## Return the representation of an allquot sequence.
for n in a:
result.addSep(", ", 0)
result.addInt(n)
#---------------------------------------------------------------------------------------------------
proc classification(n: int): tuple[cat: Category, values: AliquotSeq] =
## Return the category of the aliquot sequence of a number "n" and the sequence itself.
var count = 0 # Number of elements currently generated.
var prev = n # Previous element in the sequence.
result.cat = Unknown
for k in aliquotSeq(n):
inc count
if k == 0:
result.cat = Terminating
elif k == n:
result.cat = case count
of 1: Perfect
of 2: Amicable
else: Sociable
elif k > Limit or count > 16:
result.cat = NonTerminating
elif k == prev:
result.cat = Aspiring
elif k in result.values:
result.cat = Cyclic
prev = k
result.values.add(k)
if result.cat != Unknown:
break
#---------------------------------------------------------------------------------------------------
let t0 = getTime()
for n in 1..10:
let (cat, aseq) = classification(n)
echo fmt"{n:14}: {cat:<20} {aseq}"
echo ""
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488, 15355717786080.int]:
let (cat, aseq) = classification(n)
echo fmt"{n:14}: {cat:<20} {aseq}"
echo ""
echo fmt"Processed in {(getTime() - t0).inMilliseconds} ms."
|
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Wren | Wren | var a = [1, 2, 3, 4]
var b = a // now 'a' and 'b' both point to the same List data
b[3] = 5
System.print("'b' is %(b)")
System.print("'a' is %(a)") // the previous change is of course reflected in 'a' as well
var t = Object.same(a, b) // tells you whether 'a' and 'b' refer to the same object in memory
System.print("'a' and 'b' are the same object? %(t ? "yes" : "no")") |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #X86_Assembly | X86 Assembly | movl my_variable, %eax |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #XLISP | XLISP | (%ADDRESS-OF X) |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Go | Go | package main
import "fmt"
func bc(p int) []int64 {
c := make([]int64, p+1)
r := int64(1)
for i, half := 0, p/2; i <= half; i++ {
c[i] = r
c[p-i] = r
r = r * int64(p-i) / int64(i+1)
}
for i := p - 1; i >= 0; i -= 2 {
c[i] = -c[i]
}
return c
}
func main() {
for p := 0; p <= 7; p++ {
fmt.Printf("%d: %s\n", p, pp(bc(p)))
}
for p := 2; p < 50; p++ {
if aks(p) {
fmt.Print(p, " ")
}
}
fmt.Println()
}
var e = []rune("²³⁴⁵⁶⁷")
func pp(c []int64) (s string) {
if len(c) == 1 {
return fmt.Sprint(c[0])
}
p := len(c) - 1
if c[p] != 1 {
s = fmt.Sprint(c[p])
}
for i := p; i > 0; i-- {
s += "x"
if i != 1 {
s += string(e[i-2])
}
if d := c[i-1]; d < 0 {
s += fmt.Sprintf(" - %d", -d)
} else {
s += fmt.Sprintf(" + %d", d)
}
}
return
}
func aks(p int) bool {
c := bc(p)
c[p]--
c[0]++
for _, d := range c {
if d%int64(p) != 0 {
return false
}
}
return true
} |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #Perl | Perl | use strict;
use warnings;
use ntheory 'is_prime';
use List::Util <sum max>;
sub pp {
my $format = ('%' . (my $cw = 1+length max @_) . 'd') x @_;
my $width = ".{@{[$cw * int 60/$cw]}}";
(sprintf($format, @_)) =~ s/($width)/$1\n/gr;
}
my($limit, @ap) = 500;
is_prime($_) and is_prime(sum(split '',$_)) and push @ap, $_ for 1..$limit;
print @ap . " additive primes < $limit:\n" . pp(@ap); |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #Phix | Phix | with javascript_semantics
function additive(string p) return is_prime(sum(sq_sub(p,'0'))) end function
sequence res = filter(apply(get_primes_le(500),sprint),additive)
printf(1,"%d additive primes found: %s\n",{length(res),join(shorten(res,"",6))})
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | kprimes[k_,n_] :=
(* generates a list of the n smallest k-almost-primes *)
Module[{firstnprimes, runningkprimes = {}},
firstnprimes = Prime[Range[n]];
runningkprimes = firstnprimes;
Do[
runningkprimes =
Outer[Times, firstnprimes , runningkprimes ] // Flatten // Union // Take[#, n] & ;
(* only keep lowest n numbers in our running list *)
, {i, 1, k - 1}];
runningkprimes
]
(* now to create table with n=10 and k ranging from 1 to 5 *)
Table[Flatten[{"k = " <> ToString[i] <> ": ", kprimes[i, 10]}], {i,1,5}] // TableForm |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Modula-2 | Modula-2 | MODULE AlmostPrime;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE KPrime(n,k : INTEGER) : BOOLEAN;
VAR p,f : INTEGER;
BEGIN
f := 0;
p := 2;
WHILE (f<k) AND (p*p<=n) DO
WHILE n MOD p = 0 DO
n := n DIV p;
INC(f)
END;
INC(p)
END;
IF n>1 THEN
RETURN f+1 = k
END;
RETURN f = k
END KPrime;
VAR
buf : ARRAY[0..63] OF CHAR;
i,c,k : INTEGER;
BEGIN
FOR k:=1 TO 5 DO
FormatString("k = %i:", buf, k);
WriteString(buf);
i:=2;
c:=0;
WHILE c<10 DO
IF KPrime(i,k) THEN
FormatString(" %i", buf, i);
WriteString(buf);
INC(c)
END;
INC(i)
END;
WriteLn;
END;
ReadChar;
END AlmostPrime. |
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
| #Erlang | Erlang | -module(anagrams).
-compile(export_all).
play() ->
{ok, P} = file:read_file('unixdict.txt'),
D = dict:new(),
E=fetch(string:tokens(binary_to_list(P), "\n"), D),
get_value(dict:fetch_keys(E), E).
fetch([H|T], D) ->
fetch(T, dict:append(lists:sort(H), H, D));
fetch([], D) ->
D.
get_value(L, D) -> get_value(L,D,1,[]).
get_value([H|T], D, N, L) ->
Var = dict:fetch(H,D),
Len = length(Var),
if
Len > N ->
get_value(T, D, Len, [Var]);
Len == N ->
get_value(T, D, Len, [Var | L]);
Len < N ->
get_value(T, D, N, L)
end;
get_value([], _, _, L) ->
L.
|
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Scheme | Scheme | #!r6rs
(import (rnrs base (6))
(rnrs io simple (6)))
(define (bearing-difference bearing-2 bearing-1)
(- (mod (+ (mod (- bearing-2 bearing-1)
360)
540)
360)
180))
(define (bearing-difference-test)
(define test-cases
'((20 45)
(-45 45)
(-85 90)
(-95 90)
(-45 125)
(-45 145)
(29.4803 -88.6381)
(-78.3251 -159.036)
(-70099.74233810938 29840.67437876723)
(-165313.6666297357 33693.9894517456)
(1174.8380510598456 -154146.66490124757)
(60175.77306795546 42213.07192354373)))
(for-each
(lambda (argument-list)
(display (apply bearing-difference argument-list))
(newline))
test-cases)) |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
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 find_deranged(Array a) {
for i in (^a) {
for j in (i+1 .. a.end) {
overlaps(a[i], a[j]) || (
printf("length %d: %s => %s\n", a[i].len, a[i], a[j])
return true
)
}
}
return false
}
func main(File file) {
file.open_r(\var fh, \var err) ->
|| die "Can't open file `#{file}' for reading: #{err}\n"
var letter_list = Hash()
# Store anagrams in hash table by letters they contain
fh.words.each { |word|
letter_list{word.sort} := [] << word
}
letter_list.keys \
.grep {|k| letter_list{k}.len > 1} \ # take only ones with anagrams
.sort {|a,b| b.len <=> a.len} \ # sort by length, descending
.each {|key|
# If we find a pair, they are the longested due to the sort before
find_deranged(letter_list{key}) && break
}
}
main(%f'/tmp/unixdict.txt') |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Prolog | Prolog | :- use_module(lambda).
fib(N, _F) :-
N < 0, !,
write('fib is undefined for negative numbers.'), nl.
fib(N, F) :-
% code of Fibonacci
PF = \Nb^R^Rr1^(Nb < 2 ->
R = Nb
;
N1 is Nb - 1,
N2 is Nb - 2,
call(Rr1,N1,R1,Rr1),
call(Rr1,N2,R2,Rr1),
R is R1 + R2
),
% The Y combinator.
Pred = PF +\Nb2^F2^call(PF,Nb2,F2,PF),
call(Pred,N,F). |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #PHP | PHP | <?php
function sumDivs ($n) {
$sum = 1;
for ($d = 2; $d <= sqrt($n); $d++) {
if ($n % $d == 0) $sum += $n / $d + $d;
}
return $sum;
}
for ($n = 2; $n < 20000; $n++) {
$m = sumDivs($n);
if ($m > $n) {
if (sumDivs($m) == $n) echo $n." ".$m."<br />";
}
}
?> |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Ruby | Ruby | require 'tk'
$root = TkRoot.new("title" => "Pendulum Animation")
$canvas = TkCanvas.new($root) do
width 320
height 200
create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'
create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => "", 'fill' => 'grey50'
create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' => 3, 'fill' => 'black'
create TkcOval, 1,1,2,2, 'tags' => 'bob', 'outline' => 'black', 'fill' => 'yellow'
end
$canvas.raise('pivot')
$canvas.pack('fill' => 'both', 'expand' => true)
$Theta = 45.0
$dTheta = 0.0
$length = 150
$homeX = 160
$homeY = 25
def show_pendulum
angle = $Theta * Math::PI / 180
x = $homeX + $length * Math.sin(angle)
y = $homeY + $length * Math.cos(angle)
$canvas.coords('rod', $homeX, $homeY, x, y)
$canvas.coords('bob', x-15, y-15, x+15, y+15)
end
def recompute_angle
scaling = 3000.0 / ($length ** 2)
# first estimate
firstDDTheta = -Math.sin($Theta * Math::PI / 180) * scaling
midDTheta = $dTheta + firstDDTheta
midTheta = $Theta + ($dTheta + midDTheta)/2
# second estimate
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
midDTheta = $dTheta + (firstDDTheta + midDDTheta)/2
midTheta = $Theta + ($dTheta + midDTheta)/2
# again, first
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
lastDTheta = midDTheta + midDDTheta
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# again, second
lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# Now put the values back in our globals
$dTheta = lastDTheta
$Theta = lastTheta
end
def animate
recompute_angle
show_pendulum
$after_id = $root.after(15) {animate}
end
show_pendulum
$after_id = $root.after(500) {animate}
$canvas.bind('<Destroy>') {$root.after_cancel($after_id)}
Tk.mainloop |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Lua | Lua | function amb (set)
local workset = {}
if (#set == 0) or (type(set) ~= 'table') then return end
if #set == 1 then return set end
if #set > 2 then
local first = table.remove(set,1)
set = amb(set)
for i,v in next,first do
for j,u in next,set do
if v:byte(#v) == u[1]:byte(1) then table.insert(workset, {v,unpack(u)}) end
end
end
return workset
end
for i,v in next,set[1] do
for j,u in next,set[2] do
if v:byte(#v) == u:byte(1) then table.insert(workset,{v,u}) end
end
end
return workset
end |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #E | E | def foo(var x) {
return fn y { x += y }
} |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #EchoLisp | EchoLisp |
(define-syntax-rule (inc x v) (set! x (+ x v)))
(define (accumulator (sum 0)) (lambda(x) (inc sum x) sum))
(define x (accumulator 1)) → x
(x 5) → 6
;; another closure
(accumulator 3) → (🔒 λ (_x) (📝 #set! sum (#+ sum _x)) sum)
(x 2.3) → 8.3
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Action.21 | Action! | DEFINE MAXSIZE="1000"
CARD ARRAY stack(MAXSIZE)
CARD stacksize=[0]
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Push(BYTE v)
IF stacksize=maxsize THEN
PrintE("Error: stack is full!")
Break()
FI
stack(stacksize)=v
stacksize==+1
RETURN
BYTE FUNC Pop()
IF IsEmpty() THEN
PrintE("Error: stack is empty!")
Break()
FI
stacksize==-1
RETURN (stack(stacksize))
CARD FUNC Ackermann(CARD m,n)
Push(m)
WHILE IsEmpty()=0
DO
m=Pop()
IF m=0 THEN
n==+1
ELSEIF n=0 THEN
n=1
Push(m-1)
ELSE
n==-1
Push(m-1)
Push(m)
FI
OD
RETURN (n)
PROC Main()
CARD m,n,res
FOR m=0 TO 3
DO
FOR n=0 TO 4
DO
res=Ackermann(m,n)
PrintF("Ack(%U,%U)=%U%E",m,n,res)
OD
OD
RETURN |
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
| #AutoHotkey | AutoHotkey | Loop
{
m := A_index
; getting factors=====================
loop % floor(sqrt(m))
{
if ( mod(m, A_index) == "0" )
{
if ( A_index ** 2 == m )
{
list .= A_index . ":"
sum := sum + A_index
continue
}
if ( A_index != 1 )
{
list .= A_index . ":" . m//A_index . ":"
sum := sum + A_index + m//A_index
}
if ( A_index == "1" )
{
list .= A_index . ":"
sum := sum + A_index
}
}
}
; Factors obtained above===============
if ( sum == m ) && ( sum != 1 )
{
result := "perfect"
perfect++
}
if ( sum > m )
{
result := "Abundant"
Abundant++
}
if ( sum < m ) or ( m == "1" )
{
result := "Deficient"
Deficient++
}
if ( m == 20000 )
{
MsgBox % "number: " . m . "`nFactors:`n" . list . "`nSum of Factors: " . Sum . "`nResult: " . result . "`n_______________________`nTotals up to: " . m . "`nPerfect: " . perfect . "`nAbundant: " . Abundant . "`nDeficient: " . Deficient
ExitApp
}
list := ""
sum := 0
}
esc::ExitApp
|
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
| #BASIC | BASIC | DATA 6
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
DATA "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
DATA "column$are$separated$by$at$least$one$space."
DATA "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
DATA "justified,$right$justified,$or$center$justified$within$its$column."
REM First find the maximum length of a 'word':
max% = 0
READ nlines%
FOR Line% = 1 TO nlines%
READ text$
REPEAT
word$ = FNword(text$, "$")
IF LEN(word$) > max% THEN max% = LEN(word$)
UNTIL word$ = ""
NEXT Line%
@% = max% : REM set column width
REM Now display the aligned text:
RESTORE
READ nlines%
FOR Line% = 1 TO nlines%
READ text$
REPEAT
word$ = FNword(text$, "$")
PRINT FNjustify(word$, max%, "left"),;
UNTIL word$ = ""
PRINT
NEXT Line%
END
DEF FNword(text$, delim$)
PRIVATE delim%
LOCAL previous%
IF delim% = 0 THEN
previous% = 1
ELSE
previous% = delim% + LEN(delim$)
ENDIF
delim% = INSTR(text$+delim$, delim$, previous%)
IF delim% = 0 THEN
= ""
ELSE
= MID$(text$, previous%, delim%-previous%) + " "
ENDIF
DEF FNjustify(word$, field%, mode$)
IF word$ = "" THEN = ""
CASE mode$ OF
WHEN "center": = STRING$((field%-LEN(word$)) DIV 2, " ") + word$
WHEN "right": = STRING$(field%-LEN(word$), " ") + word$
ENDCASE
= word$ |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #J | J | coclass 'activeobject'
require'dates'
create=:setinput NB. constructor
T=:3 :0
if. nc<'T0' do. T0=:tsrep 6!:0'' end.
0.001*(tsrep 6!:0'')-T0
)
F=:G=:0:
Zero=:0
setinput=:3 :0
zero=. getoutput''
'`F ignore'=: y,_:`''
G=: F f.d._1
Zero=: zero-G T ''
getoutput''
)
getoutput=:3 :0
Zero+G T''
) |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Java | Java | /**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
public class Integrator {
public interface Function {
double apply(double timeSinceStartInSeconds);
}
private final long start;
private volatile boolean running;
private Function func;
private double t0;
private double v0;
private double sum;
public Integrator(Function func) {
this.start = System.nanoTime();
setFunc(func);
new Thread(this::integrate).start();
}
public void setFunc(Function func) {
this.func = func;
v0 = func.apply(0.0);
t0 = 0;
}
public double getOutput() {
return sum;
}
public void stop() {
running = false;
}
private void integrate() {
running = true;
while (running) {
try {
Thread.sleep(1);
update();
} catch (InterruptedException e) {
return;
}
}
}
private void update() {
double t1 = (System.nanoTime() - start) / 1.0e9;
double v1 = func.apply(t1);
double rect = (t1 - t0) * (v0 + v1) / 2;
this.sum += rect;
t0 = t1;
v0 = v1;
}
public static void main(String[] args) throws InterruptedException {
Integrator integrator = new Integrator(t -> Math.sin(Math.PI * t));
Thread.sleep(2000);
integrator.setFunc(t -> 0.0);
Thread.sleep(500);
integrator.stop();
System.out.println(integrator.getOutput());
}
}
|
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Oforth | Oforth | import: mapping
import: quicksort
import: math
Object method: sum ( coll -- m )
#+ self reduce dup ifNull: [ drop 0 ] ;
Integer method: properDivs
| i l |
Array new dup 1 over add ->l
2 self nsqrt tuck for: i [ self i mod ifFalse: [ i l add self i / l add ] ]
sq self == ifTrue: [ l pop drop ]
dup sort
;
: aliquot( n -- [] ) \ Returns aliquot sequence of n
| end l |
2 47 pow ->end
Array new dup n over add ->l
while ( l size 16 < l last 0 <> and l last end <= and ) [ l last properDivs sum l add ]
;
: aliquotClass( n -- [] s ) \ Returns aliquot sequence and classification
| l i j |
n aliquot dup ->l
l last 0 == ifTrue: [ "terminate" return ]
l second n == ifTrue: [ "perfect" return ]
3 l at n == ifTrue: [ "amicable" return ]
l indexOfFrom(n, 2) ifNotNull: [ "sociable" return ]
l size loop: i [
l indexOfFrom(l at(i), i 1+ ) -> j
j i 1+ == ifTrue: [ "aspiring" return ]
j ifNotNull: [ "cyclic" return ]
]
"non-terminating"
; |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int A, B;
[B:= addr A;
HexOut(0, B); CrLf(0);
B(0):= $1234ABCD;
HexOut(0, A); CrLf(0);
] |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Yorick | Yorick | > foo = 1
> bar = &foo
> bar
0x15f42c18
> baz = bar
> *baz = 5
> *bar
5
> *baz
5 |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Z80_Assembly | Z80 Assembly | foo equ &C000
bar equ &C001
ld (foo),a ;store A into memory location &C000
ld a,b ;copy B to A
ld (bar),a ;store "B" into memory location &C001 |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Zig | Zig | const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var i: i32 = undefined;
var address_of_i: *i32 = &i;
try stdout.print("{x}\n", .{@ptrToInt(address_of_i)});
} |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Haskell | Haskell | expand p = scanl (\z i -> z * (p-i+1) `div` i) 1 [1..p]
test p | p < 2 = False
| otherwise = and [mod n p == 0 | n <- init . tail $ expand p]
printPoly [1] = "1"
printPoly p = concat [ unwords [pow i, sgn (l-i), show (p!!(i-1))]
| i <- [l-1,l-2..1] ] where
l = length p
sgn i = if even i then "+" else "-"
pow i = take i "x^" ++ if i > 1 then show i else ""
main = do
putStrLn "-- p: (x-1)^p for small p"
putStrLn $ unlines [show i ++ ": " ++ printPoly (expand i) | i <- [0..10]]
putStrLn "-- Primes up to 100:"
print (filter test [1..100]) |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def isprime
dup 1 <= if drop false
else dup 2 == not if
( dup sqrt 2 swap ) for
over swap mod not if drop false exitfor endif
endfor
endif
endif
false == not
enddef
def digitsum
0 swap dup 0 > while dup 10 mod rot + swap 10 / int dup 0 > endwhile
drop
enddef
0 500 for
dup isprime over digitsum isprime and if print " " print 1 + else drop endif
endfor
"Additive primes found: " print print
|
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #PicoLisp | PicoLisp | (de prime? (N)
(let D 0
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(for (D 3 T (+ D 2))
(T (> D (sqrt N)) T)
(T (=0 (% N D)) NIL) ) ) ) ) )
(de additive (N)
(and
(prime? N)
(prime? (sum format (chop N))) ) )
(let C 0
(for (N 0 (> 500 N) (inc N))
(when (additive N)
(printsp N)
(inc 'C) ) )
(prinl)
(prinl "Total count: " C) ) |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #PILOT | PILOT | C :z=2
:c=0
:max=500
*number
C :n=z
U :*digsum
C :n=s
U :*prime
J (p=0):*next
C :n=z
U :*prime
J (p=0):*next
T :#z
C :c=c+1
*next
C :z=z+1
J (z<max):*number
T :There are #c additive primes below #max
E :
*prime
C :p=1
E (n<4):
C :p=0
E (n=2*(n/2)):
C :i=3
:m=n/2
*ptest
E (n=i*(n/i)):
C :i=i+2
J (i<=m):*ptest
C :p=1
E :
*digsum
C :s=0
:i=n
*digit
C :j=i/10
:s=s+(i-j*10)
:i=j
J (i>0):*digit
E : |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Nascom_BASIC | Nascom BASIC |
10 REM Almost prime
20 FOR K=1 TO 5
30 PRINT "k =";STR$(K);":";
40 I=2
50 C=0
60 IF C>=10 THEN 110
70 AN=I:GOSUB 1000
80 IF ISKPRIME=0 THEN 90
82 REM Print I in 4 fields
84 S$=STR$(I)
86 PRINT SPC(4-LEN(S$));S$;
88 C=C+1
90 I=I+1
100 GOTO 60
110 PRINT
120 NEXT K
130 END
995 REM Check if N (AN) is a K prime
1000 F=0
1010 FOR J=2 TO AN
1020 IF INT(AN/J)*J<>AN THEN 1070
1030 IF F=K THEN ISKPRIME=0:RETURN
1040 F=F+1
1050 AN=INT(AN/J)
1060 GOTO 1020
1070 NEXT J
1080 ISKPRIME=(F=K)
1090 RETURN
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Nim | Nim | proc prime(k: int, listLen: int): seq[int] =
result = @[]
var
test: int = 2
curseur: int = 0
while curseur < listLen:
var
i: int = 2
compte = 0
n = test
while i <= n:
if (n mod i)==0:
n = n div i
compte += 1
else:
i += 1
if compte == k:
result.add(test)
curseur += 1
test += 1
for k in 1..5:
echo "k = ",k," : ",prime(k,10) |
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
| #Euphoria | Euphoria | include sort.e
function compare_keys(sequence a, sequence b)
return compare(a[1],b[1])
end function
constant fn = open("unixdict.txt","r")
sequence words, anagrams
object word
words = {}
while 1 do
word = gets(fn)
if atom(word) then
exit
end if
word = word[1..$-1] -- truncate new-line character
words = append(words, {sort(word), word})
end while
close(fn)
integer maxlen
maxlen = 0
words = custom_sort(routine_id("compare_keys"), words)
anagrams = {words[1]}
for i = 2 to length(words) do
if equal(anagrams[$][1],words[i][1]) then
anagrams[$] = append(anagrams[$], words[i][2])
elsif length(anagrams[$]) = 2 then
anagrams[$] = words[i]
else
if length(anagrams[$]) > maxlen then
maxlen = length(anagrams[$])
end if
anagrams = append(anagrams, words[i])
end if
end for
if length(anagrams[$]) = 2 then
anagrams = anagrams[1..$-1]
end if
for i = 1 to length(anagrams) do
if length(anagrams[i]) = maxlen then
for j = 2 to length(anagrams[i]) do
puts(1,anagrams[i][j])
puts(1,' ')
end for
puts(1,"\n")
end if
end for |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: getDifference (in float: b1, in float: b2) is func
result
var float: difference is 0.0;
begin
difference := (b2 - b1) mod 360.0;
if difference > 180.0 then
difference -:= 360.0;
end if;
end func;
const proc: main is func
begin
writeln("Input in -180 to +180 range");
writeln(getDifference(20.0, 45.0));
writeln(getDifference(-45.0, 45.0));
writeln(getDifference(-85.0, 90.0));
writeln(getDifference(-95.0, 90.0));
writeln(getDifference(-45.0, 125.0));
writeln(getDifference(-45.0, 145.0));
writeln(getDifference(-45.0, 125.0));
writeln(getDifference(-45.0, 145.0));
writeln(getDifference(29.4803, -88.6381));
writeln(getDifference(-78.3251, -159.036));
writeln("Input in wider range");
writeln(getDifference(-70099.74233810938, 29840.67437876723));
writeln(getDifference(-165313.6666297357, 33693.9894517456));
writeln(getDifference(1174.8380510598456, -154146.66490124757));
writeln(getDifference(60175.77306795546, 42213.07192354373));
end func; |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
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 | ! cim --memory-pool-size=512 deranged-anagrams.sim;
BEGIN
CLASS TEXTVECTOR;
BEGIN
CLASS TEXTARRAY(N); INTEGER N;
BEGIN TEXT ARRAY DATA(1:N);
END TEXTARRAY;
PROCEDURE EXPAND(N); INTEGER N;
BEGIN
INTEGER I;
REF(TEXTARRAY) TEMP;
TEMP :- NEW TEXTARRAY(N);
FOR I := 1 STEP 1 UNTIL SIZE DO
TEMP.DATA(I) :- ITEMS.DATA(I);
ITEMS :- TEMP;
END EXPAND;
PROCEDURE APPEND(T); TEXT T;
BEGIN
IF SIZE + 1 > CAPACITY THEN
BEGIN
CAPACITY := 2 * CAPACITY;
EXPAND(CAPACITY);
END;
SIZE := SIZE + 1;
ITEMS.DATA(SIZE) :- T;
END APPEND;
TEXT PROCEDURE ELEMENT(I); INTEGER I;
BEGIN
IF I < 1 OR I > SIZE THEN ERROR("ELEMENT: INDEX OUT OF BOUNDS");
ELEMENT :- ITEMS.DATA(I);
END ELEMENT;
INTEGER PROCEDURE FIND_INDEX(STR,INDEX); TEXT STR; INTEGER INDEX;
BEGIN
INTEGER I, FOUND;
FOUND := -1;
FOR I := INDEX STEP 1 UNTIL SIZE DO
IF STR = ELEMENT(I) THEN
BEGIN
FOUND := I;
GOTO L;
END;
L: FIND_INDEX := FOUND;
END FIND_INDEX;
INTEGER CAPACITY;
INTEGER SIZE;
REF(TEXTARRAY) ITEMS;
CAPACITY := 20;
SIZE := 0;
EXPAND(CAPACITY);
END TEXTVECTOR;
BOOLEAN PROCEDURE DERANGE(S1,S2); TEXT S1,S2;
BEGIN
INTEGER I;
BOOLEAN RESULT;
RESULT := TRUE;
I := 1;
WHILE RESULT AND I <= S1.LENGTH DO
BEGIN
CHARACTER C1, C2;
S1.SETPOS(I); C1 := S1.GETCHAR;
S2.SETPOS(I); C2 := S2.GETCHAR;
IF C1 = C2 THEN
RESULT := FALSE
ELSE
I := I+1;
END;
DERANGE := RESULT;
END DERANGE;
PROCEDURE STRSORT(STR); NAME STR; TEXT STR;
BEGIN
INTEGER N, I;
FOR N := STR.LENGTH STEP -1 UNTIL 2 DO
FOR I := 1 STEP 1 UNTIL N-1 DO
BEGIN
CHARACTER CI1,CI2;
STR.SETPOS(I); CI1 := STR.GETCHAR; CI2 := STR.GETCHAR;
IF CI1 > CI2 THEN
BEGIN
STR.SETPOS(I); STR.PUTCHAR(CI2); STR.PUTCHAR(CI1);
END;
END;
END STRSORT;
REF(INFILE) FILE;
INTEGER LEN, FOUNDLEN;
REF(TEXTVECTOR) VECT, SVECT;
INTEGER INDEX, P1, P2;
TEXT STR;
VECT :- NEW TEXTVECTOR;
SVECT :- NEW TEXTVECTOR;
FOUNDLEN := 1;
FILE :- NEW INFILE("unixdict.txt");
FILE.OPEN(BLANKS(132));
WHILE NOT FILE.LASTITEM DO
BEGIN
STR :- FILE.INTEXT(132).STRIP;
LEN := STR.LENGTH;
IF LEN > FOUNDLEN THEN
BEGIN
VECT.APPEND(COPY(STR));
STRSORT(STR);
INDEX := 0;
COMMENT Loop through anagrams by index in vector of sorted strings;
INDEX := SVECT.FIND_INDEX(STR, INDEX + 1);
WHILE INDEX > 0 DO
BEGIN
IF DERANGE(VECT.ELEMENT(VECT.SIZE), VECT.ELEMENT(INDEX)) THEN
BEGIN
P1 := VECT.SIZE;
P2 := INDEX;
FOUNDLEN := LEN;
END IF;
INDEX := SVECT.FIND_INDEX(STR, INDEX + 1);
END WHILE;
SVECT.APPEND(STR);
END IF;
END WHILE;
FILE.CLOSE;
OUTTEXT(VECT.ELEMENT(P1) & " " & VECT.ELEMENT(P2));
OUTIMAGE;
END |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Python | Python | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Picat | Picat | * foreach loop (two variants)
* list comprehension
* while loop.
|
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Rust | Rust |
// using version 0.107.0 of piston_window
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};
const PI: f64 = std::f64::consts::PI;
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
const ANCHOR_X: f64 = WIDTH as f64 / 2. - 12.;
const ANCHOR_Y: f64 = HEIGHT as f64 / 4.;
const ANCHOR_ELLIPSE: [f64; 4] = [ANCHOR_X - 3., ANCHOR_Y - 3., 6., 6.];
const ROPE_ORIGIN: [f64; 2] = [ANCHOR_X, ANCHOR_Y];
const ROPE_LENGTH: f64 = 200.;
const ROPE_THICKNESS: f64 = 1.;
const DELTA: f64 = 0.05;
const STANDARD_GRAVITY_VALUE: f64 = -9.81;
// RGBA Colors
const BLACK: [f32; 4] = [0., 0., 0., 1.];
const RED: [f32; 4] = [1., 0., 0., 1.];
const GOLD: [f32; 4] = [216. / 255., 204. / 255., 36. / 255., 1.0];
fn main() {
let mut window: PistonWindow = WindowSettings::new("Pendulum", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
let mut angle = PI / 2.;
let mut angular_vel = 0.;
while let Some(event) = window.next() {
let (angle_sin, angle_cos) = angle.sin_cos();
let ball_x = ANCHOR_X + angle_sin * ROPE_LENGTH;
let ball_y = ANCHOR_Y + angle_cos * ROPE_LENGTH;
let angle_accel = STANDARD_GRAVITY_VALUE / ROPE_LENGTH * angle_sin;
angular_vel += angle_accel * DELTA;
angle += angular_vel * DELTA;
let rope_end = [ball_x, ball_y];
let ball_ellipse = [ball_x - 7., ball_y - 7., 14., 14.];
window.draw_2d(&event, |context, graphics, _device| {
clear([1.0; 4], graphics);
line_from_to(
BLACK,
ROPE_THICKNESS,
ROPE_ORIGIN,
rope_end,
context.transform,
graphics,
);
ellipse(RED, ANCHOR_ELLIPSE, context.transform, graphics);
ellipse(GOLD, ball_ellipse, context.transform, graphics);
});
}
}
|
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #M2000_Interpreter | M2000 Interpreter |
Module AmbFunction {
Function Amb (failure) {
// get an array of s items, return an array of 1 item
// we do this so we forget the type of element
getitem=lambda (n, c) -> {
dim z(1) :link c to c()
stock c(n) keep 1, z(0) // copy from c(n) to z(0) one item
=z()
}
read a
c1=lambda a, getitem (i, &any, &ret) ->{
any=getitem(i, a)
ret=any
=true
}
m=stack.size
if m=0 then Error "At least two arrays needed"
c=c1
while m>1 {
read b
c1=lambda c2=c, j=0, m=len(a), b, failure, getitem (i, &any, &ret) ->{
any=getitem(i, b)
ret=(,) : ok=false : anyother=(,)
do
if c2(j, &anyother, &ret) then
if not failure(any, anyother) then
ok=true
ret=cons(ret, any)
end if
end if
j++
until ok or j=m
if j=m then j=0
=ok
}
c=c1 : a=b : m--
}
read b
amb1=lambda c2=c, j=0, m=len(a), b, failure, getitem (&ret) ->{
ret=(,) : ok=false: anyother=(,)
k=each(b)
while k
any=getitem(k^, b)
do
if c2(j, &anyother, &ret) then
if not failure(any, anyother) then
ok=true
ret=cons(ret, any)
end if
end if
j++
until ok or j=m
if j=m then j=0
if ok then exit
end while
=ok
}
ret=(,)
if amb1(&ret) then =ret else =(,) ' default return value
}
a=(1, 2, 3)
b=(7, 6, 4, 5)
failure=lambda (a,b)->{
=a#val(0)*b#val(0)<>8
}
Print amb(failure, a, b)#str$()
a=("the", "that", "a")
b=("frog", "elephant", "thing")
c=("walked", "treaded", "grows")
d=("slowly", "quickly")
failure=lambda (a,b)->{
=left$(a#val$(0),1)<>right$(b#val$(0),1)
}
Print amb(failure, a, b, c, d)#str$()
}
AmbFunction
|
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Elena | Elena | function(acc)
= (n => acc.append:n);
accumulator(n)
= function(new Variable(n));
public program()
{
var x := accumulator(1);
x(5);
var y := accumulator(3);
console.write(x(2.3r))
} |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Elixir | Elixir | defmodule AccumulatorFactory do
def new(initial) do
{:ok, pid} = Agent.start_link(fn() -> initial end)
fn (a) ->
Agent.get_and_update(pid, fn(old) -> {a + old, a + old} end)
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.
| #ActionScript | ActionScript | public function ackermann(m:uint, n:uint):uint
{
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return ackermann(m - 1, 1);
}
return 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
| #AWK | AWK |
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
if (num == 1) return 0
sum=1
root=sqrt(num)
for ( i=2; i < root; i++) {
if (num % i == 0 )
{
sum = sum + i + num/i
}
}
if (num % root == 0)
{
sum = sum + root
}
return sum
}
BEGIN{
limit = 20000
abundant = 0
defiecient =0
perfect = 0
for (j=1; j < limit+1; j++)
{
sump = sumprop(j)
if (sump < j) deficient = deficient + 1
if (sump == j) perfect = perfect + 1
if (sump > j) abundant = abundant + 1
}
print "For 1 through " limit
print "Perfect: " perfect
print "Abundant: " abundant
print "Deficient: " deficient
}
|
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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
mode con cols=103
echo Given$a$text$file$of$many$lines,$where$fields$within$a$line$ >file.txt
echo are$delineated$by$a$single$'dollar'$character,$write$a$program! >>file.txt
echo that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$>>file.txt
echo column$are$separated$by$at$least$one$space.>>file.txt
echo Further,$allow$for$each$word$in$a$column$to$be$either$left$>>file.txt
echo justified,$right$justified,$or$center$justified$within$its$column.>>file.txt
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:maxlen %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 1 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 2 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 3 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
exit /B
:maxlen &::sets variables len1 to len13
set "cnt=1"
:loop1
if "%1"=="" exit /b
call:strlen %1 length
if !len%cnt%! lss !length! set len%cnt%=!length!
set /a cnt+=1
shift
goto loop1
:align
setlocal
set cnt=1
set print=
:loop2
if "%2"=="" echo(%print%&endlocal & exit /b
set /a width=len%cnt%,cnt+=1
set arr=%2
if %1 equ 1 call:left %width% arr
if %1 equ 2 call:right %width% arr
if %1 equ 3 call:center %width% arr
set "print=%print%%arr% "
shift /2
goto loop2
:left %num% &string
setlocal
set "arr=!%2! "
set arr=!arr:~0,%1!
endlocal & set %2=%arr%
exit /b
:right %num% &string
setlocal
set "arr= !%2!"
set arr=!arr:~-%1!
endlocal & set %2=%arr%
exit /b
:center %num% &string
setlocal
set /a width=%1-1
set arr=!%2!
:loop3
if "!arr:~%width%,1!"=="" set "arr=%arr% "
if "!arr:~%width%,1!"=="" set "arr= %arr%"
if "!arr:~%width%,1!"=="" goto loop3
endlocal & set %2=%arr%
exit /b
:strlen StrVar &RtnVar
setlocal EnableDelayedExpansion
set "s=#%~1"
set "len=0"
for %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%N,1!" neq "" set /a "len+=%%N" & set "s=!s:~%%N!"
)
endlocal & set %~2=%len%
exit /b |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #JavaScript | JavaScript | function Integrator(sampleIntervalMS) {
var inputF = function () { return 0.0 };
var sum = 0.0;
var t1 = new Date().getTime();
var input1 = inputF(t1 / 1000);
function update() {
var t2 = new Date().getTime();
var input2 = inputF(t2 / 1000);
var dt = (t2 - t1) / 1000;
sum += (input1 + input2) * dt / 2;
t1 = t2;
input1 = input2;
}
var updater = setInterval(update, sampleIntervalMS);
return ({
input: function (newF) { inputF = newF },
output: function () { return sum },
shutdown: function () { clearInterval(updater) },
});
} |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #PARI.2FGP | PARI/GP | aliquot(x) =
{
my (L = List(x), M = Map(Mat([x,1])), k, m = "non-term.", n = x);
for (i = 2, 16, n = vecsum(divisors(n)) - n;
if (n > 2^47, break,
n == 0, m = "terminates"; break,
mapisdefined(M, n, &k),
m = if (k == 1,
if (i == 2, "perfect",
i == 3, "amicable",
i > 3, concat("sociable-",i-1)),
k < i-1, concat("cyclic-",i-k),
"aspiring"); break,
mapput(M, n, i); listput(L, n));
);
printf("%16d: %10s, %s\n", x, m, Vec(L));
} |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Idris | Idris | import Data.Vect
-- Computes Binomial Coefficients
binCoef : Nat -> Nat -> Nat
binCoef _ Z = (S Z)
binCoef (S n) (S k) =
if n == k then (S Z) else ((S n) * (binCoef n k)) `div` (S k)
-- Binomial Expansion Of (x - 1)^p
expansion : (n : Nat) -> Vect (S n) Integer
expansion n = expansion' n 1
where
expansion' : (n : Nat) -> Integer -> Vect (S n) Integer
expansion' (S m) s = s * (toIntegerNat $ binCoef n (n `minus` (S m))) ::
expansion' m (s * -1)
expansion' Z s = [s]
showExpansion : Vect n Integer -> String
showExpansion [] = " "
showExpansion (x::xs) {n = S k} = (if x < 0 then "-" else "") ++
term x k ++ showExpansion' xs
where
term : Integer -> Nat -> String
term x n = if n == 0 then (show (abs x)) else
(if (abs x) == 1 then "" else
(show (abs x))) ++ "x" ++
(if n == 1 then "" else "^" ++ show n)
sign : Integer -> String
sign x = if x >= 0 then " + " else " - "
showExpansion' : Vect m Integer -> String
showExpansion' [] = ""
showExpansion' (y::ys) {m = S k} = sign y ++ term y k ++
showExpansion' ys
natToFin' : (m : Nat) -> Fin (S m)
natToFin' n with (natToFin n (S n))
natToFin' n | Just y = y
isPrime : Nat -> Bool
isPrime Z = False
isPrime (S Z ) = False
isPrime n = foldl (\divs, term => divs && (term `mod` (toIntegerNat n)) == 0)
True (fullExpansion $ expansion n)
-- (x - 1)^p - ((x^p) - 1)
where fullExpansion : Vect (S m) Integer -> Vect (S m) Integer
fullExpansion (x::xs) {m} = updateAt (natToFin' m) (+1) $ (x-1)::xs
printExpansions : Nat -> IO ()
printExpansions n = do
putStrLn "-- p: (x-1)^p for small p"
sequence_ $ map printExpansion [0..n]
where printExpansion : Nat -> IO ()
printExpansion n = do
print n
putStr ": "
putStrLn $ showExpansion $ expansion n
main : IO()
main = do
printExpansions 10
putStrLn "\n-- Primes Up To 100:"
putStrLn $ show $ filter isPrime [0..100] |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #PL.2FI | PL/I | /* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */
additive_primes_100H: procedure options (main);
/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */
/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */
/* PL/I */
%replace dclsieve by 500;
/* PL/M */ /*
DECLARE DCLSIEVE LITERALLY '501';
/* */
/* PL/I DEFINITIONS */
%include 'pg.inc';
/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*
DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';
DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';
DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';
DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';
BDOSF: PROCEDURE( FN, ARG )BYTE;
DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
PRNUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL BDOS( 9, .N$STR( W ) );
END PRNUMBER;
MODF: PROCEDURE( A, B )ADDRESS;
DECLARE ( A, B ) ADDRESS;
RETURN A MOD B;
END MODF;
/* END LANGUAGE DEFINITIONS */
/* TASK */
/* PRIME ELEMENTS ARE 0, 1, ... 500 IN PL/M AND 1, 2, ... 500 IN PL/I */
/* ELEMENT 0 IN PL/M IS IS UNUSED */
DECLARE PRIME( DCLSIEVE ) BIT;
DECLARE ( MAXPRIME, MAXROOT, ACOUNT, I, J, DSUM, V ) FIXED BINARY;
/* SIEVE THE PRIMES UP TO MAX PRIME */
PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE;
MAXPRIME = HBOUND( PRIME , 1
);
MAXROOT = 1; /* FIND THE ROOT OF MAXPRIME TO AVOID 16-BIT OVERFLOW */
DO WHILE( MAXROOT * MAXROOT < MAXPRIME ); MAXROOT = MAXROOT + 1; END;
DO I = 3 TO MAXPRIME BY 2; PRIME( I ) = TRUE; END;
DO I = 4 TO MAXPRIME BY 2; PRIME( I ) = FALSE; END;
DO I = 3 TO MAXROOT BY 2;
IF PRIME( I ) THEN DO;
DO J = I * I TO MAXPRIME BY I; PRIME( J ) = FALSE; END;
END;
END;
/* FIND THE PRIMES THAT ARE ADDITIVE PRIMES */
ACOUNT = 0;
DO I = 1 TO MAXPRIME;
IF PRIME( I ) THEN DO;
V = I;
DSUM = 0;
DO WHILE( V > 0 );
DSUM = DSUM + MODF( V, 10 );
V = V / 10;
END;
IF PRIME( DSUM ) THEN DO;
CALL PRCHAR( ' ' );
IF I < 10 THEN CALL PRCHAR( ' ' );
IF I < 100 THEN CALL PRCHAR( ' ' );
CALL PRNUMBER( I );
ACOUNT = ACOUNT + 1;
IF MODF( ACOUNT, 12 ) = 0 THEN CALL PRNL;
END;
END;
END;
CALL PRNL;
CALL PRSTRING( SADDR( 'FOUND $' ) );
CALL PRNUMBER( ACOUNT );
CALL PRSTRING( SADDR( ' ADDITIVE PRIMES BELOW $' ) );
CALL PRNUMBER( MAXPRIME );
CALL PRNL;
EOF: end additive_primes_100H; |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Objeck | Objeck | class Kth_Prime {
function : native : kPrime(n : Int, k : Int) ~ Bool {
f := 0;
for (p := 2; f < k & p*p <= n; p+=1;) {
while (0 = n % p) {
n /= p; f+=1;
};
};
return f + ((n > 1) ? 1 : 0) = k;
}
function : Main(args : String[]) ~ Nil {
for (k := 1; k <= 5; k+=1;) {
"k = {$k}:"->Print();
c := 0;
for (i := 2; c < 10; i+=1;) {
if (kPrime(i, k)) {
" {$i}"->Print();
c+=1;
};
};
'\n'->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
| #F.23 | F# | let xss = Seq.groupBy (Array.ofSeq >> Array.sort) (System.IO.File.ReadAllLines "unixdict.txt")
Seq.map snd xss |> Seq.filter (Seq.length >> ( = ) (Seq.map (snd >> Seq.length) xss |> Seq.max)) |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Sidef | Sidef | func bearingAngleDiff(b1, b2) {
(var b = ((b2 - b1 + 720) % 360)) > 180 ? (b - 360) : b
}
printf("%25s %25s %25s\n", "B1", "B2", "Difference")
printf("%25s %25s %25s\n", "-"*20, "-"*20, "-"*20)
for b1,b2 in ([
20, 45
-45, 45
-85, 90
-95, 90
-45, 125
-45, 145
29.4803, -88.6381
-78.3251, -159.036
-70099.74233810938, 29840.67437876723
-165313.6666297357, 33693.9894517456
1174.8380510598456, -154146.66490124757
60175.77306795546, 42213.07192354373
].slices(2)
) {
printf("%25s %25s %25s\n", b1, b2, bearingAngleDiff(b1, b2))
} |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
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
# Fetch the words
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
set wordlist [split [http::data $t] \n]
http::cleanup $t
# Group by characters in word
foreach word $wordlist {
dict lappend w [lsort [split $word ""]] [split $word ""]
}
# Deranged test
proc deranged? {l1 l2} {
foreach c1 $l1 c2 $l2 {
if {$c1 eq $c2} {return 0}
}
return 1
}
# Get a deranged pair from an anagram set, if one exists
proc getDeranged {words} {
foreach l1 [lrange $words 0 end-1] {
foreach l2 [lrange $words 1 end] {
if {[deranged? $l1 $l2]} {
return [list $l1 $l2 1]
}
}
}
return {{} {} 0}
}
# Find the max-length deranged anagram
set count 0
set candidates {}
set max 0
dict for {k words} $w {
incr count [expr {[llength $words] > 1}]
if {[llength $k] > $max && [lassign [getDeranged $words] l1 l2]} {
set max [llength $l1]
lappend candidates [join $l1 ""],[join $l2 ""]
}
}
# Print out what we found
puts "[llength $wordlist] words"
puts "[dict size $w] potential anagram-groups"
puts "$count real anagram-groups"
foreach pair $candidates {
puts "considered candidate pairing: $pair"
}
puts "MAXIMAL DERANGED ANAGRAM: LENGTH $max\n\t[lindex $candidates end]" |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #QBasic | QBasic | DECLARE FUNCTION Fibonacci! (num!)
PRINT Fibonacci(20)
PRINT Fibonacci(30)
PRINT Fibonacci(-10)
PRINT Fibonacci(10)
END
FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
Fibonacci = num
END IF
IF num < 2 THEN
Fibonacci = num
ELSE
Fibonacci = Fibonacci(num - 1) + Fibonacci(num - 2)
END IF
END FUNCTION |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #PicoLisp | PicoLisp | (de accud (Var Key)
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
(push Var (cons Key 1)) )
Key )
(de **sum (L)
(let S 1
(for I (cdr L)
(inc 'S (** (car L) I)) )
S ) )
(de factor-sum (N)
(if (=1 N)
0
(let
(R NIL
D 2
L (1 2 2 . (4 2 4 2 4 6 2 6 .))
M (sqrt N)
N1 N
S 1 )
(while (>= M D)
(if (=0 (% N1 D))
(setq M
(sqrt (setq N1 (/ N1 (accud 'R D)))) )
(inc 'D (pop 'L)) ) )
(accud 'R N1)
(for I R
(setq S (* S (**sum I))) )
(- S N) ) ) )
(bench
(for I 20000
(let X (factor-sum I)
(and
(< I X)
(= I (factor-sum X))
(println I X) ) ) ) ) |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Scala | Scala | import java.awt.Color
import java.util.concurrent.{Executors, TimeUnit}
import scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
object Pendulum extends SimpleSwingApplication {
val length = 100
lazy val ui = new Panel {
import scala.math.{cos, Pi, sin}
background = Color.white
preferredSize = (2 * length + 50, length / 2 * 3)
peer.setDoubleBuffered(true)
var angle: Double = Pi / 2
override def paintComponent(g: Graphics2D): Unit = {
super.paintComponent(g)
val (anchorX, anchorY) = (size.width / 2, size.height / 4)
val (ballX, ballY) =
(anchorX + (sin(angle) * length).toInt, anchorY + (cos(angle) * length).toInt)
g.setColor(Color.lightGray)
g.drawLine(anchorX - 2 * length, anchorY, anchorX + 2 * length, anchorY)
g.setColor(Color.black)
g.drawLine(anchorX, anchorY, ballX, ballY)
g.fillOval(anchorX - 3, anchorY - 4, 7, 7)
g.drawOval(ballX - 7, ballY - 7, 14, 14)
g.setColor(Color.yellow)
g.fillOval(ballX - 7, ballY - 7, 14, 14)
}
val animate: Runnable = new Runnable {
var angleVelocity = 0.0
var dt = 0.1
override def run(): Unit = {
angleVelocity += -9.81 / length * Math.sin(angle) * dt
angle += angleVelocity * dt
repaint()
}
}
}
override def top = new MainFrame {
title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala"
contents = ui
centerOnScreen()
Executors.
newSingleThreadScheduledExecutor().
scheduleAtFixedRate(ui.animate, 0, 15, TimeUnit.MILLISECONDS)
}
} |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CheckValid[i_List]:=If[Length[i]<=1,True,And@@(StringTake[#[[1]],-1]==StringTake[#[[2]],1]&/@Partition[i,2,1])]
sets={{"the","that","a"},{"frog","elephant","thing"},{"walked","treaded","grows"},{"slowly","quickly"}};
Select[Tuples[sets],CheckValid] |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Erlang | Erlang |
-module(acc_factory).
-export([loop/1,new/1]).
loop(N)->
receive
{P,I}->
S =N+I, P!S, loop(S)
end.
new(N)->
P=spawn(acc_factory,loop,[N]),
fun(I)->
P!{self(),I},
receive
V-> V
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Ackermann is
function Ackermann (M, N : Natural) return Natural is
begin
if M = 0 then
return N + 1;
elsif N = 0 then
return Ackermann (M - 1, 1);
else
return Ackermann (M - 1, Ackermann (M, N - 1));
end if;
end Ackermann;
begin
for M in 0..3 loop
for N in 0..6 loop
Put (Natural'Image (Ackermann (M, N)));
end loop;
New_Line;
end loop;
end Test_Ackermann; |
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
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
:_main
for /l %%i in (1,1,20000) do (
echo Processing %%i
call:_P %%i
set Pn=!errorlevel!
if !Pn! lss %%i set /a deficient+=1
if !Pn!==%%i set /a perfect+=1
if !Pn! gtr %%i set /a abundant+=1
cls
)
echo Deficient - %deficient% ^| Perfect - %perfect% ^| Abundant - %abundant%
pause>nul
:_P
setlocal enabledelayedexpansion
set sumdivisers=0
set /a upperlimit=%1-1
for /l %%i in (1,1,%upperlimit%) do (
set /a isdiviser=%1 %% %%i
if !isdiviser!==0 set /a sumdivisers+=%%i
)
exit /b %sumdivisers%
|
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
| #Beads | Beads | beads 1 program 'Align columns'
const
text = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'''
var
words : array^2 of str
widths : array of num
calc div_line
var s = '+'
loop across:widths val:w
s = s & str_repeat('-',w) & '+'
log s
calc show_table(
justify
)
loop across:words index:i
var s = '|'
loop across:widths index:j val:w
var
word = words[i,j]
if word == U
word = ''
case justify
| RIGHT
s = s & pad_left(word,w)
| LEFT
s = s & pad_right(word,w)
| CENTER
w = w - str_len(word)
s = s & str_repeat(' ',idiv(w,2)) & word & str_repeat(' ',idiv(w,2)+mod(w,2))
s = s & '|'
log s
div_line
calc main_init
var w
split_lines_words (text, words, delim:'$')
loop across:words index:i
loop across:words[i] index:j
w = str_len(words[i,j])
widths[j] = max(w,widths[j])
loop across:[LEFT CENTER RIGHT] val:v
log "\n{v} justified\n"
div_line
show_table(v) |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Julia | Julia | mutable struct Integrator
func::Function
runningsum::Float64
dt::Float64
running::Bool
function Integrator(f::Function, dt::Float64)
this = new()
this.func = f
this.runningsum = 0.0
this.dt = dt
this.running = false
return this
end
end
function run(integ::Integrator, lastval::Float64 = 0.0)
lasttime = time()
while integ.running
sleep(integ.dt)
newtime = time()
measuredinterval = newtime - lasttime
newval = integ.func(measuredinterval)
integ.runningsum += (lastval + newval) * measuredinterval / 2.0
lasttime = newtime
lastval = newval
end
end
start!(integ::Integrator) = (integ.running = true; @async run(integ))
stop!(integ) = (integ.running = false)
f1(t) = sin(2π * t)
f2(t) = 0.0
it = Integrator(f1, 0.00001)
start!(it)
sleep(2.0)
it.func = f2
sleep(0.5)
v2 = it.runningsum
println("After 2.5 seconds, integrator value was $v2") |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Kotlin | Kotlin | // version 1.2.0
import kotlin.math.*
typealias Function = (Double) -> Double
/**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
class Integrator {
private val start: Long
private @Volatile var running = false
private lateinit var func: Function
private var t0 = 0.0
private var v0 = 0.0
private var sum = 0.0
constructor(func: Function) {
start = System.nanoTime()
setFunc(func)
Thread(this::integrate).start()
}
fun setFunc(func: Function) {
this.func = func
v0 = func(0.0)
t0 = 0.0
}
fun getOutput() = sum
fun stop() {
running = false
}
private fun integrate() {
running = true
while (running) {
try {
Thread.sleep(1)
update()
}
catch(e: InterruptedException) {
return
}
}
}
private fun update() {
val t1 = (System.nanoTime() - start) / 1.0e9
val v1 = func(t1)
val rect = (t1 - t0) * (v0 + v1) / 2.0
sum += rect
t0 = t1
v0 = v1
}
}
fun main(args: Array<String>) {
val integrator = Integrator( { sin(PI * it) } )
Thread.sleep(2000)
integrator.setFunc( { 0.0 } )
Thread.sleep(500)
integrator.stop()
println(integrator.getOutput())
} |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Perl | Perl | use ntheory qw/divisor_sum/;
sub aliquot {
my($n, $maxterms, $maxn) = @_;
$maxterms = 16 unless defined $maxterms;
$maxn = 2**47 unless defined $maxn;
my %terms = ($n => 1);
my @allterms = ($n);
for my $term (2 .. $maxterms) {
$n = divisor_sum($n)-$n;
# push onto allterms here if we want the cyclic term to display
last if $n > $maxn;
return ("terminates",@allterms, 0) if $n == 0;
if (defined $terms{$n}) {
return ("perfect",@allterms) if $term == 2 && $terms{$n} == 1;
return ("amicible",@allterms) if $term == 3 && $terms{$n} == 1;
return ("sociable-".($term-1),@allterms) if $term > 3 && $terms{$n} == 1;
return ("aspiring",@allterms) if $terms{$n} == $term-1;
return ("cyclic-".($term-$terms{$n}),@allterms) if $terms{$n} < $term-1;
}
$terms{$n} = $term;
push @allterms, $n;
}
("non-term",@allterms);
}
for my $n (1..10) {
my($class, @seq) = aliquot($n);
printf "%14d %10s [@seq]\n", $n, $class;
}
print "\n";
for my $n (qw/11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080/) {
my($class, @seq) = aliquot($n);
printf "%14d %10s [@seq]\n", $n, $class;
} |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #J | J | binomialExpansion =: (!~ * _1 ^ 2 | ]) i.&.:<: NB. 1) Create a function that gives the coefficients of (x-1)^p.
testAKS =: 0 *./ .= ] | binomialExpansion NB. 3) Use that function to create another which determines whether p is prime using AKS. |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #PL.2FM | PL/M | /* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */
additive_primes_100H: procedure options (main);
/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */
/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */
/* PL/I */
%replace dclsieve by 500;
/* PL/M */ /*
DECLARE DCLSIEVE LITERALLY '501';
/* */
/* PL/I DEFINITIONS */
%include 'pg.inc';
/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*
DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';
DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';
DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';
DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';
BDOSF: PROCEDURE( FN, ARG )BYTE;
DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
PRNUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL BDOS( 9, .N$STR( W ) );
END PRNUMBER;
MODF: PROCEDURE( A, B )ADDRESS;
DECLARE ( A, B ) ADDRESS;
RETURN A MOD B;
END MODF;
/* END LANGUAGE DEFINITIONS */
/* TASK */
/* PRIME ELEMENTS ARE 0, 1, ... 500 IN PL/M AND 1, 2, ... 500 IN PL/I */
/* ELEMENT 0 IN PL/M IS IS UNUSED */
DECLARE PRIME( DCLSIEVE ) BIT;
DECLARE ( MAXPRIME, MAXROOT, ACOUNT, I, J, DSUM, V ) FIXED BINARY;
/* SIEVE THE PRIMES UP TO MAX PRIME */
PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE;
MAXPRIME = HBOUND( PRIME , 1
);
MAXROOT = 1; /* FIND THE ROOT OF MAXPRIME TO AVOID 16-BIT OVERFLOW */
DO WHILE( MAXROOT * MAXROOT < MAXPRIME ); MAXROOT = MAXROOT + 1; END;
DO I = 3 TO MAXPRIME BY 2; PRIME( I ) = TRUE; END;
DO I = 4 TO MAXPRIME BY 2; PRIME( I ) = FALSE; END;
DO I = 3 TO MAXROOT BY 2;
IF PRIME( I ) THEN DO;
DO J = I * I TO MAXPRIME BY I; PRIME( J ) = FALSE; END;
END;
END;
/* FIND THE PRIMES THAT ARE ADDITIVE PRIMES */
ACOUNT = 0;
DO I = 1 TO MAXPRIME;
IF PRIME( I ) THEN DO;
V = I;
DSUM = 0;
DO WHILE( V > 0 );
DSUM = DSUM + MODF( V, 10 );
V = V / 10;
END;
IF PRIME( DSUM ) THEN DO;
CALL PRCHAR( ' ' );
IF I < 10 THEN CALL PRCHAR( ' ' );
IF I < 100 THEN CALL PRCHAR( ' ' );
CALL PRNUMBER( I );
ACOUNT = ACOUNT + 1;
IF MODF( ACOUNT, 12 ) = 0 THEN CALL PRNL;
END;
END;
END;
CALL PRNL;
CALL PRSTRING( SADDR( 'FOUND $' ) );
CALL PRNUMBER( ACOUNT );
CALL PRSTRING( SADDR( ' ADDITIVE PRIMES BELOW $' ) );
CALL PRNUMBER( MAXPRIME );
CALL PRNL;
EOF: end additive_primes_100H; |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Oforth | Oforth | : kprime?( n k -- b )
| i |
0 2 n for: i [
while( n i /mod swap 0 = ) [ ->n 1+ ] drop
]
k ==
;
: table( k -- [] )
| l |
Array new dup ->l
2 while (l size 10 <>) [ dup k kprime? if dup l add then 1+ ]
drop
; |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #PARI.2FGP | PARI/GP | almost(k)=my(n); for(i=1,10,while(bigomega(n++)!=k,); print1(n", "));
for(k=1,5,almost(k);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
| #Fantom | Fantom | class Main
{
// take given word and return a string rearranging characters in order
static Str toOrderedChars (Str word)
{
Str[] chars := [,]
word.each |Int c| { chars.add (c.toChar) }
return chars.sort.join("")
}
// add given word to anagrams map
static Void addWord (Str:Str[] anagrams, Str word)
{
Str orderedWord := toOrderedChars (word)
if (anagrams.containsKey (orderedWord))
anagrams[orderedWord].add (word)
else
anagrams[orderedWord] = [word]
}
public static Void main ()
{
Str:Str[] anagrams := [:] // map Str -> Str[]
// loop through input file, adding each word to map of anagrams
File (`unixdict.txt`).eachLine |Str word|
{
addWord (anagrams, word)
}
// loop through anagrams, keeping the keys with values of largest size
Str[] largestKeys := [,]
anagrams.keys.each |Str k|
{
if ((largestKeys.size < 1) || (anagrams[k].size == anagrams[largestKeys[0]].size))
largestKeys.add (k)
else if (anagrams[k].size > anagrams[largestKeys[0]].size)
largestKeys = [k]
}
largestKeys.each |Str k|
{
echo ("Key: $k -> " + anagrams[k].join(", "))
}
}
} |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Swift | Swift | func angleDifference(a1: Double, a2: Double) -> Double {
let diff = (a2 - a1).truncatingRemainder(dividingBy: 360)
if diff < -180.0 {
return 360.0 + diff
} else if diff > 180.0 {
return -360.0 + diff
} else {
return diff
}
}
let testCases = [
(20.0, 45.0),
(-45, 45),
(-85, 90),
(-95, 90),
(-45, 125),
(-45, 145),
(29.4803, -88.6381),
(-78.3251, -159.036),
(-70099.74233810938, 29840.67437876723),
(-165313.6666297357, 33693.9894517456),
(1174.8380510598456, -154146.66490124757),
(60175.77306795546, 42213.07192354373)
]
print(testCases.map(angleDifference)) |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Tcl | Tcl |
proc angleDiff {b1 b2} {
set angle [::tcl::mathfunc::fmod [expr ($b2 - $b1)] 360]
if {$angle < -180.0} {
set angle [expr $angle + 360.0]
}
if {$angle >= 180.0} {
set angle [expr $angle - 360.0]
}
return $angle
}
puts "Input in -180 to +180 range"
puts [angleDiff 20.0 45.0]
puts [angleDiff -45.0 45.0]
puts [angleDiff -85.0 90.0]
puts [angleDiff -95.0 90.0]
puts [angleDiff -45.0 125.0]
puts [angleDiff -45.0 145.0]
puts [angleDiff -45.0 125.0]
puts [angleDiff -45.0 145.0]
puts [angleDiff 29.4803 -88.6381]
puts [angleDiff -78.3251 -159.036]
puts "Input in wider range"
puts [angleDiff -70099.74233810938 29840.67437876723]
puts [angleDiff -165313.6666297357 33693.9894517456]
puts [angleDiff 1174.8380510598456 -154146.66490124757]
puts [angleDiff 60175.77306795546 42213.07192354373]
|
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
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://www.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 LOOKUP charString,num,freq,wordalt,wlalt
IF (num==0) THEN
WL=SIZE (charString)
DICT anagramm APPEND/QUIET/COUNT charString,num,freq,word,wl;" "
ELSE
DICT anagramm APPEND/QUIET/COUNT charString,num,freq,word,"";" "
ENDIF
ENDLOOP
DICT anagramm UNLOAD charString,all,freq,anagrams,wl
index =DIGIT_INDEX (wl)
reverseIndex =REVERSE (index)
wl =INDEX_SORT (wl,reverseIndex)
freq =INDEX_SORT (freq,reverseIndex)
anagrams =INDEX_SORT (anagrams,reverseIndex)
charString =INDEX_SORT (charString,reverseIndex)
LOOP fr=freq,a=anagrams,w=wl
IF (fr==1) cycle
asplit=SPLIT (a,": :")
a1=SELECT (asplit,1,arest)
a1split=STRINGS (a1," ? ")
LOOP r=arest
rsplit=STRINGS (r," ? ")
LOOP v1=a1split,v2=rsplit
IF (v1==v2) EXIT,EXIT
ENDLOOP
PRINT "Largest deranged anagram (length: ",w,"):"
PRINT a
STOP
ENDLOOP
ENDLOOP
ENDCOMPILE |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.