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/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #VBA | VBA | Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Vim_Script | Vim Script | " Creating a dictionary with some initial values
let dict = {"one": 1, "two": 2}
" Retrieving a value
let two_a = dict["two"]
let two_b = dict.two
let two_c = get(dict, "two", "default value for missing key")
" Modifying a value
let dict["one"] = 1.0
let dict.two = 2.0
" Adding a new value
let dict["three"] = 3
let dict.four = 4
" Removing a value
let one = remove(dict, "one")
unlet dict["two"]
unlet dict.three |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Visual_FoxPro | Visual FoxPro |
LOCAL loCol As Collection, k, n, o
CLEAR
*!* Example using strings
loCol = NEWOBJECT("Collection")
loCol.Add("Apples", "A")
loCol.Add("Oranges", "O")
loCol.Add("Pears", "P")
n = loCol.Count
? "Items:", n
*!* Loop through the collection
k = 1
FOR EACH o IN loCol FOXOBJECT
? o, loCol.GetKey(k)
k = k + 1
ENDFOR
*!* Get an item by its key
? loCol("O")
?
*!* Example using objects
LOCAL loFruits As Collection
loFruits = NEWOBJECT("Collection")
loFruits.Add(CREATEOBJECT("fruit", "Apples"), "A")
loFruits.Add(CREATEOBJECT("fruit", "Oranges"), "O")
loFruits.Add(CREATEOBJECT("fruit", "Pears"), "P")
*!* Loop through the collection
k = 1
FOR EACH o IN loFruits FOXOBJECT
? o.Name, loFruits.GetKey(k)
k = k + 1
ENDFOR
*!* Get an item name by its key
? loFruits("P").Name
DEFINE CLASS fruit As Custom
PROCEDURE Init(tcName As String)
THIS.Name = tcName
ENDPROC
ENDDEFINE
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Vlang | Vlang | fn main() {
// make empty map
mut my_map := map[string]int{}
//s et value
my_map['foo'] = 3
// getting values
y1 := my_map['foo']
// remove keys
my_map.delete('foo')
// make map with values
my_map = {
'foo': 2
'bar': 42
'baz': -1
}
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wart | Wart | h <- (table 'a 1 'b 2)
h 'a
=> 1 |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wren | Wren | var fruit = {} // creates an empty map
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[2] = "apple" // associates a key of 2 with "apple"
System.print(fruit[1]) // retrieves the value with a key of 1 and prints it out
fruit.remove(1) // removes the entry with a key of 1 from the map
System.print(fruit) // prints the rest of the map
System.print()
var capitals = { // creates a new map with three entries
"France": "Paris",
"Germany": "Berlin",
"Spain": "Madrid"
}
capitals["Russia"] = "Moscow" // adds another entry
System.print(capitals["France"]) // retrieves the "France" entry and prints out its capital
capitals.remove("France") // removes the "France" entry
System.print(capitals) // prints all remaining entries
System.print(capitals.count) // prints the number of remaining entries
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one) |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XLISP | XLISP | (define starlings (make-table)) |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
proc AddEntry(Letter, Greek); \Insert entry into associative array
char Letter, Greek;
[Dict(Entries,0):= Letter;
StrCopy(Greek, @Dict(Entries,1));
Entries:= Entries+1; \(limit checks ignored for simplicity)
];
func Lookup(Greek); \Given Greek name return English letter
char Greek;
int I;
[for I:= 0, Entries-1 do
if StrCmp(Greek, @Dict(I,1)) = 0 then return Dict(I,0);
return ^?;
];
[Entries:= 0;
AddEntry(^A, "alpha");
AddEntry(^D, "delta");
AddEntry(^B, "beta");
AddEntry(^C, "gamma");
ChOut(0, Lookup("beta")); CrLf(0);
ChOut(0, Lookup("omega")); CrLf(0);
] |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #zkl | zkl | zkl: Dictionary("one",1, "two",2, "three",3)
D(two:2,three:3,one:1)
zkl: T("one",1, "two",2, "three",3).toDictionary()
D(two:2,three:3,one:1) |
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.
| #11l | 11l | F fib(n)
F f(Int n) -> Int
I n < 2
R n
R @f(n - 1) + @f(n - 2)
R f(n)
L(i) 0..20
print(fib(i), 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.
| #Ada | Ada | function Fib (X: in Integer) return Integer is
function Actual_Fib (N: in Integer) return Integer is
begin
if N < 2 then
return N;
else
return Actual_Fib (N-1) + Actual_Fib (N-2);
end if;
end Actual_Fib;
begin
if X < 0 then
raise Constraint_Error;
else
return Actual_Fib (X);
end if;
end Fib; |
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.
| #ALGOL_68 | ALGOL 68 | PROC fibonacci = ( INT x )INT:
IF x < 0
THEN
print( ( "negative parameter to fibonacci", newline ) );
stop
ELSE
PROC actual fibonacci = ( INT n )INT:
IF n < 2
THEN
n
ELSE
actual fibonacci( n - 1 ) + actual fibonacci( n - 2 )
FI;
actual fibonacci( x )
FI;
|
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.
| #APL | APL | fib←{ ⍝ Outer function
⍵<0:⎕SIGNAL 11 ⍝ DOMAIN ERROR if argument < 0
{ ⍝ Inner (anonymous) function
⍵<2:⍵
(∇⍵-1)+∇⍵-2 ⍝ ∇ = anonymous recursive call
}⍵ ⍝ Call function in place
} |
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
| #11l | 11l | F is_not_deranged(s1, s2)
L(i) 0 .< s1.len
I s1[i] == s2[i]
R 1B
R 0B
Dict[String, Array[String]] anagram
V count = 0
L(word) File(‘unixdict.txt’).read().split("\n")
V a = sorted(word).join(‘’)
I a !C anagram
anagram[a] = [word]
E
L(ana) anagram[a]
I is_not_deranged(ana, word)
L.break
L.was_no_break
anagram[a].append(word)
count = max(count, word.len)
L(ana) anagram.values()
I ana.len > 1 & ana[0].len == count
print(ana) |
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.
| #AppleScript | AppleScript | on fibonacci(n) -- "Anonymous recursion" task.
-- For the sake of the task, a needlessly anonymous local script object containing a needlessly recursive handler.
-- The script could easily (and ideally should) be assigned to a local variable.
script
property one : 1
property sequence : {}
on f(n)
if (n < 2) then
set end of my sequence to 0
if (n is 1) then set end of my sequence to one
else
f(n - 1)
set end of my sequence to (item -2 of my sequence) + (end of my sequence)
end if
end f
end script
-- Don't insert any additional code here!
-- Sort out whether the input's positive or negative and tell the object generated above to do the recursive business.
tell result
if (n < 0) then
set its one to -1
set n to -n
end if
f(n)
return its sequence
end tell
end fibonacci
fibonacci(15) --> {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}
fibonacci(-15) --> {0, -1, -1, -2, -3, -5, -8, -13, -21, -34, -55, -89, -144, -233, -377, -610} |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program anaderan64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 50000
.equ BUFFERSIZE, 300000
/*********************************/
/* Structures */
/*********************************/
/* this structure has size multiple de 8 */
/* see task anagram for program not use structure */
.struct 0
Word_Ptr_buffer: // p.quader word buffer
.struct Word_Ptr_buffer + 8
Word_Ptr_sorted: // p.quader word sorted letters
.struct Word_Ptr_sorted + 8
Word_length: // word length
.struct Word_length + 8
Word_top: // top
.struct Word_top + 8
Word_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szFileName: .asciz "./unixdict.txt"
//szFileName: .asciz "./listwordT.txt"
szMessErreur: .asciz "FILE ERROR."
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessSpace: .asciz " "
ptBuffex1: .quad sBuffex1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
tbStWords: .skip Word_end * MAXI
qNBword: .skip 8
sBuffer: .skip BUFFERSIZE
sBuffex1: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
mov x4,#0 // loop indice
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszFileName // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN //
svc 0
cmp x0,#0 // error open
ble 99f
mov x9,x0 // FD save Fd
ldr x1,qAdrsBuffer // buffer address
ldr x2,qSizeBuf // buffersize
mov x8, #READ
svc 0
cmp x0,#0 // error read ?
blt 99f
mov x5,x0 // save size read bytes
ldr x4,qAdrsBuffer // buffer address
ldr x0,qAdrsBuffer // start word address
mov x2,#0
mov x1,#0 // word length
1:
cmp x2,x5
bge 2f
ldrb w3,[x4,x2]
cmp w3,#0xD // end word ?
cinc x1,x1,ne // increment word length
cinc x2,x2,ne // increment indice
bne 1b // and loop
strb wzr,[x4,x2] // store final zero
bl anaWord // sort word letters
add x2,x2,#2 // jump OD and 0A
add x0,x4,x2 // new address begin word
mov x1,#0 // init length
b 1b // and loop
2:
strb wzr,[x4,x2] // last word
bl anaWord
mov x0,x9 // file Fd
mov x8, #CLOSE
svc 0
cmp x0,#0 // error close ?
blt 99f
ldr x0,qAdrtbStWords // array structure words address
mov x1,#0 // first indice
ldr x2,qAdrqNBword
ldr x2,[x2] // last indice
bl triRapide // quick sort
ldr x4,qAdrtbStWords // array structure words address
mov x0,x4
mov x9,x2 // size word array
mov x8,#0 // indice first occurence
ldr x3,[x4,#Word_Ptr_sorted] // load first value
mov x2,#1 // loop indice
mov x10,#Word_end // words structure size
mov x12,#0 // max word length
3: // begin loop
madd x7,x2,x10,x4 // compute array index
ldr x5,[x7,#Word_Ptr_sorted] // load next value
mov x0,x3
mov x1,x5
bl comparStrings
cmp x0,#0 // sorted strings equal ?
bne 4f
madd x11,x8,x10,x4
ldr x0,[x11,#Word_Ptr_buffer] // address word 1
ldr x1,[x7,#Word_Ptr_buffer] // address word 2
bl controlLetters
cmp x0,#0 // not ok ?
beq 5f
mov x0,#1 // letters ok
str x0,[x7,#Word_top] // store top in first occurence
str x0,[x11,#Word_top] // store top in current occurence
ldr x0,[x7,#Word_length] // word length
cmp x0,x12 // compare maxi
csel x12,x0,x12,gt // yes length word -> value max
b 5f
4: // no
mov x0,x8
add x8,x8,#1 // init index new first occurence
madd x11,x8,x10,x4 // compute array index
ldr x3,[x11,#Word_Ptr_sorted] // init value new first occurence
mov x2,x0 // reprise au debut de la sequence
5:
add x2,x2,#1 // increment indice
cmp x2,x9 // end word array ?
blt 3b // no -> loop
mov x2,#0 // raz indice
ldr x4,qAdrtbStWords // array structure words address
6: // begin display loop
madd x11,x2,x10,x4 // compute array index
ldr x6,[x11,#Word_top] // load top
cmp x6,#0 // top ok ?
beq 7f
ldr x6,[x11,#Word_length] // load length
cmp x6,x12 // compare maxi
bne 7f
ldr x0,[x11,#Word_Ptr_buffer] // load address first word
bl affichageMess // display first word
add x2,x2,#1 // increment indice
madd x11,x2,x10,x4 // compute array index
ldr x6,[x11,#Word_top] // load top
cmp x6,#0 // top ok ?
beq 7f
ldr x0,qAdrszMessSpace
bl affichageMess
ldr x0,[x11,#Word_Ptr_buffer] // load address other word
bl affichageMess // display second word
ldr x0,qAdrszCarriageReturn
bl affichageMess
7:
add x2,x2,#1 // increment indice
cmp x2,x9 // maxi ?
blt 6b // no -> loop
b 100f
99: // display error
ldr x0,qAdrszMessErreur
bl affichageMess
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
qAdrszFileName: .quad szFileName
qAdrszMessErreur: .quad szMessErreur
qAdrsBuffer: .quad sBuffer
qSizeBuf: .quad BUFFERSIZE
qAdrszMessSpace: .quad szMessSpace
qAdrtbStWords: .quad tbStWords
qAdrszMessStart: .quad szMessStart
/******************************************************************/
/* analizing word */
/******************************************************************/
/* x0 word address */
/* x1 word length */
anaWord:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x5,x0
mov x6,x1
ldr x1,qAdrtbStWords
ldr x2,qAdrqNBword
ldr x3,[x2]
mov x4,#Word_end
madd x1,x3,x4,x1
str x0,[x1,#Word_Ptr_buffer]
mov x0,#0
str x0,[x1,#Word_top]
str x6,[x1,#Word_length]
ldr x4,qAdrptBuffex1
ldr x0,[x4]
add x6,x6,x0
add x6,x6,#1
str x6,[x4]
str x0,[x1,#Word_Ptr_sorted]
add x3,x3,#1
str x3,[x2]
mov x1,x0
mov x0,x5
bl triLetters // sort word letters
mov x2,#0
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqNBword: .quad qNBword
qAdrptBuffex1: .quad ptBuffex1
/******************************************************************/
/* sort word letters */
/******************************************************************/
/* x0 address begin word */
/* x1 address recept array */
triLetters:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x2,#0
1:
ldrb w3,[x0,x2] // load letter
cmp w3,#0 // end word ?
beq 6f
cmp x2,#0 // first letter ?
bne 2f
strb w3,[x1,x2] // yes store in first position
add x2,x2,#1 // increment indice
b 1b // and loop
2:
mov x4,#0
3: // begin loop to search insertion position
ldrb w5,[x1,x4] // load letter
cmp w3,w5 // compare
blt 4f // to low -> insertion
add x4,x4,#1 // increment indice
cmp x4,x2 // compare to letters number in place
blt 3b // search loop
strb w3,[x1,x2] // else store in last position
add x2,x2,#1
b 1b // and loop
4: // move first letters in one position
sub x6,x2,#1 // start indice
5:
ldrb w5,[x1,x6] // load letter
add x7,x6,#1 // store indice - 1
strb w5,[x1,x7] // store letter
sub x6,x6,#1 // decrement indice
cmp x6,x4 // end ?
bge 5b // no loop
strb w3,[x1,x4] // else store letter in free position
add x2,x2,#1
b 1b // and loop
6:
strb wzr,[x1,x2] // final zéro
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* control letters */
/******************************************************************/
/* x0 address word 1*/
/* x1 address word 2 */
controlLetters:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x2,#0
mov x5,x0
1:
ldrb w3,[x5,x2] // load a letter
cmp w3,#0 // end word ?
cset x0,eq
// moveq x0,#1 // yes it is OK
beq 100f
ldrb w4,[x1,x2] // load a letter word 2 same position
cmp w3,w4 // equal ?
cset x0,ne // yes -> not good
//moveq x0,#0 // yes -> not good
beq 100f
add x2,x2,#1
b 1b
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/***************************************************/
/* Appel récursif Tri Rapide quicksort */
/***************************************************/
/* x0 contains the address of table */
/* x1 contains index of first item */
/* x2 contains the number of elements > 0 */
triRapide:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
sub x2,x2,#1 // last item index
cmp x1,x2 // first > last ?
bge 100f // yes -> end
mov x4,x0 // save x0
mov x5,x2 // save x2
bl partition1 // cutting.quado 2 parts
mov x2,x0 // index partition
mov x0,x4 // table address
bl triRapide // sort lower part
mov x0,x4 // table address
add x1,x2,#1 // index begin = index partition + 1
add x2,x5,#1 // number of elements
bl triRapide // sort higter part
100: // end function
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Partition table elements */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains index of first item */
/* x2 contains index of last item */
partition1:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
mov x8,x0 // save address table 2
mov x7,x2
mov x9,#Word_end
madd x3,x7,x9,x8
ldr x6,[x3,#Word_Ptr_sorted] // load string address last index
mov x4,x1 // init with first index
mov x5,x1 // init with first index
1: // begin loop
madd x3,x5,x9,x8
ldr x0,[x3,#Word_Ptr_sorted] // load current string address
mov x1,x6 // first string address
bl comparStrings
cmp x0,#0
bge 2f
mov x0,x8 // current string < first string
mov x1,x4 // swap array
mov x2,x5
bl swapWord
add x4,x4,#1 // and increment index 1
2:
add x5,x5,#1 // increment index 2
cmp x5,x7 // end ?
blt 1b // no -> loop
mov x0,x8 // and swap array
mov x1,x4
mov x2,x7
bl swapWord
mov x0,x4 // return index partition
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Swap table elements */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains index 1 */
/* x2 contains index 2 */
swapWord:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x3,#Word_end
madd x4,x1,x3,x0 // compute array index
madd x5,x2,x3,x0
mov x6,#0
1:
ldr x2,[x4,x6] // load 4 bytes
ldr x3,[x5,x6]
str x2,[x5,x6] // store 4 bytes
str x3,[x4,x6]
add x6,x6,#8 // increment 4 bytes
cmp x6,#Word_end // structure size is multiple to 4
blt 1b
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* x0 et x1 contains the address of strings */
/* return 0 in x0 if equals */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparStrings:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x2,#0 // counter
1:
ldrb w3,[x0,x2] // byte string 1
ldrb w4,[x1,x2] // byte string 2
cmp w3,w4
blt 2f // small
bgt 3f // greather
cmp x3,#0 // 0 end string
beq 4f // end string
add x2,x2,#1 // else add 1 in counter
b 1b // and loop
2:
mov x0,#-1 // small
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #Arturo | Arturo | fib: function [x][
; Using scoped function fibI inside fib
fibI: function [n][
(n<2)? -> n -> add fibI n-2 fibI n-1
]
if x < 0 -> panic "Invalid argument"
return fibI x
]
loop 0..4 'x [
print fib x
] |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Containers.Indefinite_Vectors;
procedure Danagrams is
package StringVector is new Ada.Containers.Indefinite_Vectors
(Positive, String);
procedure StrSort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive,
Element_Type => Character,
Array_Type => String);
function Derange (s1 : String; s2 : String) return Boolean is begin
for i in s1'Range loop
if (s1 (i) = s2 (i)) then return False; end if;
end loop;
return True;
end Derange;
File : File_Type;
len, foundlen : Positive := 1;
Vect, SVect : StringVector.Vector;
index, p1, p2 : StringVector.Extended_Index := 0;
begin
Open (File, In_File, "unixdict.txt");
while not End_Of_File (File) loop
declare str : String := Get_Line (File);
begin
len := str'Length;
if len > foundlen then
Vect.Append (str);
StrSort (str);
index := 0;
loop -- Loop through anagrams by index in vector of sorted strings
index := SVect.Find_Index (str, index + 1);
exit when index = StringVector.No_Index;
if Derange (Vect.Last_Element, Vect.Element (index)) then
p1 := Vect.Last_Index; p2 := index;
foundlen := len;
end if;
end loop;
SVect.Append (str);
end if;
end;
end loop;
Close (File);
Put_Line (Vect.Element (p1) & " " & Vect.Element (p2));
end Danagrams; |
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.
| #AutoHotkey | AutoHotkey | Fib(n) {
nold1 := 1
nold2 := 0
If n < 0
{
MsgBox, Positive argument required!
Return
}
Else If n = 0
Return nold2
Else If n = 1
Return nold1
Fib_Label:
t := nold2+nold1
If n > 2
{
n--
nold2:=nold1
nold1:=t
GoSub Fib_Label
}
Return t
} |
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
| #ALGOL_68 | ALGOL 68 | # find the largest deranged anagrams in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
# returns the length of str #
OP LENGTH = ( STRING str )INT: 1 + ( UPB str - LWB str );
# returns TRUE if a and b are the same length and have no #
# identical characters at any position, #
# FALSE otherwise #
PRIO ALLDIFFER = 9;
OP ALLDIFFER = ( STRING a, b )BOOL:
IF LENGTH a /= LENGTH b
THEN
# the two stringa are not the same size #
FALSE
ELSE
# the strings are the same length, check the characters #
BOOL result := TRUE;
INT b pos := LWB b;
FOR a pos FROM LWB a TO UPB a WHILE result := ( a[ a pos ] /= b[ b pos ] )
DO
b pos +:= 1
OD;
result
FI # ALLDIFFER # ;
# returns text with the characters sorted #
OP SORT = ( STRING text )STRING:
BEGIN
STRING sorted := text;
FOR end pos FROM UPB sorted - 1 BY -1 TO LWB sorted
WHILE
BOOL swapped := FALSE;
FOR pos FROM LWB sorted TO end pos DO
IF sorted[ pos ] > sorted[ pos + 1 ]
THEN
CHAR t := sorted[ pos ];
sorted[ pos ] := sorted[ pos + 1 ];
sorted[ pos + 1 ] := t;
swapped := TRUE
FI
OD;
swapped
DO SKIP OD;
sorted
END # SORTED # ;
# read the list of words and find the longest deranged anagrams #
CHAR separator = "|"; # character that will separate the anagrams #
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
REF AARRAY words := INIT LOC AARRAY;
STRING word;
INT longest derangement := 0;
STRING longest word := "<none>";
STRING longest anagram := "<none>";
WHILE NOT at eof
DO
STRING word;
get( input file, ( word, newline ) );
INT word length = LENGTH word;
IF word length >= longest derangement
THEN
# this word is at least long as the longest derangement #
# found so far - test it #
STRING sorted word = SORT word;
IF ( words // sorted word ) /= ""
THEN
# we already have this sorted word - test for #
# deranged anagrams #
# the word list will have a leading separator #
# and be followed by one or more words separated by #
# the separator #
STRING word list := words // sorted word;
INT list pos := LWB word list + 1;
INT list max = UPB word list;
BOOL is deranged := FALSE;
WHILE list pos < list max
AND NOT is deranged
DO
STRING anagram = word list[ list pos : ( list pos + word length ) - 1 ];
IF is deranged := word ALLDIFFER anagram
THEN
# have a deranged anagram #
longest derangement := word length;
longest word := word;
longest anagram := anagram
FI;
list pos +:= word length + 1
OD
FI;
# add the word to the anagram list #
words // sorted word +:= separator + word
FI
OD;
close( input file );
print( ( "Longest deranged anagrams: "
, longest word
, " and "
, longest anagram
, newline
)
)
FI |
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.
| #AutoIt | AutoIt |
ConsoleWrite(Fibonacci(10) & @CRLF) ; ## USAGE EXAMPLE
ConsoleWrite(Fibonacci(20) & @CRLF) ; ## USAGE EXAMPLE
ConsoleWrite(Fibonacci(30)) ; ## USAGE EXAMPLE
Func Fibonacci($number)
If $number < 0 Then Return "Invalid argument" ; No negative numbers
If $number < 2 Then ; If $number equals 0 or 1
Return $number ; then return that $number
Else ; Else $number equals 2 or more
Return Fibonacci($number - 1) + Fibonacci($number - 2) ; FIBONACCI!
EndIf
EndFunc
|
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
| #AppleScript | AppleScript | use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands!
-- Uses the customisable AppleScript-coded sort shown at <https://macscripter.net/viewtopic.php?pid=194430#p194430>.
-- It's assumed scripters will know how and where to install it as a library.
use sorter : script "Custom Iterative Ternary Merge Sort"
use scripting additions
on longestDerangedAnagrams(listOfWords)
script o
property wordList : listOfWords
property doctoredWords : {}
property hitLength : 0
property output : {}
-- Test for any deranged pairs amongst the words of an anagram group.
on testPairs(a, b)
set anagramGroup to items a thru b of my wordList
set groupCount to b - a + 1
set wordLength to (count beginning of anagramGroup)
repeat with i from 1 to (groupCount - 1)
set w1 to item i of anagramGroup
repeat with j from (i + 1) to groupCount
set w2 to item j of anagramGroup
set areDeranged to true
repeat with c from 1 to wordLength
if (character c of w1 = character c of w2) then
set areDeranged to false
exit repeat
end if
end repeat
-- Append any deranged pairs found to the output list and note their word length.
if (areDeranged) then
set end of my output to {w1, w2}
set hitLength to wordLength
end if
end repeat
end repeat
end testPairs
end script
ignoring case
-- Build another list containing doctored versions of the input words with their characters lexically sorted.
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
repeat with thisWord in o's wordList
set theseChars to thisWord's characters
-- A straight ascending in-place sort here.
tell sorter to sort(theseChars, 1, -1, {}) -- Params: (list, start index, end index, customisation spec.).
set end of o's doctoredWords to theseChars as text
end repeat
set AppleScript's text item delimiters to astid
-- Sort the list of doctored words into descending order by length and ascending order by value within
-- each length, rearranging the original-word list in parallel to maintain the index correspondence.
script descendingByLengthAscendingByValue
on isGreater(a, b)
set lenA to (count a)
set lenB to (count b)
if (lenA = lenB) then return (a > b)
return (lenB > lenA)
end isGreater
end script
tell sorter to sort(o's doctoredWords, 1, -1, {comparer:descendingByLengthAscendingByValue, slave:{o's wordList}})
-- Locate each run of equal doctored words and test the corresponding originals for deranged pairs.
set i to 1
set currentText to beginning of o's doctoredWords
repeat with j from 2 to (count o's doctoredWords)
set thisText to item j of o's doctoredWords
if (thisText is not currentText) then
if (j - i > 1) then tell o to testPairs(i, j - 1)
set currentText to thisText
set i to j
end if
-- Stop on reaching a word shorter than the longest derangement(s) found.
if ((count thisText) < o's hitLength) then exit repeat
end repeat
if (j > i) then tell o to testPairs(i, j)
end ignoring
return o's output
end longestDerangedAnagrams
-- The closing values of AppleScript 'run handler' variables not explicity declared local are
-- saved back to the script file afterwards — and "unixdict.txt" contains 25,104 words!
local wordFile, wordList
-- The words in "unixdict.txt" are arranged one per line in alphabetical order.
-- Some contain punctuation characters, so they're best extracted as 'paragraphs' rather than as 'words'.
set wordFile to ((path to desktop as text) & "unixdict.txt") as «class furl»
set wordList to paragraphs of (read wordFile as «class utf8»)
return longestDerangedAnagrams(wordList) |
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.
| #Axiom | Axiom | #include "axiom"
Z ==> Integer;
fib(x:Z):Z == {
x <= 0 => error "argument outside of range";
f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2);
f(x,1,1);
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program anaderan.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 50000
.equ BUFFERSIZE, 300000
.equ READ, 3 @ system call
.equ OPEN, 5 @ system call
.equ CLOSE, 6 @ system call
.equ O_RDWR, 0x0002 @ open for reading and writing
/*********************************/
/* Structures */
/*********************************/
/* this structure has size multiple de 4 */
.struct 0
Word_Ptr_buffer: @ pointer word buffer
.struct Word_Ptr_buffer + 4
Word_Ptr_sorted: @ pointer word sorted letters
.struct Word_Ptr_sorted + 4
Word_length: @ word length
.struct Word_length + 4
Word_top: @ top
.struct Word_top + 4
Word_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szFileName: .asciz "./unixdict.txt"
//szFileName: .asciz "./listwordT.txt"
szMessErreur: .asciz "FILE ERROR."
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessSpace: .asciz " "
ptBuffer1: .int sBuffer1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
tbStWords: .skip Word_end * MAXI
iNBword: .skip 4
sBuffer: .skip BUFFERSIZE
sBuffer1: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
mov r4,#0 @ loop indice
ldr r0,iAdrszFileName @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @
svc 0
cmp r0,#0 @ error open
ble 99f
mov r8,r0 @ FD save Fd
ldr r1,iAdrsBuffer @ buffer address
ldr r2,iSizeBuf @ buffersize
mov r7, #READ
svc 0
cmp r0,#0 @ error read ?
blt 99f
mov r5,r0 @ save size read bytes
ldr r4,iAdrsBuffer @ buffer address
ldr r0,iAdrsBuffer @ start word address
mov r2,#0
mov r1,#0 @ word length
1:
cmp r2,r5
bge 2f
ldrb r3,[r4,r2]
cmp r3,#0xD @ end word ?
addne r1,r1,#1 @ increment word length
addne r2,r2,#1 @ increment indice
bne 1b @ and loop
mov r3,#0
strb r3,[r4,r2] @ store final zero
bl anaWord @ sort word letters
add r2,r2,#2 @ jump OD and 0A
add r0,r4,r2 @ new address begin word
mov r1,#0 @ init length
b 1b @ and loop
2:
mov r3,#0 @ last word
strb r3,[r4,r2]
bl anaWord
mov r0,r8 @ file Fd
mov r7, #CLOSE
svc 0
cmp r0,#0 @ error close ?
blt 99f
ldr r0,iAdrtbStWords @ array structure words address
mov r1,#0 @ first indice
ldr r2,iAdriNBword
ldr r2,[r2] @ last indice
bl triRapide @ quick sort
ldr r4,iAdrtbStWords @ array structure words address
mov r0,r4
mov r9,r2 @ size word array
mov r8,#0 @ indice first occurence
ldr r3,[r4,#Word_Ptr_sorted] @ load first value
mov r2,#1 @ loop indice
mov r10,#Word_end @ words structure size
mov r12,#0 @ max word length
3: @ begin loop
mla r7,r2,r10,r4 @ compute array index
ldr r5,[r7,#Word_Ptr_sorted] @ load next value
mov r0,r3
mov r1,r5
bl comparStrings
cmp r0,#0 @ sorted strings equal ?
bne 4f
mla r11,r8,r10,r4
ldr r0,[r11,#Word_Ptr_buffer] @ address word 1
ldr r1,[r7,#Word_Ptr_buffer] @ address word 2
bl controlLetters
cmp r0,#0 @ not ok ?
beq 5f
mov r0,#1 @ letters ok
str r0,[r7,#Word_top] @ store top in first occurence
str r0,[r11,#Word_top] @ store top in current occurence
ldr r0,[r7,#Word_length] @ word length
cmp r0,r12 @ compare maxi
movgt r12,r0 @ yes length word -> value max
b 5f
4: @ no
mov r0,r8
add r8,r8,#1 @ init index new first occurence
mla r11,r8,r10,r4 @ compute array index
ldr r3,[r11,#Word_Ptr_sorted] @ init value new first occurence
mov r2,r0 @ reprise au debut de la sequence
5:
add r2,r2,#1 @ increment indice
cmp r2,r9 @ end word array ?
blt 3b @ no -> loop
mov r2,#0 @ raz indice
ldr r4,iAdrtbStWords @ array structure words address
6: @ begin display loop
mla r11,r2,r10,r4 @ compute array index
ldr r6,[r11,#Word_top] @ load top
cmp r6,#0 @ top ok ?
beq 7f
ldr r6,[r11,#Word_length] @ load length
cmp r6,r12 @ compare maxi
bne 7f
ldr r0,[r11,#Word_Ptr_buffer] @ load address first word
bl affichageMess @ display first word
add r2,r2,#1 @ increment indice
mla r11,r2,r10,r4 @ compute array index
ldr r6,[r11,#Word_top] @ load top
cmp r6,#0 @ top ok ?
beq 7f
ldr r0,iAdrszMessSpace
bl affichageMess
ldr r0,[r11,#Word_Ptr_buffer] @ load address other word
bl affichageMess @ display second word
ldr r0,iAdrszCarriageReturn
bl affichageMess
7:
add r2,r2,#1 @ increment indice
cmp r2,r9 @ maxi ?
blt 6b @ no -> loop
b 100f
99: @ display error
ldr r1,iAdrszMessErreur
bl displayError
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszFileName: .int szFileName
iAdrszMessErreur: .int szMessErreur
iAdrsBuffer: .int sBuffer
iSizeBuf: .int BUFFERSIZE
iAdrszMessSpace: .int szMessSpace
iAdrtbStWords: .int tbStWords
iAdrszMessStart: .int szMessStart
/******************************************************************/
/* analizing word */
/******************************************************************/
/* r0 word address */
/* r1 word length */
anaWord:
push {r1-r6,lr}
mov r5,r0
mov r6,r1
//ldr r1,iAdrptTabBuffer
ldr r1,iAdrtbStWords
ldr r2,iAdriNBword
ldr r3,[r2]
mov r4,#Word_end
mla r1,r3,r4,r1
str r0,[r1,#Word_Ptr_buffer]
mov r0,#0
str r0,[r1,#Word_top]
str r6,[r1,#Word_length]
ldr r4,iAdrptBuffer1
ldr r0,[r4]
add r6,r6,r0
add r6,r6,#1
str r6,[r4]
str r0,[r1,#Word_Ptr_sorted]
add r3,r3,#1
str r3,[r2]
mov r1,r0
mov r0,r5
bl triLetters @ sort word letters
mov r2,#0
100:
pop {r1-r6,pc}
iAdriNBword: .int iNBword
iAdrptBuffer1: .int ptBuffer1
/******************************************************************/
/* sort word letters */
/******************************************************************/
/* r0 address begin word */
/* r1 address recept array */
triLetters:
push {r1-r7,lr}
mov r2,#0
1:
ldrb r3,[r0,r2] @ load letter
cmp r3,#0 @ end word ?
beq 6f
cmp r2,#0 @ first letter ?
bne 2f
strb r3,[r1,r2] @ yes store in first position
add r2,r2,#1 @ increment indice
b 1b @ and loop
2:
mov r4,#0
3: @ begin loop to search insertion position
ldrb r5,[r1,r4] @ load letter
cmp r3,r5 @ compare
blt 4f @ to low -> insertion
add r4,r4,#1 @ increment indice
cmp r4,r2 @ compare to letters number in place
blt 3b @ search loop
strb r3,[r1,r2] @ else store in last position
add r2,r2,#1
b 1b @ and loop
4: @ move first letters in one position
sub r6,r2,#1 @ start indice
5:
ldrb r5,[r1,r6] @ load letter
add r7,r6,#1 @ store indice - 1
strb r5,[r1,r7] @ store letter
sub r6,r6,#1 @ decrement indice
cmp r6,r4 @ end ?
bge 5b @ no loop
strb r3,[r1,r4] @ else store letter in free position
add r2,r2,#1
b 1b @ and loop
6:
mov r3,#0 @ final zéro
strb r3,[r1,r2]
100:
pop {r1-r7,pc}
/******************************************************************/
/* control letters */
/******************************************************************/
/* r0 address word 1*/
/* r1 address word 2 */
controlLetters:
push {r1-r4,lr}
mov r2,#0
1:
ldrb r3,[r0,r2] @ load a letter
cmp r3,#0 @ end word ?
moveq r0,#1 @ yes it is OK
beq 100f
ldrb r4,[r1,r2] @ load a letter word 2 same position
cmp r3,r4 @ equal ?
moveq r0,#0 @ yes -> not good
beq 100f
add r2,r2,#1
b 1b
100:
pop {r1-r4,pc}
/***************************************************/
/* Appel récursif Tri Rapide quicksort */
/***************************************************/
/* r0 contains the address of table */
/* r1 contains index of first item */
/* r2 contains the number of elements > 0 */
triRapide:
push {r2-r5,lr} @ save registers
sub r2,#1 @ last item index
cmp r1,r2 @ first > last ?
bge 100f @ yes -> end
mov r4,r0 @ save r0
mov r5,r2 @ save r2
bl partition1 @ cutting into 2 parts
mov r2,r0 @ index partition
mov r0,r4 @ table address
bl triRapide @ sort lower part
mov r0,r4 @ table address
add r1,r2,#1 @ index begin = index partition + 1
add r2,r5,#1 @ number of elements
bl triRapide @ sort higter part
100: @ end function
pop {r2-r5,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* Partition table elements */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains index of first item */
/* r2 contains index of last item */
partition1:
push {r1-r9,lr} @ save registers
mov r8,r0 @ save address table 2
mov r7,r2
mov r9,#Word_end
mla r3,r7,r9,r8
ldr r6,[r3,#Word_Ptr_sorted] @ load string address last index
mov r4,r1 @ init with first index
mov r5,r1 @ init with first index
1: @ begin loop
mla r3,r5,r9,r8
ldr r0,[r3,#Word_Ptr_sorted] @ load current string address
mov r1,r6 @ first string address
bl comparStrings
cmp r0,#0
bge 2f
mov r0,r8 @ current string < first string
mov r1,r4 @ swap array
mov r2,r5
bl swapWord
add r4,r4,#1 @ and increment index 1
2:
add r5,r5,#1 @ increment index 2
cmp r5,r7 @ end ?
blt 1b @ no -> loop
mov r0,r8 @ and swap array
mov r1,r4
mov r2,r7
bl swapWord
mov r0,r4 @ return index partition
100:
pop {r1-r9,lr}
bx lr
/******************************************************************/
/* Swap table elements */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains index 1 */
/* r2 contains index 2 */
swapWord:
push {r1-r6,lr} @ save registers
mov r3,#Word_end
mla r4,r1,r3,r0 @ compute array index
mla r5,r2,r3,r0
mov r6,#0
1:
ldr r2,[r4,r6] @ load 4 bytes
ldr r3,[r5,r6]
str r2,[r5,r6] @ store 4 bytes
str r3,[r4,r6]
add r6,r6,#4 @ increment 4 bytes
cmp r6,#Word_end @ structure size is multiple to 4
blt 1b
100:
pop {r1-r6,pc}
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* r0 et r1 contains the address of strings */
/* return 0 in r0 if equals */
/* return -1 if string r0 < string r1 */
/* return 1 if string r0 > string r1 */
comparStrings:
push {r1-r4} @ save des registres
mov r2,#0 @ counter
1:
ldrb r3,[r0,r2] @ byte string 1
ldrb r4,[r1,r2] @ byte string 2
cmp r3,r4
movlt r0,#-1 @ small
movgt r0,#1 @ greather
bne 100f @ not equals
cmp r3,#0 @ 0 end string
moveq r0,#0 @ equals
beq 100f @ end string
add r2,r2,#1 @ else add 1 in counter
b 1b @ and loop
100:
pop {r1-r4}
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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.
| #BaCon | BaCon |
DEF FN fib(x) = FIB(x)
'============================
FUNCTION FIB(int n) TYPE int
'============================
IF n < 2 THEN
PRINT n
ELSE
n1 = 0
n2 = 1
FOR i = 1 TO n
sum = n1 + n2
n1 = n2
n2 = sum
NEXT
PRINT n1
END IF
END FUNCTION
'--- less than 2
FIB(0)
FIB(1)
'--- greater than or equal to 2
FIB(2)
FIB(3)
FIB(4)
FIB(5)
FIB(6)
FIB(7)
FIB(8)
FIB(9)
'--- using an alias
'fib(9)
|
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.
| #11l | 11l | F sum_proper_divisors(n)
R I n < 2 {0} E sum((1 .. n I/ 2).filter(it -> (@n % it) == 0))
L(n) 1..20000
V m = sum_proper_divisors(n)
I m > n & sum_proper_divisors(m) == n
print(n"\t"m) |
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
| #Arturo | Arturo | isDeranged?: function [p][
[a,b]: p
loop 0..dec size a 'i [
if a\[i] = b\[i] [return false]
]
return true
]
wordset: map read.lines relative "unixdict.txt" => strip
anagrams: #[]
loop wordset 'word [
anagram: sort to [:char] word
unless key? anagrams anagram ->
anagrams\[anagram]: new []
anagrams\[anagram]: anagrams\[anagram] ++ word
]
deranged: select values anagrams 'anagram [ 2 = size anagram]
maxDeranged: ["" ""]
loop deranged 'd [
if (size first d) > size first maxDeranged [
pair: @[first d, last d]
if isDeranged? pair [
maxDeranged: pair
]
]
]
print maxDeranged |
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.
| #BASIC256 | BASIC256 | print Fibonacci(20)
print Fibonacci(30)
print Fibonacci(-10)
print Fibonacci(10)
end
function Fibonacci(num)
if num < 0 then
print "Invalid argument: ";
return num
end if
if num < 2 then
return num
else
return 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.
| #8080_Assembly | 8080 Assembly | org 100h
;;; Calculate proper divisors of 2..20000
lxi h,pdiv + 4 ; 2 bytes per entry
lxi d,19999 ; [2 .. 20000] means 19999 entries
lxi b,1 ; Initialize each entry to 1
init: mov m,c
inx h
mov m,b
inx h
dcx d
mov a,d
ora e
jnz init
lxi b,1 ; BC = outer loop variable
iouter: inx b
lxi h,-10001 ; Are we there yet?
dad b
jc idone ; If so, we've calculated all of them
mov h,b
mov l,c
dad h
xchg ; DE = inner loop variable
iinner: push d ; save DE
xchg
dad h ; calculate *pdiv[DE]
lxi d,pdiv
dad d
mov e,m ; DE = pdiv[DE]
inx h
mov d,m
xchg ; pdiv[DE] += BC
dad b
xchg ; store it back
mov m,d
dcx h
mov m,e
pop h ; restore DE (into HL)
dad b ; add BC
lxi d,-20001 ; are we there yet?
dad d
jc iouter ; then continue with outer loop
lxi d,20001 ; otherwise continue with inner loop
dad d
xchg
jmp iinner
idone: lxi b,1 ; BC = outer loop variable
touter: inx b
lxi h,-20001 ; Are we there yet?
dad b
rc ; If so, stop
mov d,b ; DE = outer loop variable
mov e,c
tinner: inx d
lxi h,-20001 ; Are we there yet?
dad d
jc touter ; If so continue with outer loop
push d ; Store the variables
push b
mov h,b ; find *pdiv[BC]
mov l,c
dad b
lxi b,pdiv
dad b
mov a,m ; Compare low byte (to E)
cmp e
jnz tnext1 ; Not equal = not amicable
inx h
mov a,m
cmp d ; Compare high byte (to B)
jnz tnext1 ; Not equal = not amicable
pop b ; Restore BC
xchg ; find *pdiv[DE]
dad h
lxi d,pdiv
dad d
mov a,m ; Compare low byte (to C)
cmp c
jnz tnext2 ; Not equal = not amicable
inx h
mov a,m ; Compare high byte (to B)
cmp b
jnz tnext2 ; Not equal = not amicable
pop d ; Restore DE
push d ; Save them both on the stack again
push b
push d
mov h,b ; Print the first number
mov l,c
call prhl
pop h ; And the second number
call prhl
lxi d,nl ; And a newline
mvi c,9
call 5
tnext1: pop b ; Restore B
tnext2: pop d ; Restore D
jmp tinner ; Continue
;;; Print the number in HL
prhl: lxi d,nbuf ; Store buffer pointer on stack
push d
lxi b,-10 ; Divisor
pdgt: lxi d,-1 ; Quotient
pdivlp: inx d
dad b
jc pdivlp
mvi a,'0'+10 ; Make ASCII digit
add l
pop h ; Store in output buffer
dcx h
mov m,a
push h
xchg ; Keep going with rest of number
mov a,h ; if not zero
ora l
jnz pdgt
mvi c,9 ; CP/M call to print string
pop d ; Get buffer pointer
jmp 5
db '*****'
nbuf: db ' $'
nl: db 13,10,'$'
pdiv: equ $ ; base |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Action.21 | Action! | PROC DrawWindow(BYTE x,y,len)
BYTE i
Position(x,y)
Put(17)
FOR i=1 TO len DO Put(18) OD
Put(5)
Position(x,y+1)
Put(124)
Position(x+len+1,y+1)
Put(124)
Position(x,y+2)
Put(26)
FOR i=1 TO len DO Put(18) OD
Put(3)
RETURN
PROC RotateLeft(CHAR ARRAY a)
BYTE i,tmp
IF a(0)<1 THEN RETURN FI
i=1 tmp=a(i)
WHILE i<a(0)
DO
a(i)=a(i+1)
i==+1
OD
a(a(0))=tmp
RETURN
PROC RotateRight(CHAR ARRAY a)
BYTE i,tmp
IF a(0)<1 THEN RETURN FI
i=a(0) tmp=a(i)
WHILE i>1
DO
a(i)=a(i-1)
i==-1
OD
a(1)=tmp
RETURN
PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
BYTE
CH=$02FC, ;Internal hardware value for last key pressed
CRSINH=$02F0 ;Controls visibility of cursor
BYTE k,dir=[0]
CHAR ARRAY text="Hello World! "
Graphics(0)
CRSINH=1 ;hide cursor
Position(4,1)
PrintE("Press Space to reverse direction")
Position(11,2)
Print("Press Esc to exit")
DrawWindow(12,4,text(0))
DO
Position(13,5)
Print(text)
k=CH CH=$FF
IF k=33 THEN dir==!$FF FI
IF dir THEN
RotateLeft(text)
ELSE
RotateRight(text)
FI
Wait(6)
UNTIL k=28
OD
CRSINH=0 ;show cursor
RETURN |
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
| #AutoHotkey | AutoHotkey | Time := A_TickCount
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetBatchLines -1
Loop, Read, unixdict.txt
StrOut .= StrLen(A_LoopReadLine) - 2 . "," . A_LoopReadLine . "`n"
Sort StrOut, N R
Loop, Parse, StrOut, `n, `r
{
StringSplit, No_Let, A_Loopfield, `,
if ( old1 = no_let1 )
string .= old2 "`n"
if ( old1 != no_let1 )
{
string := trim(string old2)
if ( old2 != "" )
Loop, Parse, string, `n, `r ; Specifying `n prior to `r allows both Windows and Unix files to be Parsed.
line_number := A_Index
if ( line_number > 1 )
{
Loop, Parse, string, `n, `r
{
StringSplit, newstr, A_Loopfield, `, ; break the string based on Comma
Loop, Parse, newstr2
k .= A_LoopField " "
Sort k, D%A_Space%
k := RegExReplace( k, "\s", "" )
file .= "`r`n" k . "," . newstr1 . "," . newstr2
k =
}
Sort File
Loop, Parse, File, `n, `r
{
if ( A_Loopfield != "" )
{
StringSplit, T_C, A_Loopfield, `,
if ( old = T_C1 )
{
Loop, 1
{
Loop % T_C2
if (SubStr(T_C3, A_Index, 1) = SubStr(old3, A_Index, 1))
break 2
Time := (A_tickcount - Time)/1000
MsgBox % T_C3 " " old3 " in " Time . " seconds."
ExitApp
}
}
old := T_C1, old3 := T_C3
}
}
file =
}
string =
}
old1 := no_let1, old2 := A_Loopfield
} |
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.
| #BBC_BASIC | BBC BASIC | PRINT FNfib(10)
END
DEF FNfib(n%) IF n%<0 THEN ERROR 100, "Must not be negative"
LOCAL P% : P% = !384 + LEN$!384 + 4 : REM Function pointer
(n%) IF n%<2 THEN = n% ELSE = FN(^P%)(n%-1) + FN(^P%)(n%-2) |
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.
| #8086_Assembly | 8086 Assembly | LIMIT: equ 20000 ; Maximum value
cpu 8086
org 100h
section .text
mov ax,final ; Set DS and ES to point just beyond the
mov cl,4 ; program. We're just going to assume MS-DOS
shr ax,cl ; gave us enough memory. (Generally the case,
inc ax ; a .COM gets a 64K segment and we need ~40K.)
mov cx,cs
add ax,cx
mov ds,ax
mov es,ax
calc: mov ax,1 ; Calculate proper divisors for 2..20000
mov di,4 ; Initially, set each entry to 1.
mov cx,LIMIT-1 ; 2 to 20000 inclusive = 19999 entries
rep stosw
mov ax,2 ; AX = outer loop counter
mov cl,2
mov dx,LIMIT*2 ; Keep inner loop limit ready in DX
mov bp,LIMIT/2 ; And outer loop limit in BP
.outer: mov bx,ax ; BX = inner loop counter (multiplied by two)
shl bx,cl ; Each entry is 2 bytes wide
.inner: add [bx],ax ; divsum[BX/2] += AX
add bx,ax ; Advance to next entry
add bx,ax ; Twice, because each entry is 2 bytes wide
cmp bx,dx ; Are we there yet?
jbe .inner ; If not, keep going
inc ax
cmp ax,bp ; Is the outer loop done yet?
jbe .outer ; If not, keep going
show: mov dx,LIMIT ; Keep limit ready in DX
mov ax,2 ; AX = outer loop counter
mov si,4 ; SI = address for outer loop
.outer: mov cx,ax ; CX = inner loop counter
inc cx
mov di,cx ; DI = address for inner loop
shl di,1
mov bx,[si] ; Preload divsum[AX]
.inner: cmp cx,bx ; CX == divsum[AX]?
jne .next ; If not, the pair is not amicable
cmp ax,[di] ; AX == divsum[CX]?
jne .next ; If not, the pair is not amicable
push ax ; Keep the registers
push bx
push cx
push dx
push cx ; And CX twice because we need to print it
call prax ; Print the first number
pop ax
call prax ; And the second number
mov dx,nl ; And a newline
call pstr
pop dx ; Restore the registers
pop cx
pop bx
pop ax
.next: inc di ; Increment inner loop variable and address
inc di ; Address twice because each entry has 2 bytes
inc cx
cmp cx,dx ; Are we done yet?
jbe .inner ; If not, keep going
inc si ; Increment outer loop variable and address
inc si ; Address twice because each entry has 2 bytes
inc ax
cmp ax,dx ; Are we done yet?
jbe .outer ; If not, keep going.
ret
;;; Print the number in AX. Destroys AX, BX, CX, DX.
prax: mov cx,10 ; Divisor
mov bx,nbuf ; Buffer pointer
.digit: xor dx,dx
div cx ; Divide by 10 and extract digit
add dl,'0' ; Add ASCII 0 to digit
dec bx
mov [cs:bx],dl ; Store in string
test ax,ax ; Any more?
jnz .digit ; If so, keep going
mov dx,bx ; If not, print the result
;;; Print string from CS.
pstr: push ds ; Save DS
mov ax,cs ; Set DS to CS
mov ds,ax
mov ah,9 ; Print string using MS-DOS
int 21h
pop ds ; Restore DS
ret
db '*****'
nbuf: db ' $'
nl: db 13,10,'$'
final: equ $ |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #ActionScript | ActionScript | //create the text box
var textBox:TextField = new TextField();
addChild(textBox);
var text = "Hello, World! ";
var goingRight = true;
//modify the string and update it in the text box
function animate(e:Event)
{
if(goingRight)
text = text.slice(text.length-1,text.length) + text.slice(0, text.length - 1);
else
text = text.slice(1) + text.slice(0,1);
textBox.text = text;
}
//event handler to perform the animation
textBox.addEventListener(Event.ENTER_FRAME, animate);
//event handler to register clicks
textBox.addEventListener(MouseEvent.MOUSE_DOWN, function(){goingRight = !goingRight;});
|
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
| #11l | 11l | F get_difference(b1, b2)
R wrap(b2 - b1, -180.0, 180.0)
print(get_difference( 20.0, 45.0))
print(get_difference(-45.0, 45.0))
print(get_difference(-85.0, 90.0))
print(get_difference(-95.0, 90.0))
print(get_difference(-45.0, 125.0))
print(get_difference(-45.0, 145.0))
print(get_difference(-45.0, 125.0))
print(get_difference(-45.0, 145.0))
print(get_difference(29.4803, -88.6381))
print(get_difference(-78.3251, -159.036))
print(‘’)
print(get_difference(-70099.74233810938, 29840.67437876723))
print(get_difference(-165313.6666297357, 33693.9894517456))
print(get_difference(1174.8380510598456, -154146.66490124757))
print(get_difference(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
| #AWK | AWK | #!/bin/gawk -f
BEGIN{
FS=""
wordcount = 0
maxlength = 0
}
# hash generates the sorted sequence of characters in a word,
# so that the hashes for a pair of anagrams will be the same.
# Example: hash meat = aemt and hash team = aemt
function hash(myword, i,letters,myhash){
split(myword,letters,"")
asort(letters)
for (i=1;i<=length(myword);i++) myhash=myhash letters[i]
return myhash
}
# deranged checks two anagrems for derangement
function deranged(worda, wordb, a,b,i,n,len){
n=0
len=split(worda,a,"")
split(wordb,b,"")
for (i=len; i>=1; i--){
if (a[i] == b[i]) n = n+1
}
return n==0
}
# field separator null makes gawk split input record character by character.
# the split function works the same way
{
wordcount = wordcount + 1
fullword[wordcount]=$0
bylength[length($0)]=bylength[length($0)] wordcount "|"
if (length($0) > maxlength) maxlength = length($0)
}
END{
for (len=maxlength; len>1; len--){
numwords=split(bylength[len],words,"|")
split("",hashed)
split("",anagrams)
for (i=1;i<=numwords;i++){
# make lists of anagrams in hashed
myword = fullword[words[i]]
myhash = hash(myword)
hashed[myhash] = hashed[myhash] myword " "
}
# check anagrams for derangement
for (myhash in hashed){
n = split(hashed[myhash],anagrams," ")
for (i=1; i< n; i++)
for (j=i+1; j<=n; j++){
if(deranged(anagrams[i],anagrams[j])) found = found anagrams[i] " " anagrams[j] " "
}
}
if (length(found) > 0 ) print "deranged: " found
if (length(found) > 0) exit
}
} |
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.
| #Bracmat | Bracmat | ( (
=
. !arg:#:~<0
& ( (=.!arg$!arg)
$ (
=
.
' (
. !arg:<2
| (($arg)$($arg))$(!arg+-2)
+ (($arg)$($arg))$(!arg+-1)
)
)
)
$ !arg
)
$ 30
)
|
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program amicable64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NMAXI, 20000
.equ TABMAXI, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ : @\n"
szCarriageReturn: .asciz "\n"
szMessErr1: .asciz "Array too small !!"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tResult: .skip 8 * TABMAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x3,qNMaxi // load limit
mov x4,#2 // number begin
1:
mov x0,x4 // number
bl decFactor // compute sum factors
cmp x0,x4 // equal ?
beq 2f
mov x2,x0 // factor sum 1
bl decFactor
cmp x0,x4 // equal number ?
bne 2f
mov x0,x4 // yes -> search in array
mov x1,x2 // and store sum
bl searchRes
cmp x0,#0 // find ?
bne 2f // yes
mov x0,x4 // no -> display number ans sum
mov x1,x2
bl displayResult
2:
add x4,x4,#1 // increment number
cmp x4,x3 // end ?
ble 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
qNMaxi: .quad NMAXI
/***************************************************/
/* display message number */
/***************************************************/
/* x0 contains number 1 */
/* x1 contains number 2 */
displayResult:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x1
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x3,x0
mov x0,x2
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
mov x0,x3
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
/***************************************************/
/* compute factors sum */
/***************************************************/
/* x0 contains the number */
decFactor:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,#1 // init sum
mov x1,#2 // start factor -> divisor
1:
udiv x2,x0,x1
msub x3,x2,x1,x0 // remainder
cmp x1,x2 // divisor > quotient ?
bgt 3f
cmp x3,#0 // remainder = 0 ?
bne 2f
add x4,x4,x1 // add divisor to sum
cmp x1,x2 // divisor = quotient ?
beq 3f // yes -> end
add x4,x4,x2 // no -> add quotient to sum
2:
add x1,x1,#1 // increment factor
b 1b // and loop
3:
mov x0,x4 // return sum
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/***************************************************/
/* search and store result in array */
/***************************************************/
/* x0 contains the number */
/* x1 contains factors sum */
/* x0 return 1 if find 0 else -1 if error */
searchRes:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
ldr x4,qAdrtResult // array address
mov x2,#0 // indice begin
1:
ldr x3,[x4,x2,lsl #3] // load one result array
cmp x3,#0 // if 0 store new result
beq 2f
cmp x3,x0 // equal ?
beq 3f // find -> return 1
add x2,x2,#1 // increment indice
cmp x2,#TABMAXI // maxi array ?
blt 1b
ldr x0,qAdrszMessErr1 // error
bl affichageMess
mov x0,#-1
b 100f
2:
str x1,[x4,x2,lsl #3]
mov x0,#0 // not find -> store and retun 0
b 100f
3:
mov x0,#1
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrtResult: .quad tResult
qAdrszMessErr1: .quad szMessErr1
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Ada | Ada | with Gtk.Main;
with Gtk.Handlers;
with Gtk.Label;
with Gtk.Button;
with Gtk.Window;
with Glib.Main;
procedure Animation is
Scroll_Forwards : Boolean := True;
package Button_Callbacks is new Gtk.Handlers.Callback
(Gtk.Button.Gtk_Button_Record);
package Label_Timeout is new Glib.Main.Generic_Sources
(Gtk.Label.Gtk_Label);
package Window_Callbacks is new Gtk.Handlers.Return_Callback
(Gtk.Window.Gtk_Window_Record, Boolean);
-- Callback for click event
procedure On_Button_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class);
-- Callback for delete event
function On_Main_Window_Delete
(Object : access Gtk.Window.Gtk_Window_Record'Class)
return Boolean;
function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean;
procedure On_Button_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class)
is
pragma Unreferenced (Object);
begin
Scroll_Forwards := not Scroll_Forwards;
end On_Button_Click;
function On_Main_Window_Delete
(Object : access Gtk.Window.Gtk_Window_Record'Class)
return Boolean
is
pragma Unreferenced (Object);
begin
Gtk.Main.Main_Quit;
return True;
end On_Main_Window_Delete;
function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean is
Text : constant String := Gtk.Label.Get_Text (Data);
begin
if Scroll_Forwards then
Gtk.Label.Set_Text
(Label => Data,
Str => Text (Text'First + 1 .. Text'Last) & Text (Text'First));
else
Gtk.Label.Set_Text
(Label => Data,
Str => Text (Text'Last) & Text (Text'First .. Text'Last - 1));
end if;
return True;
end Scroll_Text;
Main_Window : Gtk.Window.Gtk_Window;
Text_Button : Gtk.Button.Gtk_Button;
Scrolling_Text : Gtk.Label.Gtk_Label;
Timeout_ID : Glib.Main.G_Source_Id;
pragma Unreferenced (Timeout_ID);
begin
Gtk.Main.Init;
Gtk.Window.Gtk_New (Window => Main_Window);
Gtk.Label.Gtk_New (Label => Scrolling_Text, Str => "Hello World! ");
Gtk.Button.Gtk_New (Button => Text_Button);
Gtk.Button.Add (Container => Text_Button, Widget => Scrolling_Text);
Button_Callbacks.Connect
(Widget => Text_Button,
Name => "clicked",
Marsh => Button_Callbacks.To_Marshaller (On_Button_Click'Access));
Timeout_ID :=
Label_Timeout.Timeout_Add
(Interval => 125,
Func => Scroll_Text'Access,
Data => Scrolling_Text);
Gtk.Window.Add (Container => Main_Window, Widget => Text_Button);
Window_Callbacks.Connect
(Widget => Main_Window,
Name => "delete_event",
Marsh => Window_Callbacks.To_Marshaller (On_Main_Window_Delete'Access));
Gtk.Window.Show_All (Widget => Main_Window);
Gtk.Main.Main;
end Animation; |
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
| #360_Assembly | 360 Assembly | * Angle difference between two bearings - 06/06/2018
ANGLEDBB CSECT
USING ANGLEDBB,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,T-4 @t
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LA R10,4(R10) next @t
L R7,0(R10) a=t(i,1)
LA R10,4(R10) next @t
L R8,0(R10) b=t(i,2)
LR R4,R8 b
SR R4,R7 b-a
SRDA R4,32 ~
D R4,=F'3600000' /360
A R4,=F'5400000' +540
SRDA R4,32 ~
D R4,=F'3600000' /360
S R4,=F'1800000' x=((((b-a)//360)+540)//360)-180
XDECO R7,XDEC edit a
MVC PG(8),XDEC output a
MVC PG+9(4),XDEC+8 output a decimals
XDECO R8,XDEC edit b
MVC PG+14(8),XDEC output b
MVC PG+23(4),XDEC+8 output b decimals
XDECO R4,XDEC edit x
MVC PG+28(8),XDEC output x
MVC PG+37(4),XDEC+8 output x decimals
XPRNT PG,L'PG print
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
N DC F'8' number of pairs
T DC F'200000',F'450000',F'-450000',F'450000'
DC F'-850000',F'900000',F'-950000',F'900000'
DC F'-450000',F'1250000',F'450000',F'1450000'
DC F'294803',F'-886361',F'-783251',F'-1590360'
PG DC CL80'12345678.1234 12345678.1234 12345678.1234'
XDEC DS CL12 temp
YREGS
END ANGLEDBB |
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
| #BaCon | BaCon | DECLARE idx$ ASSOC STRING
FUNCTION Deranged(a$, b$)
FOR i = 1 TO LEN(a$)
IF MID$(a$, i, 1) = MID$(b$, i, 1) THEN RETURN FALSE
NEXT
RETURN TRUE
END FUNCTION
FOR w$ IN LOAD$(DIRNAME$(ME$) & "/unixdict.txt") STEP NL$
set$ = EXTRACT$(SORT$(EXPLODE$(w$, 1)), " ")
idx$(set$) = APPEND$(idx$(set$), 0, w$)
NEXT
FOR w$ IN OBTAIN$(idx$)
FOR x = 1 TO AMOUNT(idx$(w$))
FOR y = x+1 TO AMOUNT(idx$(w$))
IF Deranged(TOKEN$(idx$(w$), x), TOKEN$(idx$(w$), y)) AND LEN(TOKEN$(idx$(w$), x)) > current THEN
current = LEN(TOKEN$(idx$(w$), x))
an1$ = TOKEN$(idx$(w$), x)
an2$ = TOKEN$(idx$(w$), y)
END IF
NEXT
NEXT
NEXT
PRINT "Maximum deranged anagrams: ", an1$, " and ", an2$
PRINT NL$, "Total time: ", TIMER, " msecs.", NL$ |
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.
| #BQN | BQN | {
(𝕩<2)◶⟨+´𝕊¨,𝕏⟩𝕩-1‿2
}¨↕10 |
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.
| #Action.21 | Action! | INCLUDE "H6:SIEVE.ACT"
CARD FUNC SumDivisors(CARD x)
CARD i,max,sum
sum=1 i=2 max=x
WHILE i<max
DO
IF x MOD i=0 THEN
max=x/i
IF i<max THEN
sum==+i+max
ELSEIF i=max THEN
sum==+i
FI
FI
i==+1
OD
RETURN (sum)
PROC Main()
DEFINE MAXNUM="20000"
BYTE ARRAY primes(MAXNUM+1)
CARD m,n
Put(125) PutE() ;clear the screen
Sieve(primes,MAXNUM+1)
FOR m=1 TO MAXNUM-1
DO
IF primes(m)=0 THEN
n=SumDivisors(m)
IF n<MAXNUM AND primes(n)=0 AND n>m THEN
IF m=SumDivisors(n) THEN
PrintF("%U %U%E",m,n)
FI
FI
FI
OD
RETURN |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Applesoft_BASIC | Applesoft BASIC | 10 LET T$ = "HELLO WORLD! ":P = 1:L = LEN (T$):T$ = T$ + T$
20 D = 1: VTAB INT (( PEEK (35) - PEEK (34)) / 2) + 1: FOR R = 1 TO 0 STEP 0
30 HTAB INT (( PEEK (33) - L) / 2) + 1: PRINT MID$ (T$,P,L);
40 P = P + D: IF P > L THEN P = 1
50 IF P < 1 THEN P = L
60 R = PEEK (49152) < 128: FOR I = 1 TO 5:B = PEEK (49249) > 127: IF B < > BO THEN BO = B: IF B = 0 THEN D = - D
70 NEXT I,R:R = PEEK (49168) |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program diffAngle64.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szMessResult: .asciz "Difference between @ and @ = @ \n"
.align 8
fB1: .double 0F20.0
fB2: .double 0F45.0
fB3: .double 0F-45.0
fB4: .double 0F-85.0
fB5: .double 90.0
fB6: .double -95.0
fB7: .double 125.0
fB8: .double 145.0
fB9: .double 0F29.4803
fB10: .double 0F-88.6381
fB11: .double 0F-78.3251
fB12: .double 0F-159.036
fB13: .double 0F-70099.74233810938
fB14: .double 0F29840.67437876723
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
ldr x0,qAdrfB1
ldr x1,qAdrfB2
bl testComputeAngle
//b 100f
ldr x0,qAdrfB3
ldr x1,qAdrfB2
bl testComputeAngle
ldr x0,qAdrfB4
ldr x1,qAdrfB5
bl testComputeAngle
ldr x0,qAdrfB6
ldr x1,qAdrfB5
bl testComputeAngle
ldr x0,qAdrfB3
ldr x1,qAdrfB7
bl testComputeAngle
ldr x0,qAdrfB3
ldr x1,qAdrfB8
bl testComputeAngle
ldr x0,qAdrfB9
ldr x1,qAdrfB10
bl testComputeAngle
ldr x0,qAdrfB11
ldr x1,qAdrfB12
bl testComputeAngle
ldr x0,qAdrfB13
ldr x1,qAdrfB14
bl testComputeAngle
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrfB1: .quad fB1
qAdrfB2: .quad fB2
qAdrfB3: .quad fB3
qAdrfB4: .quad fB4
qAdrfB5: .quad fB5
qAdrfB6: .quad fB6
qAdrfB7: .quad fB7
qAdrfB8: .quad fB8
qAdrfB9: .quad fB9
qAdrfB10: .quad fB10
qAdrfB11: .quad fB11
qAdrfB12: .quad fB12
qAdrfB13: .quad fB13
qAdrfB14: .quad fB14
/******************************************************************/
/* compute difference and display result */
/******************************************************************/
/* s0 contains bearing 1 */
/* s1 contains bearing 2 */
testComputeAngle:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr d0,[x0]
fmov d2,d0
ldr d1,[x1]
bl computeDiffAngle
fmov d3,d0
fmov d0,d2
ldr x0,qAdrsZoneConv
bl convertirFloat
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
mov x3,x0
fmov d0,d1
ldr x0,qAdrsZoneConv
bl convertirFloat
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
mov x3,x0
fmov d0,d3
ldr x0,qAdrsZoneConv
bl convertirFloat
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* compute difference of two bearing */
/******************************************************************/
/* d0 contains bearing 1 */
/* d1 contains bearing 2 */
computeDiffAngle:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp d1,d2,[sp,-16]! // save registres
stp d3,d4,[sp,-16]! // save registres
mov x1,#360
mov x4,#0 // top positive/negative
fcvtzs d4,d0 // conversion.integer
scvtf d2,d4 // conversion float
fsub d2,d0,d2 // partie décimale
fmov x0,d4 // partie entière
cmp x0,#0 // negative ?
bge 1f
neg x0,x0 // yes -> inversion
mov x4,#1
1:
udiv x2,x0,x1 // divide by 360
msub x3,x2,x1,x0
cmp x4,#0 // value negative ?
neg x5,x3
csel x3,x5,x3,ne // inversion remainder
fmov d3,x3
scvtf d3,d3 // and conversion float
fadd d0,d3,d2 // add decimal part
mov x4,#0 // bearing 2
fcvtzs d4,d1 // conversion integer
scvtf d2,d4 // conversion float
fsub d2,d1,d2 // partie décimale
fmov x0,d4
cmp x0,#0
bge 2f
neg x0,x0
mov x4,#1
2:
udiv x2,x0,x1 // divide by 360
msub x3,x2,x1,x0
cmp x4,#0
neg x5,x3
csel x3,x5,x3,ne // inversion remainder
fmov d3,x3
scvtf d3,d3 // conversion float
fadd d1,d3,d2
fsub d0,d1,d0 // calculate the difference between the 2 values
mov x0,180
fmov d3,x0
scvtf d3,d3 // conversion float 180
fmov d4,x1 // 360
scvtf d4,d4 // conversion float 360
fcmp d0,#0.0 // difference is negative ?
blt 2f
// difference is positive
fcmp d0,d4 // difference > 360
ble 3f
fsub d0,d0,d4 // yes -> difference - 360
3:
fcmp d0,d3 // compare difference and 180
ble 100f
fsub d0,d4,d0 // > 180 calculate 360 - difference
fneg d0,d0 // and negate
b 100f
2: // différence is négative
fneg d2,d4 // -360
fcmp d0,d2 // compare différence et - 360
ble 3f
fsub d0,d0,d4 // sub 360 to différence
3:
fneg d3,d3 // -180
fcmp d0,d3 // compare difference and -180
bge 100f
fadd d0,d4,d0 // calculate 360 + différence
100:
ldp d3,d4,[sp],16 // restaur registers
ldp d1,d2,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* Conversion Float */
/******************************************************************/
/* d0 contains Float */
/* x0 contains address conversion area mini 20 charactèrs */
/* x0 return result length */
/* see https://blog.benoitblanchon.fr/lightweight-float-to-string/ */
convertirFloat:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
stp d1,d2,[sp,-16]! // save registres
mov x6,x0 // save area address
fmov x0,d0
mov x8,#0 // result length
mov x3,#'+'
strb w3,[x6] // signe + forcing
mov x2,x0
tbz x2,63,1f
mov x2,1
lsl x2,x2,63
bic x0,x0,x2
mov x3,#'-' // sign -
strb w3,[x6]
1:
adds x8,x8,#1 // next position
cmp x0,#0 // case 0 positive or negative
bne 2f
mov x3,#'0'
strb w3,[x6,x8] // store character 0
adds x8,x8,#1
strb wzr,[x6,x8] // store 0 final
mov x0,x8 // return length
b 100f
2:
ldr x2,iMaskExposant
mov x1,x0
and x1,x1,x2 // exposant
cmp x1,x2
bne 4f
tbz x0,51,3f // test bit 51 to zéro
mov x2,#'N' // case Nan. store byte no possible store integer
strb w2,[x6] // area no aligned
mov x2,#'a'
strb w2,[x6,#1]
mov x2,#'n'
strb w2,[x6,#2]
mov x2,#0 // 0 final
strb w2,[x6,#3]
mov x0,#3
b 100f
3: // case infini positive or négative
mov x2,#'I'
strb w2,[x6,x8]
adds x8,x8,#1
mov x2,#'n'
strb w2,[x6,x8]
adds x8,x8,#1
mov x2,#'f'
strb w2,[x6,x8]
adds x8,x8,#1
mov x2,#0
strb w2,[x6,x8]
mov x0,x8
b 100f
4:
bl normaliserFloat
mov x5,x0 // save exposant
fcvtzu d2,d0
fmov x0,d2 // part integer
scvtf d1,d2 // conversion float
fsub d1,d0,d1 // extraction part fractional
ldr d2,dConst1
fmul d1,d2,d1 // to crop it in full
fcvtzu d1,d1 // convertion integer
fmov x4,d1 // fract value
// conversion part integer to x0
mov x2,x6 // save address begin area
adds x6,x6,x8
mov x1,x6
bl conversion10
add x6,x6,x0
mov x3,#','
strb w3,[x6]
adds x6,x6,#1
mov x0,x4 // conversion part fractionnaire
mov x1,x6
bl conversion10SP
add x6,x6,x0
sub x6,x6,#1
// remove trailing zeros
5:
ldrb w0,[x6]
cmp w0,#'0'
bne 6f
sub x6,x6,#1
b 5b
6:
cmp w0,#','
bne 7f
sub x6,x6,#1
7:
cmp x5,#0 // if exposant = 0 no display
bne 8f
add x6,x6,#1
b 10f
8:
add x6,x6,#1
mov x3,#'E'
strb w3,[x6]
add x6,x6,#1
mov x0,x5 // conversion exposant
mov x3,x0
tbz x3,63,9f // exposant negative ?
neg x0,x0
mov x3,#'-'
strb w3,[x6]
adds x6,x6,#1
9:
mov x1,x6
bl conversion10
add x6,x6,x0
10:
strb wzr,[x6] // store 0 final
adds x6,x6,#1
mov x0,x6
subs x0,x0,x2 // retour de la longueur de la zone
subs x0,x0,#1 // sans le 0 final
100:
ldp d1,d2,[sp],16 // restaur registres
ldp x8,x9,[sp],16 // restaur registres
ldp x6,x7,[sp],16 // restaur registres
ldp x4,x5,[sp],16 // restaur registres
ldp x2,x3,[sp],16 // restaur registres
ldp x1,lr,[sp],16 // restaur registres
ret
iMaskExposant: .quad 0x7FF<<52
dConst1: .double 0f1E17
/***************************************************/
/* normaliser float */
/***************************************************/
/* x0 contain float value (always positive value and <> Nan) */
/* d0 return new value */
/* x0 return exposant */
normaliserFloat:
stp x1,lr,[sp,-16]! // save registers
fmov d0,x0 // value float
mov x0,#0 // exposant
ldr d1,dConstE7 // no normalisation for value < 1E7
fcmp d0,d1
blo 10f // if d0 < dConstE7
ldr d1,dConstE256
fcmp d0,d1
blo 1f
fdiv d0,d0,d1
adds x0,x0,#256
1:
ldr d1,dConstE128
fcmp d0,d1
blo 1f
fdiv d0,d0,d1
adds x0,x0,#128
1:
ldr d1,dConstE64
fcmp d0,d1
blo 1f
fdiv d0,d0,d1
adds x0,x0,#64
1:
ldr d1,dConstE32
fcmp d0,d1
blo 1f
fdiv d0,d0,d1
adds x0,x0,#32
1:
ldr d1,dConstE16
fcmp d0,d1
blo 2f
fdiv d0,d0,d1
adds x0,x0,#16
2:
ldr d1,dConstE8
fcmp d0,d1
blo 3f
fdiv d0,d0,d1
adds x0,x0,#8
3:
ldr d1,dConstE4
fcmp d0,d1
blo 4f
fdiv d0,d0,d1
adds x0,x0,#4
4:
ldr d1,dConstE2
fcmp d0,d1
blo 5f
fdiv d0,d0,d1
adds x0,x0,#2
5:
ldr d1,dConstE1
fcmp d0,d1
blo 10f
fdiv d0,d0,d1
adds x0,x0,#1
10:
ldr d1,dConstME5 // pas de normalisation pour les valeurs > 1E-5
fcmp d0,d1
bhi 100f // fin
ldr d1,dConstME255
fcmp d0,d1
bhi 11f
ldr d1,dConstE256
fmul d0,d0,d1
subs x0,x0,#256
11:
ldr d1,dConstME127
fcmp d0,d1
bhi 11f
ldr d1,dConstE128
fmul d0,d0,d1
subs x0,x0,#128
11:
ldr d1,dConstME63
fcmp d0,d1
bhi 11f
ldr d1,dConstE64
fmul d0,d0,d1
subs x0,x0,#64
11:
ldr d1,dConstME31
fcmp d0,d1
bhi 11f
ldr d1,dConstE32
fmul d0,d0,d1
subs x0,x0,#32
11:
ldr d1,dConstME15
fcmp d0,d1
bhi 12f
ldr d1,dConstE16
fmul d0,d0,d1
subs x0,x0,#16
12:
ldr d1,dConstME7
fcmp d0,d1
bhi 13f
ldr d1,dConstE8
fmul d0,d0,d1
subs x0,x0,#8
13:
ldr d1,dConstME3
fcmp d0,d1
bhi 14f
ldr d1,dConstE4
fmul d0,d0,d1
subs x0,x0,#4
14:
ldr d1,dConstME1
fcmp d0,d1
bhi 15f
ldr d1,dConstE2
fmul d0,d0,d1
subs x0,x0,#2
15:
ldr d1,dConstE0
fcmp d0,d1
bhi 100f
ldr d1,dConstE1
fmul d0,d0,d1
subs x0,x0,#1
100: // fin standard de la fonction
ldp x1,lr,[sp],16 // restaur registres
ret
.align 2
dConstE7: .double 0f1E7
dConstE256: .double 0f1E256
dConstE128: .double 0f1E128
dConstE64: .double 0f1E64
dConstE32: .double 0f1E32
dConstE16: .double 0f1E16
dConstE8: .double 0f1E8
dConstE4: .double 0f1E4
dConstE2: .double 0f1E2
dConstE1: .double 0f1E1
dConstME5: .double 0f1E-5
dConstME255: .double 0f1E-255
dConstME127: .double 0f1E-127
dConstME63: .double 0f1E-63
dConstME31: .double 0f1E-31
dConstME15: .double 0f1E-15
dConstME7: .double 0f1E-7
dConstME3: .double 0f1E-3
dConstME1: .double 0f1E-1
dConstE0: .double 0f1E0
/******************************************************************/
/* Décimal Conversion */
/******************************************************************/
/* x0 contain value et x1 address conversion area */
conversion10SP:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x5,x1
mov x4,#16
mov x2,x0
mov x1,#10 // décimal conversion
1: // conversion loop
mov x0,x2 // copy begin number or quotient
udiv x2,x0,x1 // division by 10
msub x3,x1,x2,x0 // compute remainder
add x3,x3,#48 // compute digit
strb w3,[x5,x4] // store byte address area (x5) + offset (x4)
subs x4,x4,#1 // position precedente
bge 1b
strb wzr,[x5,16] // 0 final
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
|
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
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
DIM dict$(26000), sort$(26000), indx%(26000)
REM Load the dictionary:
dict% = OPENIN("C:\unixdict.txt")
IF dict%=0 ERROR 100, "No dictionary file"
index% = 0
REPEAT
index% += 1
dict$(index%) = GET$#dict%
indx%(index%) = index%
UNTIL EOF#dict%
CLOSE #dict%
Total% = index%
TIME = 0
REM Sort the letters in each word:
FOR index% = 1 TO Total%
sort$(index%) = FNsortstring(dict$(index%))
NEXT
REM Sort the sorted words:
C% = Total%
CALL Sort%, sort$(1), indx%(1)
REM Find anagrams and deranged anagrams:
maxlen% = 0
maxidx% = 0
FOR index% = 1 TO Total%-1
IF sort$(index%) = sort$(index%+1) THEN
One$ = dict$(indx%(index%))
Two$ = dict$(indx%(index%+1))
FOR c% = 1 TO LEN(One$)
IF MID$(One$,c%,1) = MID$(Two$,c%,1) EXIT FOR
NEXT
IF c%>LEN(One$) IF c%>maxlen% maxlen% = c% : maxidx% = index%
ENDIF
NEXT
PRINT "The longest deranged anagrams are '" dict$(indx%(maxidx%));
PRINT "' and '" dict$(indx%(maxidx%+1)) "'"
PRINT "(taking " ; TIME/100 " seconds)"
END
DEF FNsortstring(A$)
LOCAL C%, a&()
C% = LEN(A$)
DIM a&(C%)
$$^a&(0) = A$
CALL Sort%, a&(0)
= $$^a&(0) |
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.
| #C | C | #include <stdio.h>
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf("Bad argument: fib(%ld)\n", x);
return -1;
}
return fib_i(x);
}
long fib_i(long n) /* just to show the fib_i() inside fib() has no bearing outside it */
{
printf("This is not the fib you are looking for\n");
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf("fib %ld = %ld\n", x, fib(x));
printf("calling fib_i from outside fib:\n");
fib_i(3);
return 0;
} |
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.
| #Ada | Ada | with Ada.Text_IO, Generic_Divisors; use Ada.Text_IO;
procedure Amicable_Pairs is
function Same(P: Positive) return Positive is (P);
package Divisor_Sum is new Generic_Divisors
(Result_Type => Natural, None => 0, One => Same, Add => "+");
Num2 : Integer;
begin
for Num1 in 4 .. 20_000 loop
Num2 := Divisor_Sum.Process(Num1);
if Num1 < Num2 then
if Num1 = Divisor_Sum.Process(Num2) then
Put_Line(Integer'Image(Num1) & "," & Integer'Image(Num2));
end if;
end if;
end loop;
end Amicable_Pairs; |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #AutoHotkey | AutoHotkey | SetTimer, Animate ; Timer runs every 250 ms.
String := "Hello World "
Gui, Add, Text, vS gRev, %String%
Gui, +AlwaysOnTop -SysMenu
Gui, Show
Return
Animate:
String := (!Reverse) ? (SubStr(String, 0) . Substr(String, 1, StrLen(String)-1)) : (SubStr(String, 2) . SubStr(String, 1, 1))
GuiControl,,S, %String%
return
Rev: ; Runs whenever user clicks on the text control
Reverse := !Reverse
return |
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
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
INT FUNC AngleI(INT a1,a2)
INT r
r=a2-a1
WHILE r>180 DO r==-360 OD
WHILE r<-180 DO r==+360 OD
RETURN (r)
PROC TestI(INT a1,a2)
INT r
r=AngleI(a1,a2)
PrintF("%I .. %I = %I%E",a1,a2,r)
RETURN
PROC AngleR(REAL POINTER r1,r2,r)
REAL tmp,r180,rm180,r360
ValR("180",r180)
ValR("-180",rm180)
ValR("360",r360)
RealSub(r2,r1,r)
WHILE RealGreaterOrEqual(r,r180)
DO
RealSub(r,r360,tmp) RealAssign(tmp,r)
OD
WHILE RealGreaterOrEqual(rm180,r)
DO
RealAdd(r,r360,tmp) RealAssign(tmp,r)
OD
RETURN
PROC TestR(CHAR ARRAY s1,s2)
REAL r1,r2,r
ValR(s1,r1) ValR(s2,r2)
AngleR(r1,r2,r)
PrintR(r1) Print(" .. ") PrintR(r2)
Print(" = ") PrintRE(r)
RETURN
PROC Main()
Put(125) PutE() ;clear screen
TestI(20,45)
TestI(-45,45)
TestI(-85,90)
TestI(-95,90)
TestI(-45,125)
TestI(-45,145)
TestR("29.4803","-88.6381")
TestR("-78.3251","-159.036")
TestR("-70099.74233810938","29840.67437876723")
TestR("-165313.6666297357","33693.9894517456")
TestR("1174.8380510598456","-154146.66490124757")
TestR("60175.77306795546","42213.07192354373")
RETURN |
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
| #Bracmat | Bracmat | get$("unixdict.txt",STR):?wordList
& 1:?product
& :?unsorted
& whl
' ( @(!wordList:(%?word:?letterString) \n ?wordList)
& :?letterSum
& whl
' ( @(!letterString:%?letter ?letterString)
& (!letter:~#|str$(N !letter))+!letterSum
: ?letterSum
)
& !letterSum^!word !unsorted:?unsorted
)
& ( mergeSort
= newL L first second
. !arg:?L
& whl
' ( !L:% %
& :?newL
& whl
' ( !L:%?first %?second ?L
& !first*!second !newL:?newL
)
& !L !newL:?L
)
& !L
)
& mergeSort$!unsorted:?product
& 0:?maxLength:?oldMaxLength
& :?derangedAnagrams
& ( deranged
= nextLetter Atail Btail
. !arg
: ( (.)
| ( @(?:%@?nextLetter ?Atail)
. @(?:(%@:~!nextLetter) ?Btail)
)
& deranged$(!Atail.!Btail)
)
)
& ( !product
: ?
* ?
^ ( %+%
: @(%:? ([~<!maxLength:[?maxLength))+?
: ?
+ %@?anagramA
+ ?
+ %@?anagramB
+ ( ?
& deranged$(!anagramA.!anagramB)
& (!anagramA.!anagramB)
( !maxLength:>!oldMaxLength:?oldMaxLength
&
| !derangedAnagrams
)
: ?derangedAnagrams
& ~
)
)
* ?
| out$!derangedAnagrams
); |
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.
| #C.23 | C# |
static int Fib(int n)
{
if (n < 0) throw new ArgumentException("Must be non negativ", "n");
Func<int, int> fib = null; // Must be known, before we can assign recursively to it.
fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;
return fib(n);
}
|
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #11l | 11l | V values = [Float(-2), -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
F normd(x) {R fmod(x, 360)}
F normg(x) {R fmod(x, 400)}
F normm(x) {R fmod(x, 6400)}
F normr(x) {R fmod(x, (2 * math:pi))}
F d2g(x) {R normd(x) * 10 / 9}
F d2m(x) {R normd(x) * 160 / 9}
F d2r(x) {R normd(x) * math:pi / 180}
F g2d(x) {R normg(x) * 9 / 10}
F g2m(x) {R normg(x) * 16}
F g2r(x) {R normg(x) * math:pi / 200}
F m2d(x) {R normm(x) * 9 / 160}
F m2g(x) {R normm(x) / 16}
F m2r(x) {R normm(x) * math:pi / 3200}
F r2d(x) {R normr(x) * 180 / math:pi}
F r2g(x) {R normr(x) * 200 / math:pi}
F r2m(x) {R normr(x) * 3200 / math:pi}
print(‘ Degrees Normalized Gradians Mils Radians’)
print(‘───────────────────────────────────────────────────────────────────────────────────’)
L(val) values
print(‘#7.7 #7.7 #7.7 #7.7 #7.7’.format(val, normd(val), d2g(val), d2m(val), d2r(val)))
print()
print(‘ Gradians Normalized Degrees Mils Radians’)
print(‘───────────────────────────────────────────────────────────────────────────────────’)
L(val) values
print(‘#7.7 #7.7 #7.7 #7.7 #7.7’.format(val, normg(val), g2d(val), g2m(val), g2r(val)))
print()
print(‘ Mils Normalized Degrees Gradians Radians’)
print(‘───────────────────────────────────────────────────────────────────────────────────’)
L(val) values
print(‘#7.7 #7.7 #7.7 #7.7 #7.7’.format(val, normm(val), m2d(val), m2g(val), m2r(val)))
print()
print(‘ Radians Normalized Degrees Gradians Mils’)
print(‘───────────────────────────────────────────────────────────────────────────────────’)
L(val) values
print(‘#7.7 #7.7 #7.7 #7.7 #7.7’.format(val, normr(val), r2d(val), r2g(val), r2m(val))) |
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.
| #ALGOL_60 | ALGOL 60 |
begin
comment - return n mod m;
integer procedure mod(n, m);
value n, q; integer n, m;
begin
mod := n - m * entier(n / m);
end;
comment - return sum of the proper divisors of n;
integer procedure sumf(n);
value n; integer n;
begin
integer sum, f1, f2;
sum := 1;
f1 := 2;
for f1 := f1 while (f1 * f1) <= n do
begin
if mod(n, f1) = 0 then
begin
sum := sum + f1;
f2 := n / f1;
if f2 > f1 then sum := sum + f2;
end;
f1 := f1 + 1;
end;
sumf := sum;
end;
comment - main program begins here;
integer a, b, found;
outstring(1,"Searching up to 20000 for amicable pairs\n");
found := 0;
for a := 2 step 1 until 20000 do
begin
b := sumf(a);
if b > a then
begin
if a = sumf(b) then
begin
found := found + 1;
outinteger(1,a);
outinteger(1,b);
outstring(1,"\n");
end;
end;
end;
outinteger(1,found);
outstring(1,"pairs were found");
end
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #BASIC256 | BASIC256 | str$="Hello, World! "
direction=0 #value of 0: to the right, 1: to the left.
tlx=10 #Top left x
tly=10 #Top left y
fastgraphics
font "Arial",20,100 #The Font configuration (Font face, size, weight)
main:
while clickb=0
if direction=0 then
str$=RIGHT(str$,1) + LEFT(str$,length(str$)-1)
else
str$=MID(str$,2,length(str$)-1)+LEFT(str$,1)
end if
refresh
clg
color red
text tlx,tly,str$
pause .1
end while
#Note: textheight() and textwidth() depends on the latest configuration of the FONT command.
if clickb=1 and clickx>=tlx and clickx<=tlx+textwidth(str$) and clicky>=tly and clicky<=tly+textheight() then
direction=NOT direction
end if
clickclear
goto main |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #BBC_BASIC | BBC BASIC | VDU 23,22,212;40;16,32,16,128
txt$ = "Hello World! "
direction% = TRUE
ON MOUSE direction% = NOT direction% : RETURN
OFF
REPEAT
CLS
PRINT txt$;
IF direction% THEN
txt$ = RIGHT$(txt$) + LEFT$(txt$)
ELSE
txt$ = MID$(txt$,2) + LEFT$(txt$,1)
ENDIF
WAIT 20
UNTIL FALSE |
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
| #Ada | Ada |
-----------------------------------------------------------------------
-- Angle difference between two bearings
-----------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
procedure Bearing_Angles is
type Real is digits 8;
Package Real_Io is new Ada.Text_IO.Float_IO(Real);
use Real_IO;
type Angles is record
B1 : Real;
B2 : Real;
end record;
type Angle_Arr is array(Positive range <>) of Angles;
function fmod(Left, Right : Real) return Real is
Result : Real;
begin
Result := Left - Right*Real'Truncation(Left / Right);
return Result;
end fmod;
The_Angles : Angle_Arr := ((20.0,45.0),(-45.0, 45.0), (-85.0, 90.0),
(-95.0, 90.0), (-14.0, 125.0), (29.4803, -88.6381),
(-78.3251, -159.036),
(-70099.74233810938, 29840.67437876723),
(-165313.6666297357, 33693.9894517456),
(1174.8380510598456, -154146.66490124757),
(60175.77306795546, 42213.07192354373));
Diff : Real;
begin
for A of The_Angles loop
Diff := fmod(A.b2 - A.b1, 360.0);
If Diff < -180.0 then
Diff := Diff + 360.0;
elsif Diff > 180.0 then
Diff := Diff - 360.0;
end if;
Put("Difference between ");
Put(Item => A.B2, Fore => 7, Aft => 4, Exp => 0);
Put(" and ");
Put(Item => A.B1, Fore => 7, Aft => 4, Exp => 0);
Put(" is ");
Put(Item => Diff, Fore => 4, Aft => 4, Exp => 0);
New_Line;
end loop;
end Bearing_Angles;
|
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
// Letter lookup by frequency. This is to reduce word insertion time.
const char *freq = "zqxjkvbpygfwmucldrhsnioate";
int char_to_idx[128];
// Trie structure of sorts
struct word {
const char *w;
struct word *next;
};
union node {
union node *down[10];
struct word *list[10];
};
int deranged(const char *s1, const char *s2)
{
int i;
for (i = 0; s1[i]; i++)
if (s1[i] == s2[i]) return 0;
return 1;
}
int count_letters(const char *s, unsigned char *c)
{
int i, len;
memset(c, 0, 26);
for (len = i = 0; s[i]; i++) {
if (s[i] < 'a' || s[i] > 'z')
return 0;
len++, c[char_to_idx[(unsigned char)s[i]]]++;
}
return len;
}
const char * insert(union node *root, const char *s, unsigned char *cnt)
{
int i;
union node *n;
struct word *v, *w = 0;
for (i = 0; i < 25; i++, root = n) {
if (!(n = root->down[cnt[i]]))
root->down[cnt[i]] = n = calloc(1, sizeof(union node));
}
w = malloc(sizeof(struct word));
w->w = s;
w->next = root->list[cnt[25]];
root->list[cnt[25]] = w;
for (v = w->next; v; v = v->next) {
if (deranged(w->w, v->w))
return v->w;
}
return 0;
}
int main(int c, char **v)
{
int i, j = 0;
char *words;
struct stat st;
int fd = open(c < 2 ? "unixdict.txt" : v[1], O_RDONLY);
if (fstat(fd, &st) < 0) return 1;
words = malloc(st.st_size);
read(fd, words, st.st_size);
close(fd);
union node root = {{0}};
unsigned char cnt[26];
int best_len = 0;
const char *b1, *b2;
for (i = 0; freq[i]; i++)
char_to_idx[(unsigned char)freq[i]] = i;
/* count words, change newline to null */
for (i = j = 0; i < st.st_size; i++) {
if (words[i] != '\n') continue;
words[i] = '\0';
if (i - j > best_len) {
count_letters(words + j, cnt);
const char *match = insert(&root, words + j, cnt);
if (match) {
best_len = i - j;
b1 = words + j;
b2 = match;
}
}
j = ++i;
}
if (best_len) printf("longest derangement: %s %s\n", b1, b2);
return 0;
} |
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.
| #C.2B.2B | C++ | double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
static double calc(double n)
{
if(n < 2)
{
return n;
}
else
{
return calc(n-1) + calc(n-2);
}
}
};
return actual_fib::calc(n);
}
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #AutoHotkey | AutoHotkey | testAngles := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
result .= "Degrees Degrees Gradians Mils Radians`n"
for i, a in testAngles
result .= a "`t" Deg2Deg(a) "`t" Deg2Grad(a) "`t" Deg2Mil(a) "`t" Deg2Rad(a) "`n"
result .= "`nGradians Degrees Gradians Mils Radians`n"
for i, a in testAngles
result .= a "`t" Grad2Deg(a) "`t" Grad2Grad(a) "`t" Grad2Mil(a) "`t" Grad2Rad(a) "`n"
result .= "`nMills Degrees Gradians Mils Radians`n"
for i, a in testAngles
result .= a "`t" Mil2Deg(a) "`t" Mil2Grad(a) "`t" Mil2Mil(a) "`t" Mil2Rad(a) "`n"
result .= "`nRadians Degrees Gradians Mils Radians`n"
for i, a in testAngles
result .= a "`t" Rad2Deg(a) "`t" Rad2Grad(a) "`t" Rad2Mil(a) "`t" Rad2Rad(a) "`n"
MsgBox, 262144, , % result
return
;-------------------------------------------------------
Deg2Deg(Deg){
return Mod(Deg, 360)
}
Deg2Grad(Deg){
return Deg2Deg(Deg) * 400 / 360
}
Deg2Mil(Deg){
return Deg2Deg(Deg) * 6400 / 360
}
Deg2Rad(Deg){
return Deg2Deg(Deg) * (π:=3.141592653589793) / 180
}
;-------------------------------------------------------
Grad2Grad(Grad){
return Mod(Grad, 400)
}
Grad2Deg(Grad){
return Grad2Grad(Grad) * 360 / 400
}
Grad2Mil(Grad){
return Grad2Grad(Grad) * 6400 / 400
}
Grad2Rad(Grad){
return Grad2Grad(Grad) * (π:=3.141592653589793) / 200
}
;-------------------------------------------------------
Mil2Mil(Mil){
return Mod(Mil, 6400)
}
Mil2Deg(Mil){
return Mil2Mil(Mil) * 360 / 6400
}
Mil2Grad(Mil){
return Mil2Mil(Mil) * 400 / 6400
}
Mil2Rad(Mil){
return Mil2Mil(Mil) * (π:=3.141592653589793) / 3200
}
;-------------------------------------------------------
Rad2Rad(Rad){
return Mod(Rad, 2*(π:=3.141592653589793))
}
Rad2Deg(Rad){
return Rad2Rad(Rad) * 180 / (π:=3.141592653589793)
}
Rad2Grad(Rad){
return Rad2Rad(Rad) * 200 / (π:=3.141592653589793)
}
Rad2Mil(Rad){
return Rad2Rad(Rad) * 3200 / (π:=3.141592653589793)
}
;------------------------------------------------------- |
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.
| #ALGOL_68 | ALGOL 68 | # returns the sum of the proper divisors of n #
# if n = 1, 0 or -1, we return 0 #
PROC sum proper divisors = ( INT n )INT:
BEGIN
INT result := 0;
INT abs n = ABS n;
IF abs n > 1 THEN
FOR d FROM ENTIER sqrt( abs n ) BY -1 TO 2 DO
IF abs n MOD d = 0 THEN
# found another divisor #
result +:= d;
IF d * d /= n THEN
# include the other divisor #
result +:= n OVER d
FI
FI
OD;
# 1 is always a proper divisor of numbers > 1 #
result +:= 1
FI;
result
END # sum proper divisors # ;
# construct a table of the sum of the proper divisors of numbers #
# up to 20 000 #
INT max number = 20 000;
[ 1 : max number ]INT proper divisor sum;
FOR n TO UPB proper divisor sum DO proper divisor sum[ n ] := sum proper divisors( n ) OD;
# returns TRUE if n1 and n2 are an amicable pair FALSE otherwise #
# n1 and n2 are amicable if the sum of the proper diviors #
# n1 = n2 and the sum of the proper divisors of n2 = n1 #
PROC is an amicable pair = ( INT n1, n2 )BOOL:
( proper divisor sum[ n1 ] = n2 AND proper divisor sum[ n2 ] = n1 );
# find the amicable pairs up to 20 000 #
FOR p1 TO max number DO
FOR p2 FROM p1 + 1 TO max number DO
IF is an amicable pair( p1, p2 ) THEN
print( ( whole( p1, -6 ), " and ", whole( p2, -6 ), " are an amicable pair", newline ) )
FI
OD
OD |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #C | C | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
// since we shift a whole character per time, it's better to use
// a monospace font, so that the shifting seems done at the same pace
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
} |
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
| #APL | APL | [0] D←B1 DIFF B2
[1] D←180+¯360|180+B2-B1
|
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
| #C.23 | C# | public static void Main()
{
var lookupTable = File.ReadLines("unixdict.txt").ToLookup(line => AnagramKey(line));
var query = from a in lookupTable
orderby a.Key.Length descending
let deranged = FindDeranged(a)
where deranged != null
select deranged[0] + " " + deranged[1];
Console.WriteLine(query.FirstOrDefault());
}
static string AnagramKey(string word) => new string(word.OrderBy(c => c).ToArray());
static string[] FindDeranged(IEnumerable<string> anagrams) => (
from first in anagrams
from second in anagrams
where !second.Equals(first)
&& Enumerable.Range(0, first.Length).All(i => first[i] != second[i])
select new [] { first, second })
.FirstOrDefault(); |
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.
| #Clio | Clio | 10 -> (@eager) fn n:
if n:
n - 1 -> print -> recall |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #AWK | AWK |
# syntax: GAWK -f ANGLES_(GEOMETRIC)_NORMALIZATION_AND_CONVERSION.AWK
# gawk starts showing discrepancies at test case number 7 when compared with C#
BEGIN {
pi = atan2(0,-1)
data_leng = split("-2,-1,0,1,2,6.2831853,16,57.2957795,359,399,6399,1000000",data_arr,",")
unit_leng = split("degree,gradian,mil,radian",unit_arr,",")
printf("%-10s %-10s %-8s %-12s %-12s %-12s %-12s test#\n","angle","normalized","unit","degrees","gradians","mils","radians")
for (a=1; a<=data_leng; a++) {
angle = data_arr[a]
arr["degree"] = normalize(angle,360)
arr["gradian"] = normalize(angle,400)
arr["mil"] = normalize(angle,6400)
arr["radian"] = normalize(angle,pi*2)
print("") # optional blank line between groupings
for (b=1; b<=unit_leng; b++) {
key1 = unit_arr[b]
printf("%-10s %-10s %-8s",angle,arr[key1],unit_arr[b])
for (c=1; c<=unit_leng; c++) {
key2 = unit_arr[c]
func_name = sprintf("%s2%s",key1,key2)
printf(" %-12s",(key1 == key2) ? arr[key2] : @func_name(arr[key2]))
}
printf(" %d\n",a)
}
}
# normalize_usage_stats()
exit(0)
}
function normalize(angle,n, a) {
a = angle
profile_arr[a][n]["+"] = 0
profile_arr[a][n]["-"] = 0
while (angle <= -n) { angle += n ; profile_arr[a][n]["+"]++ }
while (angle >= n) { angle -= n ; profile_arr[a][n]["-"]++ }
return(angle)
}
function normalize_usage_stats( a,b,c,n,total) {
print("")
PROCINFO["sorted_in"] = "@ind_num_asc"
for (a in profile_arr) {
for (b in profile_arr[a]) {
for (c in profile_arr[a][b]) {
n = profile_arr[a][b][c]
if (n == 0) { continue }
printf("%10s %10s %1s %7d\n",a,b,c,n)
total += n
}
}
}
printf("%31d total\n",total)
}
function degree2gradian(angle) { return(angle * 10 / 9) }
function degree2mil(angle) { return(angle * 160 / 9) }
function degree2radian(angle) { return(angle * pi / 180) }
function gradian2degree(angle) { return(angle * 9 / 10) }
function gradian2mil(angle) { return(angle * 16) }
function gradian2radian(angle) { return(angle * pi / 200) }
function mil2degree(angle) { return(angle * 9 / 160) }
function mil2gradian(angle) { return(angle / 16) }
function mil2radian(angle) { return(angle * pi / 3200) }
function radian2degree(angle) { return(angle * 180 / pi) }
function radian2gradian(angle) { return(angle * 200 / pi) }
function radian2mil(angle) { return(angle * 3200 / pi) }
|
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.
| #ANSI_Standard_BASIC | ANSI Standard BASIC | 100 DECLARE EXTERNAL FUNCTION sum_proper_divisors
110 CLEAR
120 !
130 DIM f(20001) ! sum of proper factors for each n
140 FOR i=1 TO 20000
150 LET f(i)=sum_proper_divisors(i)
160 NEXT i
170 ! look for pairs
180 FOR i=1 TO 20000
190 FOR j=i+1 TO 20000
200 IF f(i)=j AND i=f(j) THEN
210 PRINT "Amicable pair ";i;" ";j
220 END IF
230 NEXT j
240 NEXT i
250 !
260 PRINT
270 PRINT "-- found all amicable pairs"
280 END
290 !
300 ! Compute the sum of proper divisors of given number
310 !
320 EXTERNAL FUNCTION sum_proper_divisors(n)
330 !
340 IF n>1 THEN ! n must be 2 or larger
350 LET sum=1 ! start with 1
360 LET root=SQR(n) ! note that root is an integer
370 ! check possible factors, up to sqrt
380 FOR i=2 TO root
390 IF MOD(n,i)=0 THEN
400 LET sum=sum+i ! i is a factor
410 IF i*i<>n THEN ! check i is not actual square root of n
420 LET sum=sum+n/i ! so n/i will also be a factor
430 END IF
440 END IF
450 NEXT i
460 END IF
470 LET sum_proper_divisors = sum
480 END FUNCTION |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #C.23 | C# | using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program diffAngle.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"
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szMessResult: .asciz "Difference between @ and @ = @ \n"
.align 4
fB1: .float 20.0
fB2: .float 45.0
fB3: .float -45.0
fB4: .float -85.0
fB5: .float 90.0
fB6: .float -95.0
fB7: .float 125.0
fB8: .float 145.0
fB9: .float 29.4803
fB10: .float -88.6381
fB11: .float -78.3251
fB12: .float -159.036
fB13: .float -70099.74233810938
fB14: .float 29840.67437876723
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
ldr r0,iAdrfB1
ldr r1,iAdrfB2
bl testComputeAngle
ldr r0,iAdrfB3
ldr r1,iAdrfB2
bl testComputeAngle
ldr r0,iAdrfB4
ldr r1,iAdrfB5
bl testComputeAngle
ldr r0,iAdrfB6
ldr r1,iAdrfB5
bl testComputeAngle
ldr r0,iAdrfB3
ldr r1,iAdrfB7
bl testComputeAngle
ldr r0,iAdrfB3
ldr r1,iAdrfB8
bl testComputeAngle
ldr r0,iAdrfB9
ldr r1,iAdrfB10
bl testComputeAngle
ldr r0,iAdrfB11
ldr r1,iAdrfB12
bl testComputeAngle
ldr r0,iAdrfB13
ldr r1,iAdrfB14
bl testComputeAngle
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrfB1: .int fB1
iAdrfB2: .int fB2
iAdrfB3: .int fB3
iAdrfB4: .int fB4
iAdrfB5: .int fB5
iAdrfB6: .int fB6
iAdrfB7: .int fB7
iAdrfB8: .int fB8
iAdrfB9: .int fB9
iAdrfB10: .int fB10
iAdrfB11: .int fB11
iAdrfB12: .int fB12
iAdrfB13: .int fB13
iAdrfB14: .int fB14
/******************************************************************/
/* compute difference and display result */
/******************************************************************/
/* s0 contains bearing 1 */
/* s1 contains bearing 2 */
testComputeAngle:
push {r1-r3,lr} @ save registers
vldr.f32 s0,[r0]
vmov s2,s0
vldr.f32 s1,[r1]
bl computeDiffAngle
vmov s3,s0
vmov s0,s2
ldr r0,iAdrsZoneConv
bl convertirFloat
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc
mov r3,r0
vmov s0,s1
ldr r0,iAdrsZoneConv
bl convertirFloat
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc
mov r3,r0
vmov s0,s3
ldr r0,iAdrsZoneConv
bl convertirFloat
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
100:
pop {r1-r3,pc} @ restaur registers
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* compute difference of two bearing */
/******************************************************************/
/* s0 contains bearing 1 */
/* s1 contains bearing 2 */
computeDiffAngle:
push {r1-r4,lr} @ save registers
vpush {s1-s4}
mov r1,#360
mov r4,#0 @ top positive/negative
vcvt.s32.f32 s4,s0 @ conversion integer
vcvt.f32.s32 s2,s4 @ conversion float
vsub.f32 s2,s0,s2 @ partie décimale
vmov r0,s4 @ partie entière
cmp r0,#0 @ negative ?
neglt r0,r0 @ yes -> inversion
movlt r4,#1
bl division @ divide by 360 (r0 dividende r1 divisor r2 quotient r3 remainder)
cmp r4,#0 @ value negative ?
negne r3,r3 @ inversion remainder
vmov s3,r3
vcvt.f32.s32 s3,s3 @ and conversion float
vadd.f32 s0,s3,s2 @ add decimal part
mov r4,#0 @ bearing 2
vcvt.s32.f32 s4,s1 @ conversion integer
vcvt.f32.s32 s2,s4 @ conversion float
vsub.f32 s2,s1,s2 @ partie décimale
vmov r0,s4
cmp r0,#0
neglt r0,r0
movlt r4,#1
bl division @ divide by 360
cmp r4,#0
negne r3,r3 @ negate remainder
vmov s3,r3
vcvt.f32.s32 s3,s3 @ conversion float
vadd.f32 s1,s3,s2
vsub.f32 s0,s1,s0 @ calculate the difference between the 2 values
mov r0,#180
vmov s3,r0
vcvt.f32.s32 s3,s3 @ conversion float 180
vmov s4,r1 @ 360
vcvt.f32.s32 s4,s4 @ conversion float 360
vcmp.f32 s0,#0.0 @ difference is negative ?
vmrs APSR_nzcv, FPSCR @ flags transfert (do not forget this instruction !!!)
blt 2f
@ difference is positive
vcmp.f32 s0,s4 @ difference > 360
vmrs APSR_nzcv, FPSCR @ flags transfert (do not forget this instruction !!!)
vsubgt.f32 s0,s4 @ yes -> difference - 360
vcmp.f32 s0,s3 @ compare difference and 180
vmrs APSR_nzcv, FPSCR @ flags transfert (do not forget this instruction !!!)
vsubgt.f32 s0,s4,s0 @ > 180 calculate 360 - difference
vneggt.f32 s0,s0 @ and negate
b 100f
2: @ différence is négative
vneg.f32 s2,s4 @ -360
vcmp.f32 s0,s2 @ compare différence et - 360
vmrs APSR_nzcv, FPSCR @ flags transfert (do not forget this instruction !!!)
vsubgt.f32 s0,s4 @ sub 360 to différence
vneg.f32 s3,s3 @ -180
vcmp.f32 s0,s3 @ compare difference and -180
vmrs APSR_nzcv, FPSCR @ flags transfert (do not forget this instruction !!!)
vaddlt.f32 s0,s4,s0 @ calculate 360 + différence
100:
vpop {s1-s4}
pop {r1-r4,pc} @ restaur registers
/******************************************************************/
/* Conversion Float */
/******************************************************************/
/* s0 contains Float */
/* r0 contains address conversion area mini 20 charactèrs*/
/* r0 return result length */
convertirFloat:
push {r1-r7,lr}
vpush {s0-s2}
mov r6,r0 @ save area address
vmov r0,s0
movs r7,#0 @ result length
movs r3,#'+'
strb r3,[r6] @ sign + forcing
mov r2,r0
lsls r2,#1 @ extraction bit 31
bcc 1f @ positive ?
lsrs r0,r2,#1 @ raz sign if negative
movs r3,#'-' @ sign -
strb r3,[r6]
1:
adds r7,#1 @ next position
cmp r0,#0 @ case of positive or negative 0
bne 2f
movs r3,#'0'
strb r3,[r6,r7] @ store character 0
adds r7,#1 @ next position
movs r3,#0
strb r3,[r6,r7] @ store 0 final
mov r0,r7 @ return length
b 100f @ and end
2:
ldr r2,iMaskExposant
mov r1,r0
ands r1,r2 @ exposant = 255 ?
cmp r1,r2
bne 4f
lsls r0,#10 @ bit 22 à 0 ?
bcc 3f @ yes
movs r2,#'N' @ case of Nan. store byte, if not possible store int
strb r2,[r6] @ area no aligned
movs r2,#'a'
strb r2,[r6,#1]
movs r2,#'n'
strb r2,[r6,#2]
movs r2,#0 @ 0 final
strb r2,[r6,#3]
movs r0,#3 @ return length 3
b 100f
3: @ case infini positive or négative
movs r2,#'I'
strb r2,[r6,r7]
adds r7,#1
movs r2,#'n'
strb r2,[r6,r7]
adds r7,#1
movs r2,#'f'
strb r2,[r6,r7]
adds r7,#1
movs r2,#0
strb r2,[r6,r7]
mov r0,r7
b 100f
4:
bl normaliserFloat
mov r5,r0 @ save exposant
VCVT.U32.f32 s2,s0 @ integer value of integer part
vmov r0,s2 @ integer part
VCVT.F32.U32 s1,s2 @ conversion float
vsub.f32 s1,s0,s1 @ extraction fract part
vldr s2,iConst1
vmul.f32 s1,s2,s1 @ to crop it in full
VCVT.U32.f32 s1,s1 @ integer conversion
vmov r4,s1 @ fract value
@ integer conversion in r0
mov r2,r6 @ save address area begin
adds r6,r7
mov r1,r6
bl conversion10
add r6,r0
movs r3,#','
strb r3,[r6]
adds r6,#1
mov r0,r4 @ conversion fractional part
mov r1,r6
bl conversion10SP @ spécial routine with conservation begin 0
add r6,r0
subs r6,#1
@ remove trailing zeros
5:
ldrb r0,[r6]
cmp r0,#'0'
bne 6f
subs r6,#1
b 5b
6:
cmp r0,#','
bne 7f
subs r6,#1
7:
adds r6,#1
movs r3,#'E'
strb r3,[r6]
adds r6,#1
mov r0,r5 @ conversion exposant
mov r3,r0
lsls r3,#1
bcc 4f
rsbs r0,r0,#0
movs r3,#'-'
strb r3,[r6]
adds r6,#1
4:
mov r1,r6
bl conversion10
add r6,r0
movs r3,#0
strb r3,[r6]
adds r6,#1
mov r0,r6
subs r0,r2 @ return length result
subs r0,#1 @ - 0 final
100:
vpop {s0-s2}
pop {r1-r7,pc}
iMaskExposant: .int 0xFF<<23
iConst1: .float 0f1E9
/***************************************************/
/* normaliser float */
/***************************************************/
/* r0 contain float value (always positive value and <> Nan) */
/* s0 return new value */
/* r0 return exposant */
normaliserFloat:
push {lr} @ save registre
vmov s0,r0 @ value float
movs r0,#0 @ exposant
vldr s1,iConstE7 @ no normalisation for value < 1E7
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 10f @ if s0 < iConstE7
vldr s1,iConstE32
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 1f
vldr s1,iConstE32
vdiv.f32 s0,s0,s1
adds r0,#32
1:
vldr s1,iConstE16
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 2f
vldr s1,iConstE16
vdiv.f32 s0,s0,s1
adds r0,#16
2:
vldr s1,iConstE8
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 3f
vldr s1,iConstE8
vdiv.f32 s0,s0,s1
adds r0,#8
3:
vldr s1,iConstE4
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 4f
vldr s1,iConstE4
vdiv.f32 s0,s0,s1
adds r0,#4
4:
vldr s1,iConstE2
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 5f
vldr s1,iConstE2
vdiv.f32 s0,s0,s1
adds r0,#2
5:
vldr s1,iConstE1
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 10f
vldr s1,iConstE1
vdiv.f32 s0,s0,s1
adds r0,#1
10:
vldr s1,iConstME5 @ pas de normalisation pour les valeurs > 1E-5
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 100f
vldr s1,iConstME31
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 11f
vldr s1,iConstE32
vmul.f32 s0,s0,s1
subs r0,#32
11:
vldr s1,iConstME15
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 12f
vldr s1,iConstE16
vmul.f32 s0,s0,s1
subs r0,#16
12:
vldr s1,iConstME7
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 13f
vldr s1,iConstE8
vmul.f32 s0,s0,s1
subs r0,#8
13:
vldr s1,iConstME3
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 14f
vldr s1,iConstE4
vmul.f32 s0,s0,s1
subs r0,#4
14:
vldr s1,iConstME1
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 15f
vldr s1,iConstE2
vmul.f32 s0,s0,s1
subs r0,#2
15:
vldr s1,iConstE0
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 100f
vldr s1,iConstE1
vmul.f32 s0,s0,s1
subs r0,#1
100: @ fin standard de la fonction
pop {pc} @ restaur des registres
.align 2
iConstE7: .float 0f1E7
iConstE32: .float 0f1E32
iConstE16: .float 0f1E16
iConstE8: .float 0f1E8
iConstE4: .float 0f1E4
iConstE2: .float 0f1E2
iConstE1: .float 0f1E1
iConstME5: .float 0f1E-5
iConstME31: .float 0f1E-31
iConstME15: .float 0f1E-15
iConstME7: .float 0f1E-7
iConstME3: .float 0f1E-3
iConstME1: .float 0f1E-1
iConstE0: .float 0f1E0
/******************************************************************/
/* Décimal Conversion */
/******************************************************************/
/* r0 contain value et r1 address conversion area */
conversion10SP:
push {r1-r6,lr} @ save registers
mov r5,r1
mov r4,#8
mov r2,r0
mov r1,#10 @ conversion decimale
1: @ begin loop
mov r0,r2 @ copy number or quotients
bl division @ r0 dividende r1 divisor r2 quotient r3 remainder
add r3,#48 @ compute digit
strb r3,[r5,r4] @ store byte area address (r5) + offset (r4)
subs r4,r4,#1 @ position précedente
bge 1b @ and loop if not < zero
mov r0,#8
mov r3,#0
strb r3,[r5,r0] @ store 0 final
100:
pop {r1-r6,pc} @ restaur registers
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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
| #C.2B.2B | C++ | #include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
bool is_deranged(const std::string& left, const std::string& right)
{
return (left.size() == right.size()) &&
(std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus<int>(), std::equal_to<char>()) == 0);
}
int main()
{
std::ifstream input("unixdict.txt");
if (!input) {
std::cerr << "can't open input file\n";
return EXIT_FAILURE;
}
typedef std::set<std::string> WordList;
typedef std::map<std::string, WordList> AnagraMap;
AnagraMap anagrams;
std::pair<std::string, std::string> result;
size_t longest = 0;
for (std::string value; input >> value; /**/) {
std::string key(value);
std::sort(key.begin(), key.end());
if (longest < value.length()) { // is it a long candidate?
if (0 < anagrams.count(key)) { // is it an anagram?
for (const auto& prior : anagrams[key]) {
if (is_deranged(prior, value)) { // are they deranged?
result = std::make_pair(prior, value);
longest = value.length();
}
}
}
}
anagrams[key].insert(value);
}
std::cout << result.first << ' ' << result.second << '\n';
return EXIT_SUCCESS;
} |
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.
| #Clojure | Clojure |
(defn fib [n]
(when (neg? n)
(throw (new IllegalArgumentException "n should be > 0")))
(loop [n n, v1 1, v2 1]
(if (< n 2)
v2
(recur (dec n) v2 (+ v1 v2)))))
|
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #C | C | #define PI 3.141592653589793
#define TWO_PI 6.283185307179586
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a += 6400;
while (a >= 6400) a -= 6400;
return a;
}
double normalize2rad(double a) {
while (a < 0) a += TWO_PI;
while (a >= TWO_PI) a -= TWO_PI;
return a;
}
double deg2grad(double a) {return a * 10 / 9;}
double deg2mil(double a) {return a * 160 / 9;}
double deg2rad(double a) {return a * PI / 180;}
double grad2deg(double a) {return a * 9 / 10;}
double grad2mil(double a) {return a * 16;}
double grad2rad(double a) {return a * PI / 200;}
double mil2deg(double a) {return a * 9 / 160;}
double mil2grad(double a) {return a / 16;}
double mil2rad(double a) {return a * PI / 3200;}
double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;} |
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.
| #AppleScript | AppleScript | -- AMICABLE PAIRS ------------------------------------------------------------
-- amicablePairsUpTo :: Int -> Int
on amicablePairsUpTo(max)
-- amicable :: [Int] -> Int -> Int -> [Int] -> [Int]
script amicable
on |λ|(a, m, n, lstSums)
if (m > n) and (m ≤ max) and ((item m of lstSums) = n) then
a & [[n, m]]
else
a
end if
end |λ|
end script
-- divisorsSummed :: Int -> Int
script divisorsSummed
-- sum :: Int -> Int -> Int
script sum
on |λ|(a, b)
a + b
end |λ|
end script
on |λ|(n)
foldl(sum, 0, properDivisors(n))
end |λ|
end script
foldl(amicable, {}, ¬
map(divisorsSummed, enumFromTo(1, max)))
end amicablePairsUpTo
-- TEST ----------------------------------------------------------------------
on run
amicablePairsUpTo(20000)
end run
-- PROPER DIVISORS -----------------------------------------------------------
-- properDivisors :: Int -> [Int]
on properDivisors(n)
-- isFactor :: Int -> Bool
script isFactor
on |λ|(x)
n mod x = 0
end |λ|
end script
-- integerQuotient :: Int -> Int
script integerQuotient
on |λ|(x)
(n / x) as integer
end |λ|
end script
if n = 1 then
{1}
else
set realRoot to n ^ (1 / 2)
set intRoot to realRoot as integer
set blnPerfectSquare to intRoot = realRoot
-- Factors up to square root of n,
set lows to filter(isFactor, enumFromTo(1, intRoot))
-- and quotients of these factors beyond the square root,
-- excluding n itself (last item)
items 1 thru -2 of (lows & map(integerQuotient, ¬
items (1 + (blnPerfectSquare as integer)) thru -1 of reverse of lows))
end if
end properDivisors
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #C.2B.2B | C++ | #include "animationwidget.h"
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
setWindowTitle(tr("Animation"));
QFont font("Courier", 24);
QLabel* label = new QLabel("Hello World! ");
label->setFont(font);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [label,this]() {
QString text = label->text();
std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
label->setText(text);
});
timer->start(200);
}
void AnimationWidget::mousePressEvent(QMouseEvent*) {
right_ = !right_;
} |
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
| #Arturo | Arturo | getDifference: function [b1, b2][
r: (b2 - b1) % 360.0
if r >= 180.0 ->
r: r - 360.0
return r
]
print "Input in -180 to +180 range"
print getDifference 20.0 45.0
print getDifference neg 45.0 45.0
print getDifference neg 85.0 90.0
print getDifference neg 95.0 90.0
print getDifference neg 45.0 125.0
print getDifference neg 45.0 145.0
print getDifference neg 45.0 125.0
print getDifference neg 45.0 145.0
print getDifference 29.4803 neg 88.6381
print getDifference neg 78.3251 neg 159.036
print ""
print "Input in wider range"
print getDifference neg 70099.74233810938 29840.67437876723
print getDifference neg 165313.6666297357 33693.9894517456
print getDifference 1174.8380510598456 neg 154146.66490124757
print 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
| #Clojure | Clojure | (->> (slurp "unixdict.txt") ; words
(re-seq #"\w+") ; |
(group-by sort) ; anagrams
vals ; |
(filter second) ; |
(remove #(some true? (apply map = %))) ; deranged
(sort-by #(count (first %)))
last
prn) |
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.
| #CoffeeScript | CoffeeScript | # This is a rather obscure technique to have an anonymous
# function call itself.
fibonacci = (n) ->
throw "Argument cannot be negative" if n < 0
do (n) ->
return n if n <= 1
arguments.callee(n-2) + arguments.callee(n-1)
# Since it's pretty lightweight to assign an anonymous
# function to a local variable, the idiom below might be
# more preferred.
fibonacci2 = (n) ->
throw "Argument cannot be negative" if n < 0
recurse = (n) ->
return n if n <= 1
recurse(n-2) + recurse(n-1)
recurse(n)
|
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #C.23 | C# | using System;
public static class Angles
{
public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);
public static void Print(params double[] angles) {
string[] names = { "Degrees", "Gradians", "Mils", "Radians" };
Func<double, double> rnd = a => Math.Round(a, 4);
Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };
Func<double, double>[,] convert = {
{ a => a, DegToGrad, DegToMil, DegToRad },
{ GradToDeg, a => a, GradToMil, GradToRad },
{ MilToDeg, MilToGrad, a => a, MilToRad },
{ RadToDeg, RadToGrad, RadToMil, a => a }
};
Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{
"Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}");
foreach (double angle in angles) {
for (int i = 0; i < 4; i++) {
double nAngle = normal[i](angle);
Console.WriteLine($@"{
rnd(angle),-12}{
rnd(nAngle),-12}{
names[i],-12}{
rnd(convert[i, 0](nAngle)),-12}{
rnd(convert[i, 1](nAngle)),-12}{
rnd(convert[i, 2](nAngle)),-12}{
rnd(convert[i, 3](nAngle)),-12}");
}
}
}
public static double NormalizeDeg(double angle) => Normalize(angle, 360);
public static double NormalizeGrad(double angle) => Normalize(angle, 400);
public static double NormalizeMil(double angle) => Normalize(angle, 6400);
public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);
private static double Normalize(double angle, double N) {
while (angle <= -N) angle += N;
while (angle >= N) angle -= N;
return angle;
}
public static double DegToGrad(double angle) => angle * 10 / 9;
public static double DegToMil(double angle) => angle * 160 / 9;
public static double DegToRad(double angle) => angle * Math.PI / 180;
public static double GradToDeg(double angle) => angle * 9 / 10;
public static double GradToMil(double angle) => angle * 16;
public static double GradToRad(double angle) => angle * Math.PI / 200;
public static double MilToDeg(double angle) => angle * 9 / 160;
public static double MilToGrad(double angle) => angle / 16;
public static double MilToRad(double angle) => angle * Math.PI / 3200;
public static double RadToDeg(double angle) => angle * 180 / Math.PI;
public static double RadToGrad(double angle) => angle * 200 / Math.PI;
public static double RadToMil(double angle) => angle * 3200 / Math.PI;
} |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program amicable.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 NMAXI, 20000
.equ TABMAXI, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ : @\n"
szCarriageReturn: .asciz "\n"
szMessErr1: .asciz "Array too small !!"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tResult: .skip 4 * TABMAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r3,iNMaxi @ load limit
mov r4,#2 @ number begin
1:
mov r0,r4 @ number
bl decFactor @ compute sum factors
cmp r0,r4 @ equal ?
beq 2f
mov r2,r0 @ factor sum 1
bl decFactor
cmp r0,r4 @ equal number ?
bne 2f
mov r0,r4 @ yes -> search in array
mov r1,r2 @ and store sum
bl searchRes
cmp r0,#0 @ find ?
bne 2f @ yes
mov r0,r4 @ no -> display number ans sum
mov r1,r2
bl displayResult
2:
add r4,#1 @ increment number
cmp r4,r3 @ end ?
ble 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iNMaxi: .int NMAXI
/***************************************************/
/* display message number */
/***************************************************/
/* r0 contains number 1 */
/* r1 contains number 2 */
displayResult:
push {r1-r3,lr} @ save registers
mov r2,r1
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r3,r0
mov r0,r2
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r0,r3
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
pop {r1-r3,pc} @ restaur des registres
iAdrsMessResult: .int sMessResult
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* compute factors sum */
/***************************************************/
/* r0 contains the number */
decFactor:
push {r1-r5,lr} @ save registers
mov r5,#1 @ init sum
mov r4,r0 @ save number
mov r1,#2 @ start factor -> divisor
1:
mov r0,r4 @ dividende
bl division
cmp r1,r2 @ divisor > quotient ?
bgt 3f
cmp r3,#0 @ remainder = 0 ?
bne 2f
add r5,r5,r1 @ add divisor to sum
cmp r1,r2 @ divisor = quotient ?
beq 3f @ yes -> end
add r5,r5,r2 @ no -> add quotient to sum
2:
add r1,r1,#1 @ increment factor
b 1b @ and loop
3:
mov r0,r5 @ return sum
pop {r1-r5,pc} @ restaur registers
/***************************************************/
/* search and store result in array */
/***************************************************/
/* r0 contains the number */
/* r1 contains factors sum */
/* r0 return 1 if find 0 else -1 if error */
searchRes:
push {r1-r4,lr} @ save registers
ldr r4,iAdrtResult @ array address
mov r2,#0 @ indice begin
1:
ldr r3,[r4,r2,lsl #2] @ load one result array
cmp r3,#0 @ if 0 store new result
beq 2f
cmp r3,r0 @ equal ?
moveq r0,#1 @ find -> return 1
beq 100f
add r2,r2,#1 @ increment indice
cmp r2,#TABMAXI @ maxi array ?
blt 1b
ldr r0,iAdrszMessErr1 @ error
bl affichageMess
mov r0,#-1
b 100f
2:
str r1,[r4,r2,lsl #2]
mov r0,#0 @ not find -> store and retun 0
100:
pop {r1-r4,pc} @ restaur registers
iAdrtResult: .int tResult
iAdrszMessErr1: .int szMessErr1
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Ceylon | Ceylon | native("jvm")
module animation "1.0.0" {
import java.desktop "8";
}
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Clojure | Clojure | (import '[javax.swing JFrame JLabel])
(import '[java.awt.event MouseAdapter])
(def text "Hello World! ")
(def text-ct (count text))
(def rotations
(vec
(take text-ct
(map #(apply str %)
(partition text-ct 1 (cycle text))))))
(def pos (atom 0)) ;position in rotations vector being displayed
(def dir (atom 1)) ;direction of next position (-1 or 1)
(def label (JLabel. text))
(.addMouseListener label
(proxy [MouseAdapter] []
(mouseClicked [evt] (swap! dir -))))
(defn animator []
(while true
(Thread/sleep 100)
(swap! pos #(-> % (+ @dir) (mod text-ct)))
(.setText label (rotations @pos))))
(doto (JFrame.)
(.add label)
(.pack)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))
(future-call animator) ;simple way to run animator on a separate thread |
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
| #AutoHotkey | AutoHotkey | Angles:= [[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 i, set in angles
result .= set.2 " to " set.1 " = " Angle_difference_between_two_bearings(set) "`n"
MsgBox, 262144, , % result
return
Angle_difference_between_two_bearings(set){
return (diff := Mod(set.2, 360) - Mod(set.1, 360)) >180 ? diff-360 : diff
} |
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
| #COBOL | COBOL |
******************************************************************
* COBOL solution to Anagrams Deranged challange
* The program was run on OpenCobolIDE
* Input data is stored in file 'Anagrams.txt' on my PC
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. DERANGED.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO 'C:\Both\Rosetta\Anagrams.txt'
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-RECORD PIC X(22).
WORKING-STORAGE SECTION.
01 SWITCHES.
05 WS-EOF PIC X VALUE 'N'.
05 WS-FND PIC X VALUE 'N'.
05 WS-EXIT PIC X VALUE 'N'.
01 COUNTERS.
05 WS-TOT-RECS PIC 9(5) COMP-3 VALUE 0.
05 WS-SEL-RECS PIC 9(5) COMP-3 VALUE 0.
05 WT-REC-NBR PIC 9(5) COMP-3 VALUE 0.
* Extra byte to guarentee a space at end - needed in sort logic.
01 WS-WORD-TEMP PIC X(23).
01 FILLER REDEFINES WS-WORD-TEMP.
05 WS-LETTER OCCURS 23 TIMES PIC X.
77 WS-LETTER-HLD PIC X.
77 WS-WORD-IN PIC X(22).
77 WS-WORD-KEY PIC X(22).
01 WS-WORD-TABLE.
05 WT-RECORD OCCURS 0 to 24000 TIMES
DEPENDING ON WT-REC-NBR
DESCENDING KEY IS WT-WORD-LEN
INDEXED BY WT-IDX.
10 WT-WORD-KEY PIC X(22).
10 WT-WORD-LEN PIC 9(2).
10 WT-ANAGRAM-CNT PIC 9(5) COMP-3.
10 WT-ANAGRAMS OCCURS 6 TIMES.
15 WT-ANAGRAM PIC X(22).
01 WS-WORD-TEMP1 PIC X(22).
01 FILLER REDEFINES WS-WORD-TEMP1.
05 WS-LETTER1 OCCURS 22 TIMES PIC X.
01 WS-WORD-TEMP2 PIC X(22).
01 FILLER REDEFINES WS-WORD-TEMP2.
05 WS-LETTER2 OCCURS 22 TIMES PIC X.
77 WS-I PIC 99999 COMP-3.
77 WS-J PIC 99999 COMP-3.
77 WS-K PIC 99999 COMP-3.
77 WS-L PIC 99999 COMP-3.
77 WS-BEG PIC 99999 COMP-3.
77 WS-MAX PIC 99999 COMP-3.
PROCEDURE DIVISION.
000-MAIN.
PERFORM 100-INITIALIZE.
PERFORM 200-PROCESS-RECORD
UNTIL WS-EOF = 'Y'.
SORT WT-RECORD ON DESCENDING KEY WT-WORD-LEN.
PERFORM 500-FIND-DERANGED.
PERFORM 900-TERMINATE.
STOP RUN.
100-INITIALIZE.
OPEN INPUT IN-FILE.
PERFORM 150-READ-RECORD.
150-READ-RECORD.
READ IN-FILE INTO WS-WORD-IN
AT END
MOVE 'Y' TO WS-EOF
NOT AT END
COMPUTE WS-TOT-RECS = WS-TOT-RECS + 1
END-READ.
200-PROCESS-RECORD.
IF WS-WORD-IN IS ALPHABETIC
COMPUTE WS-SEL-RECS = WS-SEL-RECS + 1
MOVE WS-WORD-IN TO WS-WORD-TEMP
PERFORM 300-SORT-WORD
MOVE WS-WORD-TEMP TO WS-WORD-KEY
PERFORM 400-ADD-TO-TABLE
END-IF.
PERFORM 150-READ-RECORD.
* bubble sort:
300-SORT-WORD.
PERFORM VARYING WS-MAX FROM 1 BY 1
UNTIL WS-LETTER(WS-MAX) = SPACE
END-PERFORM.
PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I = WS-MAX
PERFORM VARYING WS-J FROM WS-I BY 1
UNTIL WS-J > WS-MAX - 1
IF WS-LETTER(WS-J) < WS-LETTER(WS-I) THEN
MOVE WS-LETTER(WS-I) TO WS-LETTER-HLD
MOVE WS-LETTER(WS-J) TO WS-LETTER(WS-I)
MOVE WS-LETTER-HLD TO WS-LETTER(WS-J)
END-IF
END-PERFORM
END-PERFORM.
400-ADD-TO-TABLE.
SET WT-IDX TO 1.
SEARCH WT-RECORD
AT END
PERFORM 420-ADD-RECORD
WHEN WT-WORD-KEY(WT-IDX) = WS-WORD-KEY
PERFORM 440-UPDATE-RECORD
END-SEARCH.
420-ADD-RECORD.
ADD 1 To WT-REC-NBR.
MOVE WS-WORD-KEY TO WT-WORD-KEY(WT-REC-NBR).
COMPUTE WT-WORD-LEN(WT-REC-NBR) = WS-MAX - 1.
MOVE 1 TO WT-ANAGRAM-CNT(WT-REC-NBR).
MOVE WS-WORD-IN TO
WT-ANAGRAM(WT-REC-NBR, WT-ANAGRAM-CNT(WT-REC-NBR)).
440-UPDATE-RECORD.
ADD 1 TO WT-ANAGRAM-CNT(WT-IDX).
MOVE WS-WORD-IN TO
WT-ANAGRAM(WT-IDX, WT-ANAGRAM-CNT(WT-IDX)).
500-FIND-DERANGED.
PERFORM VARYING WS-I FROM 1 BY 1
UNTIL WS-I > WT-REC-NBR OR WS-FND = 'Y'
PERFORM VARYING WS-J FROM 1 BY 1
UNTIL WS-J > WT-ANAGRAM-CNT(WS-I) - 1 OR WS-FND = 'Y'
COMPUTE WS-BEG = WS-J + 1
PERFORM VARYING WS-K FROM WS-BEG BY 1
UNTIL WS-K > WT-ANAGRAM-CNT(WS-I) OR WS-FND = 'Y'
MOVE WT-ANAGRAM(WS-I, WS-J) TO WS-WORD-TEMP1
MOVE WT-ANAGRAM(WS-I, WS-K) To WS-WORD-TEMP2
PERFORM 650-CHECK-DERANGED
END-PERFORM
END-PERFORM
END-PERFORM.
650-CHECK-DERANGED.
MOVE 'N' TO WS-EXIT.
PERFORM VARYING WS-L FROM 1 BY 1
UNTIL WS-L > WT-WORD-LEN(WS-I) OR WS-EXIT = 'Y'
IF WS-LETTER1(WS-L) = WS-LETTER2(WS-L)
MOVE 'Y' TO WS-EXIT
END-PERFORM.
IF WS-EXIT = 'N'
DISPLAY WS-WORD-TEMP1(1:WT-WORD-LEN(WS-I))
' '
WS-WORD-TEMP2
MOVE 'Y' TO WS-FND
END-IF.
900-TERMINATE.
DISPLAY 'RECORDS READ: ' WS-TOT-RECS.
DISPLAY 'RECORDS SELECTED ' WS-SEL-RECS.
DISPLAY 'RECORD KEYS: ' WT-REC-NBR.
CLOSE IN-FILE.
*> OUTPUT:
*> excitation intoxicate
*> RECORDS READ: 25104
*> RECORDS SELECTED 24978
*> RECORD KEYS: 23441
*> BUBBLE SORT REFERENCE:
*> https://mainframegeek.wordpress.com/tag/bubble-sort-in-cobol
|
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.
| #Common_Lisp | Common Lisp | (defmacro alambda (parms &body body)
`(labels ((self ,parms ,@body))
#'self)) |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #C.2B.2B | C++ | #include <functional>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
template<typename T>
T normalize(T a, double b) { return std::fmod(a, b); }
inline double d2d(double a) { return normalize<double>(a, 360); }
inline double g2g(double a) { return normalize<double>(a, 400); }
inline double m2m(double a) { return normalize<double>(a, 6400); }
inline double r2r(double a) { return normalize<double>(a, 2*M_PI); }
double d2g(double a) { return g2g(a * 10 / 9); }
double d2m(double a) { return m2m(a * 160 / 9); }
double d2r(double a) { return r2r(a * M_PI / 180); }
double g2d(double a) { return d2d(a * 9 / 10); }
double g2m(double a) { return m2m(a * 16); }
double g2r(double a) { return r2r(a * M_PI / 200); }
double m2d(double a) { return d2d(a * 9 / 160); }
double m2g(double a) { return g2g(a / 16); }
double m2r(double a) { return r2r(a * M_PI / 3200); }
double r2d(double a) { return d2d(a * 180 / M_PI); }
double r2g(double a) { return g2g(a * 200 / M_PI); }
double r2m(double a) { return m2m(a * 3200 / M_PI); }
void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {
using namespace std;
ostringstream out;
out << " ┌───────────────────┐\n";
out << " │ " << setw(17) << s << " │\n";
out << "┌─────────────────┼───────────────────┤\n";
for (double i : values)
out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n";
out << "└─────────────────┴───────────────────┘\n";
auto str = out.str();
boost::algorithm::replace_all(str, ".000000", " ");
cout << str;
}
int main() {
std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };
print(values, "normalized (deg)", d2d);
print(values, "normalized (grad)", g2g);
print(values, "normalized (mil)", m2m);
print(values, "normalized (rad)", r2r);
print(values, "deg -> grad ", d2g);
print(values, "deg -> mil ", d2m);
print(values, "deg -> rad ", d2r);
print(values, "grad -> deg ", g2d);
print(values, "grad -> mil ", g2m);
print(values, "grad -> rad ", g2r);
print(values, "mil -> deg ", m2d);
print(values, "mil -> grad ", m2g);
print(values, "mil -> rad ", m2r);
print(values, "rad -> deg ", r2d);
print(values, "rad -> grad ", r2g);
print(values, "rad -> mil ", r2m);
return 0;
} |
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.
| #Arturo | Arturo | properDivs: function [x] ->
(factors x) -- x
amicable: function [x][
y: sum properDivs x
if and? x = sum properDivs y
x <> y
-> return @[x,y]
return ø
]
amicables: []
loop 1..20000 'n [
am: amicable n
if am <> ø
-> 'amicables ++ @[sort am]
]
print unique amicables |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Commodore_BASIC | Commodore BASIC |
1 rem rosetta code
2 rem task: animation
10 t$="hello world! ":d=-1
20 print chr$(147);:rem clear screen
30 print "*****************"
35 print "* *"
40 print "* *"
45 print "* *"
50 print "*****************"
60 print "{HOME}{DOWN}{DOWN}{RIGHT}{RIGHT}"t$
70 get k$
75 if k$=" " then d=not d
80 on (abs(d))+1 gosub 1000,1010
90 if k$="q" then print chr$(147):end
95 rem
100 rem between line 80 and line 999
110 rem check for other user input
120 rem and process accordingly
130 rem
999 for i=1 to 100:next:goto 60
1000 t$=right$(t$,len(t$)-1)+left$(t$,1):return
1010 t$=right$(t$,1)+left$(t$,len(t$)-1):return
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Common_Lisp | Common Lisp | (use-package :ltk)
(defparameter *message* "Hello World! ")
(defparameter *direction* :left)
(defun animate (label)
(let* ((n (length *message*))
(i (if (eq *direction* :left) 0 (1- n)))
(c (char *message* i)))
(if (eq *direction* :left)
(setq *message* (concatenate 'string
(subseq *message* 1 n)
(list c)))
(setq *message* (concatenate 'string (list c)
(subseq *message* 0 (1- n)))))
(setf (ltk:text label) *message*)
(ltk:after 125 (lambda () (animate label)))))
(defun basic-animation ()
(ltk:with-ltk ()
(let* ((label (make-instance 'label
:font "Courier 14")))
(setf (text label) *message*)
(ltk:bind label "<Button-1>"
(lambda (event)
(declare (ignore event))
(cond
((eq *direction* :left) (setq *direction* :right))
((eq *direction* :right) (setq *direction* :left)))))
(ltk:pack label)
(animate label)
(ltk:mainloop))))
(basic-animation) |
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
| #AWK | AWK |
# syntax: GAWK -f ANGLE_DIFFERENCE_BETWEEN_TWO_BEARINGS.AWK
BEGIN {
fmt = "%11s %11s %11s\n"
while (++i <= 11) { u = u "-" }
printf(fmt,"B1","B2","DIFFERENCE")
printf(fmt,u,u,u)
main(20,45)
main(-45,45)
main(-85,90)
main(-95,90)
main(-45,125)
main(-45,145)
main(29.4803,-88.6381)
main(-78.3251,-159.036)
main(-70099.74233810938,29840.67437876723)
main(-165313.6666297357,33693.9894517456)
main(1174.8380510598456,-154146.66490124757)
main(60175.77306795546,42213.07192354373)
exit(0)
}
function main(b1,b2) {
printf("%11.2f %11.2f %11.2f\n",b1,b2,angle_difference(b1,b2))
}
function angle_difference(b1,b2, r) {
r = (b2 - b1) % 360
if (r < -180) {
r += 360
}
if (r >= 180) {
r -= 360
}
return(r)
}
|
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
| #CoffeeScript | CoffeeScript | http = require 'http'
is_derangement = (word1, word2) ->
for c, i in word1
return false if c == word2[i]
true
show_longest_derangement = (word_lst) ->
anagrams = {}
max_len = 0
for word in word_lst
continue if word.length < max_len
key = word.split('').sort().join('')
if anagrams[key]
for prior in anagrams[key]
if is_derangement(prior, word)
max_len = word.length
result = [prior, word]
else
anagrams[key] = []
anagrams[key].push word
console.log "Longest derangement: #{result.join ' '}"
get_word_list = (process) ->
options =
host: "www.puzzlers.org"
path: "/pub/wordlists/unixdict.txt"
req = http.request options, (res) ->
s = ''
res.on 'data', (chunk) ->
s += chunk
res.on 'end', ->
process s.split '\n'
req.end()
get_word_list show_longest_derangement |
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.
| #D | D | int fib(in uint arg) pure nothrow @safe @nogc {
assert(arg >= 0);
return function uint(in uint n) pure nothrow @safe @nogc {
static immutable self = &__traits(parent, {});
return (n < 2) ? n : self(n - 1) + self(n - 2);
}(arg);
}
void main() {
import std.stdio;
39.fib.writeln;
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Common_Lisp | Common Lisp | (defun DegToDeg (a) (rem a 360))
(defun GradToGrad (a) (rem a 400))
(defun MilToMil (a) (rem a 6400))
(defun RadToRad (a) (rem a (* 2 pi)))
(defun DegToGrad (a) (GradToGrad (* (/ a 360) 400)))
(defun DegToRad (a) (RadToRad (* (/ a 360) (* 2 pi))))
(defun DegToMil (a) (MilToMil (* (/ a 360) 6400)))
(defun GradToDeg (a) (DegToDeg (* (/ a 400) 360)))
(defun GradToRad (a) (RadToRad (* (/ a 400) (* 2 pi))))
(defun GradToMil (a) (MilToMil (* (/ a 400) 6400)))
(defun MilToDeg (a) (DegToDeg (* (/ a 6400) 360)))
(defun MilToGrad (a) (GradToGrad (* (/ a 6400) 400)))
(defun MilToRad (a) (RadToRad (* (/ a 6400) (* 2 pi))))
(defun RadToDeg (a) (DegToDeg (* (/ a (* 2 pi)) 360)))
(defun RadToGrad (a) (GradToGrad (* (/ a (* 2 pi)) 400)))
(defun RadToMil (a) (MilToMil (* (/ a (* 2 pi)) 6400)))
(defun angles (&rest angles)
(if (not angles) (setf angles '(-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000)))
(dolist (a angles)
(format t "UNIT ~15@a ~15@a ~15@a ~15@a ~15@a~%" "VAL*" "DEG" "GRAD" "MIL" "RAD")
(format t "Deg | ~15f | ~15f | ~15f | ~15f | ~15f~%" a (DegToDeg a) (DegToGrad a) (DegToMil a) (DegToRad a))
(format t "Grad | ~15f | ~15f | ~15f | ~15f | ~15f~%" a (GradToDeg a) (GradToGrad a) (GradToMil a) (GradToRad a))
(format t "Mil | ~15f | ~15f | ~15f | ~15f | ~15f~%" a (MilToDeg a) (MilToGrad a) (MilToMil a) (MilToRad a))
(format t "Rad | ~15f | ~15f | ~15f | ~15f | ~15f~%~%" a (RadToDeg a) (RadToGrad a) (RadToMil a) (RadToRad a)))) |
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.
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
fun
sum_list_vt
(xs: List_vt(int)): int =
(
case+ xs of
| ~list_vt_nil() => 0
| ~list_vt_cons(x, xs) => x + sum_list_vt(xs)
)
//
(* ****** ****** *)
fun
propDivs
(
x0: int
) : List0_vt(int) =
loop(x0, 2, list_vt_sing(1)) where
{
//
fun
loop
(
x0: int, i: int, res: List0_vt(int)
) : List0_vt(int) =
(
if
(i * i) > x0
then list_vt_reverse(res)
else
(
if x0 % i != 0
then
loop(x0, i+1, res)
// end of [then]
else let
val res =
cons_vt(i, res)
// end of [val]
val res =
(
if i * i = x0 then res else cons_vt(x0 / i, res)
) : List0_vt(int) // end of [val]
in
loop(x0, i+1, res)
end // end of [else]
// end of [if]
)
) (* end of [loop] *)
//
} // end of [propDivs]
(* ****** ****** *)
fun
sum_propDivs(x: int): int = sum_list_vt(propDivs(x))
(* ****** ****** *)
val
theNat2 = auxmain(2) where
{
fun
auxmain
(
n: int
) : stream_vt(int) = $ldelay(stream_vt_cons(n, auxmain(n+1)))
}
(* ****** ****** *)
//
val
theAmicable =
(
stream_vt_takeLte(theNat2, 20000)
).filter()
(
lam x =>
let
val x2 = sum_propDivs(x)
in x < x2 && x = sum_propDivs(x2) end
)
//
(* ****** ****** *)
val () =
theAmicable.foreach()
(
lam x => println! ("(", x, ", ", sum_propDivs(x), ")")
)
(* ****** ****** *)
implement main0 () = ()
(* ****** ****** *)
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #D | D | module test26;
import qd, SDL_ttf, tools.time;
void main() {
screen(320, 200);
auto last = sec();
string text = "Hello World! ";
auto speed = 0.2;
int dir = true;
while (true) {
cls;
print(10, 10, Bottom|Right, text);
if (sec() - last > speed) {
last = sec();
if (dir == 0) text = text[$-1] ~ text[0 .. $-1];
else text = text[1 .. $] ~ text[0];
}
flip; events;
if (mouse.clicked
&& mouse.pos in display.select(10, 10, 100, 20)
) dir = !dir;
}
} |
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.
| #Ada | Ada | generic
type Float_Type is digits <>;
Gravitation : Float_Type;
package Pendulums is
type Pendulum is private;
function New_Pendulum (Length : Float_Type;
Theta0 : Float_Type) return Pendulum;
function Get_X (From : Pendulum) return Float_Type;
function Get_Y (From : Pendulum) return Float_Type;
procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration);
private
type Pendulum is record
Length : Float_Type;
Theta : Float_Type;
X : Float_Type;
Y : Float_Type;
Velocity : Float_Type;
end record;
end Pendulums; |
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
| #BASIC | BASIC | SUB getDifference (b1!, b2!)
r! = (b2 - b1) MOD 360!
IF r >= 180! THEN r = r - 360!
PRINT USING "#######.###### #######.###### #######.######"; b1; b2; r
END SUB
PRINT " Bearing 1 Bearing 2 Difference"
CALL getDifference(20!, 45!)
CALL getDifference(-45!, 45!)
CALL getDifference(-85!, 90!)
CALL getDifference(-95!, 90!)
CALL getDifference(-45!, 125!)
CALL getDifference(-45!, 145!)
CALL getDifference(-45!, 125!)
CALL getDifference(-45!, 145!)
CALL getDifference(29.4803, -88.6381)
CALL getDifference(-78.3251, -159.036)
CALL getDifference(-70099.74233810938#, 29840.67437876723#)
CALL getDifference(-165313.6666297357#, 33693.9894517456#)
CALL getDifference(1174.838051059846#, -154146.6649012476#) |
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
| #Common_Lisp | Common Lisp | (defun read-words (file)
(with-open-file (stream file)
(loop with w = "" while w collect (setf w (read-line stream nil)))))
(defun deranged (a b)
(loop for ac across a for bc across b always (char/= ac bc)))
(defun longest-deranged (file)
(let ((h (make-hash-table :test #'equal))
(wordlist (sort (read-words file)
#'(lambda (x y) (> (length x) (length y))))))
(loop for w in wordlist do
(let* ((ws (sort (copy-seq w) #'char<))
(l (gethash ws h)))
(loop for w1 in l do
(if (deranged w w1)
(return-from longest-deranged (list w w1))))
(setf (gethash ws h) (cons w l))))))
(format t "~{~A~%~^~}" (longest-deranged "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.
| #Dylan | Dylan |
define function fib (n)
when (n < 0)
error("Can't take fibonacci of negative integer: %d\n", n)
end;
local method fib1 (n, a, b)
if (n = 0)
a
else
fib1(n - 1, b, a + b)
end
end;
fib1(n, 0, 1)
end
|
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Delphi | Delphi |
program normalization_and_conversion;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
function d2d(d: double): double;
begin
result := FMod(d, 360);
end;
function g2g(g: double): double;
begin
result := FMod(g, 400);
end;
function m2m(m: double): double;
begin
result := FMod(m, 6400);
end;
function r2r(r: double): double;
begin
result := FMod(r, 2 * Pi);
end;
function d2g(d: double): double;
begin
result := d2d(d) * 400 / 360;
end;
function d2m(d: double): double;
begin
result := d2d(d) * 6400 / 360;
end;
function d2r(d: double): double;
begin
result := d2d(d) * Pi / 180;
end;
function g2d(g: double): double;
begin
result := g2g(g) * 360 / 400;
end;
function g2m(g: double): double;
begin
result := g2g(g) * 6400 / 400;
end;
function g2r(g: double): double;
begin
result := g2g(g) * Pi / 200;
end;
function m2d(m: double): double;
begin
result := m2m(m) * 360 / 6400;
end;
function m2g(m: double): double;
begin
result := m2m(m) * 400 / 6400;
end;
function m2r(m: double): double;
begin
result := m2m(m) * Pi / 3200;
end;
function r2d(r: double): double;
begin
result := r2r(r) * 180 / Pi;
end;
function r2g(r: double): double;
begin
result := r2r(r) * 200 / Pi;
end;
function r2m(r: double): double;
begin
result := r2r(r) * 3200 / Pi;
end;
function s(f: double): string;
begin
var wf := FloatToStrF(f, ffGeneral, 16, 64).Split([FormatSettings.DecimalSeparator], TStringSplitOptions.ExcludeEmpty);
if Length(wf) = 1 then
exit(format('%7s ', [wf[0]]));
var le := length(wf[1]);
if le > 7 then
le := 7;
Result := format('%7s.%-7s', [wf[0], copy(wf[1], 0, le)]);
end;
begin
var angles: TArray<Double> := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359,
399, 6399, 1000000];
var ft := '%s %s %s %s %s';
writeln(format(ft, [' degrees ', 'normalized degs', ' gradians ',
' mils ', ' radians']));
for var a in angles do
writeln(format(ft, [s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))]));
writeln(format(ft, [#10' gradians ', 'normalized grds', ' degrees ',
' mils ', ' radians']));
for var a in angles do
writeln(format(ft, [s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))]));
writeln(format(ft, [#10' mils ', 'normalized mils', ' degrees ',
' gradians ', ' radians']));
for var a in angles do
writeln(format(ft, [s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))]));
writeln(format(ft, [#10' radians ', 'normalized rads', ' degrees ',
' gradians ', ' mils ']));
for var a in angles do
writeln(format(ft, [s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))]));
readln;
end. |
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.
| #AutoHotkey | AutoHotkey | SetBatchLines -1
Loop, 20000
{
m := A_index
; Getting factors
loop % floor(sqrt(m))
{
if ( mod(m, A_index) = 0 )
{
if ( A_index ** 2 == m )
{
sum += A_index
continue
} else if ( A_index != 1 )
{
sum += A_index + m//A_index
} else if ( A_index = 1 )
{
sum += A_index
}
}
} ; Factors obtained
; Checking factors of sum
if ( sum > 1 )
{
loop % floor(sqrt(sum))
{
if ( mod(sum, A_index) = 0 )
{
if ( A_index ** 2 == sum )
{
sum2 += A_index
continue
} else if ( A_index != 1 )
{
sum2 += A_index + sum//A_index
} else if ( A_index = 1 )
{
sum2 += A_index
}
}
}
if ( m = sum2 ) && ( m != sum ) && ( m < sum )
final .= m . ":" . sum . "`n"
} ; Checked
sum := 0
sum2 := 0
}
MsgBox % final
ExitApp |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.