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/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Crystal | Crystal | def digital_root(n : Int, base = 10) : Int
max_single_digit = base - 1
n = n.abs
if n > max_single_digit
n = 1 + (n - 1) % max_single_digit
end
n
end
puts digital_root 627615
puts digital_root 39390
puts digital_root 588225
puts digital_root 7, base: 3 |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
ClearAll[mdr, mp, nums];
mdr[n_] := NestWhile[Times @@ IntegerDigits[#] &, n, # > 9 &];
mp[n_] := Length@NestWhileList[Times @@ IntegerDigits[#] &, n, # > 9 &] - 1;
TableForm[{#, mdr[#], mp[#]} & /@ {123321, 7739, 893, 899998},
TableHeadings -> {None, {"Number", "MDR", "MP"}}]
nums = ConstantArray[{}, 10];
For[i = 0, Min[Length /@ nums] < 5, i++, AppendTo[nums[[mdr[i] + 1]], i]];
TableForm[Table[{i, Take[nums[[i + 1]], 5]}, {i, 0, 9}],
TableHeadings -> {None, {"MDR", "First 5"}}, TableDepth -> 2]
|
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #Haskell | Haskell | import Data.List (permutations)
import Control.Monad (guard)
dinesman :: [(Int,Int,Int,Int,Int)]
dinesman = do
-- baker, cooper, fletcher, miller, smith are integers representing
-- the floor that each person lives on, from 1 to 5
-- Baker, Cooper, Fletcher, Miller, and Smith live on different floors
-- of an apartment house that contains only five floors.
[baker, cooper, fletcher, miller, smith] <- permutations [1..5]
-- Baker does not live on the top floor.
guard $ baker /= 5
-- Cooper does not live on the bottom floor.
guard $ cooper /= 1
-- Fletcher does not live on either the top or the bottom floor.
guard $ fletcher /= 5 && fletcher /= 1
-- Miller lives on a higher floor than does Cooper.
guard $ miller > cooper
-- Smith does not live on a floor adjacent to Fletcher's.
guard $ abs (smith - fletcher) /= 1
-- Fletcher does not live on a floor adjacent to Cooper's.
guard $ abs (fletcher - cooper) /= 1
-- Where does everyone live?
return (baker, cooper, fletcher, miller, smith)
main :: IO ()
main = do
print $ head dinesman -- print first solution: (3,2,4,5,1)
print dinesman -- print all solutions (only one): [(3,2,4,5,1)] |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Elixir | Elixir | defmodule Vector do
def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0)
def dot_product(_,_) do
raise ArgumentError, message: "Vectors must have the same length."
end
defp dot_product([],[],product), do: product
defp dot_product([h1|t1], [h2|t2], product), do: dot_product(t1, t2, product+h1*h2)
end
IO.puts Vector.dot_product([1,3,-5],[4,-2,-1]) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Elm | Elm | dotp: List number -> List number -> Maybe number
dotp a b =
if List.length a /= List.length b then
Nothing
else
Just (List.sum <| List.map2 (*) a b)
dotp [1,3,-5] [4,-2,-1]) |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | 10 DEFINT A-Z
20 READ N: DIM S$(N): FOR I=1 TO N: READ S$(I): NEXT
30 READ S,C$: IF S=0 THEN END
40 PRINT "Character: '";C$;"'"
50 O$=S$(S): GOSUB 200
60 I$=S$(S): GOSUB 100: GOSUB 200
70 PRINT
80 GOTO 30
100 REM --
101 REM -- Squeeze I$ on character C$, output in O$
102 REM --
105 O$ = ""
110 X = INSTR(I$,C$)
120 IF X = 0 THEN O$ = O$ + I$: RETURN
130 O$ = O$ + LEFT$(I$,X)
140 FOR X=X TO LEN(I$): IF MID$(I$,X,1) = C$ THEN NEXT
150 I$ = RIGHT$(I$,LEN(I$)-X+1)
160 GOTO 110
200 REM --
201 REM -- Display O$ and its length in brackets
202 REM --
210 PRINT USING "##";LEN(O$);
220 PRINT "<<<";O$;">>>"
230 RETURN
400 REM -- Strings
410 DATA 5
415 DATA""
420 DATA"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
430 DATA"..1111111111111111111111111111111111111111111111111111111111111117777888"
440 DATA"I never give 'em hell, I just tell the truth, and they think it's hell. "
450 DATA" --- Harry S Truman "
500 REM -- String index and character to squeeze
510 DATA 1," ", 2,"-", 3,"7", 4,".", 5," ", 5,"-", 5,"r", 0,"" |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BCPL | BCPL | get "libhdr"
// Squeeze a string
let squeeze(in, ch, out) = valof
$( out%0 := 0
for i=1 to in%0
if i=1 | in%i~=ch | in%(i-1)~=ch
$( out%0 := out%0 + 1
out%(out%0) := in%i
$)
resultis out
$)
// Print string with brackets and length
let brackets(s) be
writef("%N: <<<%S>>>*N", s%0, s)
// Print original and collapsed version
let show(s, ch) be
$( let v = vec 1+255/BYTESPERWORD
writef("Character: '%C'*N", ch)
brackets(s)
brackets(squeeze(s, ch, v))
wrch('*N')
$)
let start() be
$( let s1=""
let s2="*"If I were two-faced, would I be wearing this one?*" --- Abraham Lincoln "
let s3="..1111111111111111111111111111111111111111111111111111111111111117777888"
let s4="I never give 'em hell, I just tell the truth, and they think it's hell. "
let s5=" --- Harry S Truman "
show(s1, ' ')
show(s2, '-')
show(s3, '7')
show(s4, '.')
show(s5, ' ')
show(s5, '-')
show(s5, 'r')
$) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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
| #8th | 8th | : number? >n >kind ns:n n:= ; |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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 Raspberry PI */
/* program strNumber.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessNum: .asciz "Enter number : \n"
szMessError: .asciz "String is not a number !!!\n"
szMessInteger: .asciz "String is a integer.\n"
szMessFloat: .asciz "String is a float.\n"
szMessFloatExp: .asciz "String is a float with exposant.\n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE
/* code section */
.text
.global main
main:
loop:
ldr x0,qAdrszMessNum
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8, #READ // request to read datas
svc 0 // call system
ldr x1,qAdrsBuffer // buffer address
mov x2,#0 // end of string
sub x0,x0,#1 // replace character 0xA
strb w2,[x1,x0] // store byte at the end of input string (x0 contains number of characters)
ldr x0,qAdrsBuffer
bl controlNumber // call routine
cmp x0,#0
bne 1f
ldr x0,qAdrszMessError // not a number
bl affichageMess
b 5f
1:
cmp x0,#1
bne 2f
ldr x0,qAdrszMessInteger // integer
bl affichageMess
b 5f
2:
cmp x0,#2
bne 3f
ldr x0,qAdrszMessFloat // float
bl affichageMess
b 5f
3:
cmp x0,#3
bne 5f
ldr x0,qAdrszMessFloatExp // float with exposant
bl affichageMess
5:
b loop
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessNum: .quad szMessNum
qAdrszMessError: .quad szMessError
qAdrszMessInteger: .quad szMessInteger
qAdrszMessFloat: .quad szMessFloat
qAdrszMessFloatExp: .quad szMessFloatExp
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsBuffer: .quad sBuffer
/******************************************************************/
/* control if string is number */
/******************************************************************/
/* x0 contains the address of the string */
/* x0 return 0 if not a number */
/* x0 return 1 if integer eq 12345 or -12345 */
/* x0 return 2 if float eq 123.45 or 123,45 or -123,45 */
/* x0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 */
controlNumber:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x1,#0
mov x3,#0 // point counter
1:
ldrb w2,[x0,x1]
cmp x2,#0 // end string ?
beq 7f
cmp x2,#' ' // space ?
bne 3f
add x1,x1,#1
b 1b // loop
3:
cmp x2,#'-' // negative ?
bne 4f
add x1,x1,#1
b 5f
4:
cmp x2,#'+' // positive ?
bne 5f
add x1,x1,#1
5:
ldrb w2,[x0,x1] // control space
cmp x2,#0 // end ?
beq 7f
cmp x2,#' ' // space ?
bne 6f
add x1,x1,#1
b 5b // loop
6:
ldrb w2,[x0,x1]
cmp x2,#0 // end ?
beq 14f
cmp x2,#'E' // exposant ?
beq 9f
cmp x2,#'e' // exposant ?
beq 9f
cmp x2,#'.' // point ?
bne 7f
add x3,x3,#1 // yes increment counter
add x1,x1,#1
b 6b // and loop
7:
cmp x2,#',' // comma ?
bne 8f
add x3,x3,#1 // yes increment counter
add x1,x1,#1
b 6b // and loop
8:
cmp x2,#'0' // control digit < 0
blt 99f
cmp x2,#'9' // control digit > 0
bgt 99f
add x1,x1,#1 // no error loop digit
b 6b
9: // float with exposant
add x1,x1,#1
ldrb w2,[x0,x1]
cmp x2,#0 // end ?
beq 99f
cmp x2,#'-' // negative exposant ?
bne 10f
add x1,x1,#1
10:
mov x4,#0 // nombre de chiffres
11:
ldrb w2,[x0,x1]
cmp x2,#0 // end ?
beq 13f
cmp x2,#'0' // control digit < 0
blt 99f
cmp x2,#'9' // control digit > 9
bgt 99f
add x1,x1,#1
add x4,x4,#1 // counter digit
b 11b // and loop
13:
cmp x4,#0 // number digit exposant = 0 -> error
beq 99f // error
cmp x4,#2 // number digit exposant > 2 -> error
bgt 99f // error
mov x0,#3 // valid float with exposant
b 100f
14:
cmp x3,#0
bne 15f
mov x0,#1 // valid integer
b 100f
15:
cmp x3,#1 // number of point or comma = 1 ?
blt 100f
bgt 99f // error
mov x0,#2 // valid float
b 100f
99:
mov x0,#0 // error
100:
ldp x4,x5,[sp],16 // restaur 2 registres
ldp x2,x3,[sp],16 // restaur 2 registres
ldp x1,lr,[sp],16 // restaur 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
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
| #Tcl | Tcl | package require Tcl 8.4
proc dl {_name cmd {where error} {value ""}} {
upvar 1 $_name N
switch -- $cmd {
insert {
if ![info exists N()] {set N() {"" "" 0}}
set id [lindex $N() 2]
lset N() 2 [incr id]
switch -- $where {
head {
set prev {}
set next [lindex $N() 0]
lset N() 0 $id
}
end {
set prev [lindex $N() 1]
set next {}
lset N() 1 $id
}
default {
set prev $where
set next [lindex $N($where) 1]
lset N($where) 1 $id
}
}
if {$prev ne ""} {lset N($prev) 1 $id}
if {$next ne ""} {lset N($next) 0 $id}
if {[lindex $N() 1] eq ""} {lset N() 1 $id}
set N($id) [list $prev $next $value]
return $id
}
delete {
set i $where
if {$where eq "head"} {set i [dl N head]}
if {$where eq "end"} {set i [dl N end]}
foreach {prev next} $N($i) break
if {$prev ne ""} {lset N($prev) 1 $next}
if {$next ne ""} {lset N($next) 0 $prev}
if {[dl N head] == $i} {lset N() 0 $next}
if {[dl N end] == $i} {lset N() 1 $prev}
unset N($i)
}
findfrom {
if {$where eq "head"} {set where [dl N head]}
for {set i $where} {$i ne ""} {set i [dl N next $i]} {
if {[dl N get $i] eq $value} {return $i}
}
}
get {lindex $N($where) 2}
set {lset N($where) 2 $value; set value}
head {lindex $N() 0}
end {lindex $N() 1}
next {lindex $N($where) 1}
prev {lindex $N($where) 0}
length {expr {[array size N]-1}}
asList {
set res {}
for {set i [dl N head]} {$i ne ""} {set i [dl N next $i]} {
lappend res [dl N get $i]
}
return $res
}
asList2 {
set res {}
for {set i [dl N end]} {$i ne ""} {set i [dl N prev $i]} {
lappend res [dl N get $i]
}
return $res
}
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
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 processString(input)
[Char = Int] charMap
V dup = Char("\0")
V index = 0
V pos1 = -1
V pos2 = -1
L(key) input
index++
I key C charMap
dup = key
pos1 = charMap[key]
pos2 = index
L.break
charMap[key] = index
V unique = I dup == Char("\0") {‘yes’} E ‘no’
V diff = I dup == Char("\0") {‘’} E ‘'’dup‘'’
V hexs = I dup == Char("\0") {‘’} E hex(dup.code)
V position = I dup == Char("\0") {‘’} E pos1‘ ’pos2
print(‘#<40 #<6 #<10 #<8 #<3 #<5’.format(input, input.len, unique, diff, hexs, position))
print(‘#<40 #2 #10 #8 #. #.’.format(‘String’, ‘Length’, ‘All Unique’, ‘1st Diff’, ‘Hex’, ‘Positions’))
print(‘#<40 #2 #10 #8 #. #.’.format(‘------------------------’, ‘------’, ‘----------’, ‘--------’, ‘---’, ‘---------’))
L(s) [‘’, ‘.’, ‘abcABC’, ‘XYZ ZYX’, ‘1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ’]
processString(s) |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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
| #APL | APL | task←{
⍝ Collapse a string
collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}
⍝ Given a function ⍺⍺, display a string in brackets,
⍝ along with its length, and do the same for the result
⍝ of applying ⍺⍺ to the string.
display←{
bracket←{(⍕⍴⍵),' «««',⍵,'»»»'}
↑(⊂bracket ⍵),(⊂bracket ⍺⍺ ⍵)
}
⍝ Strings from the task
s1←''
s2←'"If I were two-faced, would I be wearing this one?"'
s2,←' --- Abraham Lincoln '
s3←'..1111111111111111111111111111111111111111111111111'
s3,←'111111111111117777888'
s4←'I never give ''em hell, I just tell the truth, '
s4,←'and they think it''s hell. '
s5←' '
s5,←' --- Harry S Truman '
strs←s1 s2 s3 s4 s5
⍝ Collapse each string and display it as specified
↑collapse display¨ strs
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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 | lines: [
{::}
{:"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln :}
{:..1111111111111111111111111111111111111111111111111111111111111117777888:}
{:I never give 'em hell, I just tell the truth, and they think it's hell. :}
{: --- Harry S Truman :}
]
loop lines 'line ->
print squeeze line |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Python | Python | from itertools import product
def gen_dict(n_faces, n_dice):
counts = [0] * ((n_faces + 1) * n_dice)
for t in product(range(1, n_faces + 1), repeat=n_dice):
counts[sum(t)] += 1
return counts, n_faces ** n_dice
def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
c1, p1 = gen_dict(n_sides1, n_dice1)
c2, p2 = gen_dict(n_sides2, n_dice2)
p12 = float(p1 * p2)
return sum(p[1] * q[1] / p12
for p, q in product(enumerate(c1), enumerate(c2))
if p[0] > q[0])
print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
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 | strings: [
"", " ", "2", "333", ".55", "tttTTT",
"4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"
]
allSameChars?: function [str][
if empty? str -> return ø
current: first str
loop.with:'i str 'ch [
if ch <> current -> return i
]
return ø
]
loop strings 's [
prints ["\"" ++ s ++ "\"" ~"(size |size s|):"]
firstNotSame: allSameChars? s
if? null? firstNotSame -> print "all the same."
else -> print ~"first different char `|get s firstNotSame|` at position |firstNotSame|."
] |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
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 | testCases := ["", " ", "2", "333", ".55", "tttTTT", "4444 4444k"]
for key, str in testCases {
MsgBox % "Examining `'" str "`' which has a length of " StrLen(str) ":`n"
if (StrLen(str) == 0) or (StrLen(str) == 1) {
MsgBox % " All characters in the string are the same.`n"
continue
}
firstChar := SubStr(str, 1, 1)
Loop, Parse, str
{
if (firstChar != A_LoopField) {
hex := Format("0x{:x}", Ord(A_LoopField))
MsgBox % " Not all characters in the string are the same.`n Character `'" A_LoopField "`' (" hex ") is different at position " A_Index ".`n", *
break
}
if (A_Index = StrLen(str))
MsgBox % " All characters in the string are the same.`n", *
}
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Ring | Ring |
# Project : Determine if only one instance is running
task = "ringw.exe"
taskname = "tasklist.txt"
remove(taskname)
system("tasklist >> tasklist.txt")
fp = fopen(taskname,"r")
tasks = read("tasklist.txt")
counttask = count(tasks,task)
if counttask > 0
see task + " running in " + counttask + " instances" + nl
else
see task + " is not running" + nl
ok
func count(cString,dString)
sum = 0
while substr(cString,dString) > 0
sum++
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
return sum
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Ruby | Ruby | def main
puts "first instance"
sleep 20
puts :done
end
if $0 == __FILE__
if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
main
else
raise "another instance of this program is running"
end
end
__END__ |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Run_BASIC | Run BASIC | if instr(shell$("tasklist"),"rbp.exe") <> 0 then print "Task is Running" |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Rust | Rust | use std::net::TcpListener;
fn create_app_lock(port: u16) -> TcpListener {
match TcpListener::bind(("0.0.0.0", port)) {
Ok(socket) => {
socket
},
Err(_) => {
panic!("Couldn't lock port {}: another instance already running?", port);
}
}
}
fn remove_app_lock(socket: TcpListener) {
drop(socket);
}
fn main() {
let lock_socket = create_app_lock(12345);
// ...
// your code here
// ...
remove_app_lock(lock_socket);
} |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Go | Go | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
// Number of philosophers is simply the length of this list.
// It is not otherwise fixed in the program.
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3 // number of times each philosopher eats
const think = time.Second / 100 // mean think time
const eat = time.Second / 100 // mean eat time
var fmt = log.New(os.Stdout, "", 0) // for thread-safe output
var done = make(chan bool)
// This solution uses channels to implement synchronization.
// Sent over channels are "forks."
type fork byte
// A fork object in the program models a physical fork in the simulation.
// A separate channel represents each fork place. Two philosophers
// have access to each fork. The channels are buffered with capacity = 1,
// representing a place for a single fork.
// Goroutine for philosopher actions. An instance is run for each
// philosopher. Instances run concurrently.
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
// each philosopher goroutine has a random number generator,
// seeded with a hash of the philosopher's name.
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
// utility function to sleep for a randomized nominal time
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand // pick up forks
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f' // put down forks
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
// Create fork channels and start philosopher goroutines,
// supplying each goroutine with the appropriate channels
place0 := make(chan fork, 1)
place0 <- 'f' // byte in channel represents a fork on the table.
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
// Make one philosopher left handed by reversing fork place
// supplied to philosopher's dominant hand.
// This makes precedence acyclic, preventing deadlock.
go philosopher(ph[0], place0, placeLeft, done)
// they are all now busy eating
for range ph {
<-done // wait for philosphers to finish
}
fmt.Println("table empty")
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Fortran | Fortran |
program discordianDate
implicit none
! Declare variables
character(32) :: arg
character(15) :: season,day,holyday
character(80) :: Output,fmt1,fmt2,fmt3
character(2) :: dayfix,f1,f2,f3,f4
integer :: i,j,k,daysofyear,dayofweek,seasonnum,yold,dayofseason,t1,t2,t3
integer,dimension(8) :: values
integer, dimension(12) :: daysinmonth
logical :: isleapyear, isholyday, Pleapyear
! Get the current date
call date_and_time(VALUES=values)
! Set some values up to defaults
daysinmonth = (/ 31,28,31,30,31,30,31,31,30,31,30,31 /)
isleapyear = .false.
isholyday = .false.
! process any command line arguments
! using arguments dd mm yyyy
j = iargc()
do i = 1, iargc()
call getarg(i, arg) ! fetches argument as a character string
if (j==3) then
if (i==1) then
read(arg,'(i2)') values(3) ! convert to integer
endif
if (i==2) then
read(arg,'(i2)') values(2) ! convert to integer
endif
if (i==3) then
read(arg,'(i4)') values(1) ! convert to integer
endif
endif
if (j==2) then ! arguments dd mm
if (i==1) then
read(arg,'(i2)') values(3) ! convert to integer
endif
if (i==2) then
read(arg,'(i2)') values(2) ! convert to integer
endif
endif
if (j==1) then ! argument dd
read(arg,'(i2)') values(3) ! convert to integer
endif
end do
!Start the number crunching here
yold = values(1) + 1166
daysofyear = 0
if (values(2)>1) then
do i=1 , values(2)-1 , 1
daysofyear = daysofyear + daysinmonth(i)
end do
end if
daysofyear = daysofyear + values(3)
isholyday = .false.
isleapyear = Pleapyear(yold)
dayofweek = mod (daysofyear, 5)
seasonnum = ((daysofyear - 1) / 73) + 1
dayofseason = daysofyear - ((seasonnum - 1) * 73)
k = mod(dayofseason,10) ! just to get the day number postfix
select case (k)
case (1)
dayfix='st'
case (2)
dayfix='nd'
case (3)
dayfix='rd'
case default
dayfix='th'
end select
! except between 10th and 20th where we always have 'th'
if (((dayofseason > 10) .and. (dayofseason < 20)) .eqv. .true.) then
dayfix = 'th'
end if
select case (Seasonnum)
case (1)
season ='Choas'
f4 = '5'
case (2)
season ='Discord'
f4 = '7'
case (3)
season ='Confusion'
f4 = '9'
case (4)
season ='Bureaucracy'
f4 = '10'
case (5)
season ='The Aftermath'
f4 = '13'
end select
select case (dayofweek)
case (0)
day='Setting Orange'
f2 = '14'
case (1)
day ='Sweetmorn'
f2 = '9'
case (2)
day = 'Boomtime'
f2 = '8'
case (3)
day = 'Pungenday'
f2 = '9'
case (4)
day = 'Prickle-Prickle'
f2 = '15'
end select
! check for holydays
select case (dayofseason)
case (5)
isholyday = .true.
select case (seasonnum)
case (1)
holyday ='Mungday'
f1 = '7'
case (2)
holyday = 'Mojoday'
f1 = '7'
case (3)
holyday = 'Syaday'
f1 = '6'
case (4)
holyday = 'Zaraday'
f1 = '7'
case (5)
holyday = 'Maladay'
f1 = '7'
end select
Case (50)
isholyday = .true.
select case (seasonnum)
case (1)
holyday = 'Chaoflux'
f1 = '8'
case (2)
holyday = 'Discoflux'
f1 = '9'
case (3)
holyday = 'Confuflux'
f1 = '9'
case (4)
holyday = 'Bureflux'
f1 = '8'
case (5)
holyday = 'Afflux'
f1 = '6'
end select
end select
! Check if it is St. Tibbs day
if (isleapyear .eqv. .true.) then
if ((values(2) == 2) .and. (values(3) == 29)) then
isholyday = .true.
end if
end if
! Construct our format strings
f3 = "2"
if (dayofseason < 10) then
f3 = "1"
end if
fmt1 = "(a,i4)"
fmt2 = "(A,a" // f1 // ",A,A" // f2 // ",A,I" // f3 // ",A2,A,A" // f4 // ",A,I4)"
fmt3 = "(A,A" // f2 // ",A,I" // f3 //",A2,A,A" // f4 // ",A,I4)"
! print an appropriate line
if (isholyday .eqv. .true.) then
if (values(3) == 29) then
print fmt1,'Celebrate for today is St. Tibbs Day in the YOLD ',yold
else
print fmt2, 'Today is ',holyday, ' on ',day,' the ',dayofseason,dayfix,' day of ',season,' in the YOLD ',yold
end if
else ! not a holyday
print fmt3, 'Today is ',day,' the ',dayofseason,dayfix, ' day of ',season,' in the YOLD ',yold
end if
end program discordianDate
! Function to check to see if this is a leap year returns true or false!
function Pleapyear(dloy) result(leaper)
implicit none
integer, intent(in) :: dloy
logical :: leaper
leaper = .false.
if (mod((dloy-1166),4) == 0) then
leaper = .true.
end if
if (mod((dloy-1166),100) == 0) then
leaper = .false.
if (mod((dloy-1166),400)==0) then
leaper = .true.
end if
end if
end function Pleapyear
|
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
graph := getGraph()
repeat {
writes("What is the start node? ")
start := \graph.nodes[read()] | stop()
writes("What is the finish node? ")
finish := read() | stop()
QMouse(graph,start,finish)
waitForCompletion() # block until all quantum mice have finished
showPath(getBestMouse(),start.name,finish)
cleanGraph(graph)
}
end
procedure getGraph()
graph := Graph(table(),table())
write("Enter edges as 'n1,n2,weight' (blank line terminates)")
repeat {
if *(line := trim(read())) = 0 then break
line ? {
n1 := 1(tab(upto(',')),move(1))
n2 := 1(tab(upto(',')),move(1))
w := tab(0)
/graph.nodes[n1] := Node(n1,set())
/graph.nodes[n2] := Node(n2,set())
insert(graph.nodes[n1].targets,graph.nodes[n2])
graph.weights[n1||":"||n2] := w
}
}
return graph
end
procedure showPath(mouse,start,finish)
if \mouse then {
path := mouse.getPath()
writes("Weight: ",path.weight," -> ")
every writes(" ",!path.nodes)
write("\n")
}
else write("No path from ",start," to ",finish,"\n")
end
# A "Quantum-mouse" for traversing graphs. Each mouse lives for just
# one node but can spawn additional mice to search adjoining nodes.
global qMice, goodMice, region, qMiceEmpty
record Graph(nodes,weights)
record Node(name,targets,weight)
record Path(weight, nodes)
class QMouse(graph, loc, finish, path)
method getPath(); return path; end
method atEnd(); return (finish == loc.name); end
method visit(n) # Visit if we don't already have a cheaper route to n
newWeight := path.weight + graph.weights[loc.name||":"||n.name]
critical region[n]: if /n.weight | (newWeight < n.weight) then {
n.weight := newWeight
unlock(region[n])
return n
}
end
initially (g, l, f, p)
initial { # Construct critical region mutexes and completion condvar
qMiceEmpty := condvar()
region := table()
every region[n := !g.nodes] := mutex()
qMice := mutex(set())
cleanGraph(g)
}
graph := g
loc := l
finish := f
/p := Path(0,[])
path := Path(p.weight,copy(p.nodes))
if *path.nodes > 0 then
path.weight +:= g.weights[path.nodes[-1]||":"||loc.name]
put(path.nodes, loc.name)
insert(qMice,self)
thread {
if atEnd() then insert(goodMice, self) # This mouse found a finish
every QMouse(g,visit(!loc.targets),f,path)
delete(qMice, self) # Kill this mouse
if *qMice=0 then signal(qMiceEmpty) # All mice are dead
}
end
procedure cleanGraph(graph)
every (!graph.nodes).weight := &null
goodMice := mutex(set())
end
procedure getBestMouse()
every mouse := !goodMice do { # Locate shortest path
weight := mouse.getPath().weight
/minPathWeight := weight
if minPathWeight >=:= weight then bestMouse := mouse
}
return bestMouse
end
procedure waitForCompletion()
critical qMiceEmpty: while *qMice > 0 do wait(qMiceEmpty)
end |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #D | D | import std.stdio, std.typecons, std.conv, std.bigint, std.math,
std.traits;
Tuple!(uint, Unqual!T) digitalRoot(T)(in T inRoot, in uint base)
pure nothrow
in {
assert(base > 1);
} body {
Unqual!T root = inRoot.abs;
uint persistence = 0;
while (root >= base) {
auto num = root;
root = 0;
while (num != 0) {
root += num % base;
num /= base;
}
persistence++;
}
return typeof(return)(persistence, root);
}
void main() {
enum f1 = "%s(%d): additive persistance= %d, digital root= %d";
foreach (immutable b; [2, 3, 8, 10, 16, 36]) {
foreach (immutable n; [5, 627615, 39390, 588225, 393900588225])
writefln(f1, text(n, b), b, n.digitalRoot(b)[]);
writeln;
}
enum f2 = "<BIG>(%d): additive persistance= %d, digital root= %d";
immutable n = BigInt("581427189816730304036810394583022044713" ~
"00738980834668522257090844071443085937");
foreach (immutable b; [2, 3, 8, 10, 16, 36])
writefln(f2, b, n.digitalRoot(b)[]); // Shortened output.
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Nim | Nim | import strutils, sequtils, sugar
proc mdroot(n: int): tuple[mp, mdr: int] =
var mdr = @[n]
while mdr[mdr.high] > 9:
var n = 1
for dig in $mdr[mdr.high]:
n *= parseInt($dig)
mdr.add n
(mdr.high, mdr[mdr.high])
for n in [123321, 7739, 893, 899998]:
echo align($n, 6)," ",mdroot(n)
echo ""
var table = newSeqWith(10, newSeq[int]())
for n in 0..int.high:
if table.map((x: seq[int]) => x.len).min >= 5: break
table[mdroot(n).mdr].add n
for mp, val in table:
echo mp, ": ", val[0..4] |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #Icon_and_Unicon | Icon and Unicon | invocable all
global nameL, nameT, rules
procedure main() # Dinesman
nameT := table()
nameL := ["Baker", "Cooper", "Fletcher", "Miller", "Smith"]
rules := [ [ distinct ],
[ "~=", "Baker", top() ],
[ "~=", "Cooper", bottom() ],
[ "~=", "Fletcher", top() ],
[ "~=", "Fletcher", bottom() ],
[ ">", "Miller", "Cooper" ],
[ notadjacent, "Smith", "Fletcher" ],
[ notadjacent, "Fletcher", "Cooper" ],
[ showsolution ],
[ stop ] ]
if not solve(1) then
write("No solution found.")
end
procedure dontstop() # use if you want to search for all solutions
end
procedure showsolution() # show the soluton
write("The solution is:")
every write(" ",n := !nameL, " lives in ", nameT[n])
return
end
procedure eval(n) # evaluate a rule
r := copy(rules[n-top()])
every r[i := 2 to *r] := rv(r[i])
if get(r)!r then suspend
end
procedure rv(x) # return referenced value if it exists
return \nameT[x] | x
end
procedure solve(n) # recursive solver
if n > top() then { # apply rules
if n <= top() + *rules then
( eval(n) & solve(n+1) ) | fail
}
else # setup locations
(( nameT[nameL[n]] := bottom() to top() ) & solve(n + 1)) | fail
return
end
procedure distinct(a,b) # ensure each name is distinct
if nameT[n := !nameL] = nameT[n ~== key(nameT)] then fail
suspend
end
procedure notadjacent(n1,n2) # ensure n1,2 are not adjacent
if not adjacent(n1,n2) then suspend
end
procedure adjacent(n1,n2) # ensure n1,2 are adjacent
if abs(n1 - n2) = 1 then suspend
end
procedure bottom() # return bottom
return if *nameL > 0 then 1 else 0
end
procedure top() # return top
return *nameL
end |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Emacs_Lisp | Emacs Lisp | (defun dot-product (v1 v2)
(let ((res 0))
(dotimes (i (length v1))
(setq res (+ (* (elt v1 i) (elt v2 i)) res)))
res))
(dot-product [1 2 3] [1 2 3]) ;=> 14
(dot-product '(1 2 3) '(1 2 3)) ;=> 14 |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
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<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
/*
Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.
Comment this out if testing on a compiler where it is already defined.
*/
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #11l | 11l | T Triangle
(Float, Float) p1, p2, p3
F (p1, p2, p3)
.p1 = p1
.p2 = p2
.p3 = p3
F String()
R ‘Triangle: #., #., #.’.format(.p1, .p2, .p3)
F.const det2D()
R .p1[0] * (.p2[1] - .p3[1])
+ .p2[0] * (.p3[1] - .p1[1])
+ .p3[0] * (.p1[1] - .p2[1])
F checkTriWinding(Triangle &t; allowReversed)
V detTri = t.det2D()
I detTri < 0.0
assert(allowReversed, ‘Triangle has wrong winding direction’)
swap(&t.p2, &t.p3)
F boundaryCollideChk(Triangle t, Float eps)
R t.det2D() < eps
F boundaryDoesntCollideChk(Triangle t, Float eps)
R t.det2D() <= eps
F triTri2D(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)
checkTriWinding(&t1, allowReversed)
checkTriWinding(&t2, allowReversed)
V chkEdge = I onBoundary {:boundaryCollideChk} E :boundaryDoesntCollideChk
V lp1 = [t1.p1, t1.p2, t1.p3]
V lp2 = [t2.p1, t2.p2, t2.p3]
L(i) 3
V j = (i + 1) % 3
I chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &
chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &
chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)
R 0B
L(i) 3
V j = (i + 1) % 3
I chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &
chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &
chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)
R 0B
R 1B
F overlap(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)
I triTri2D(&t1, &t2, eps, allowReversed, onBoundary)
print(‘overlap’)
E
print(‘do not overlap’)
V t1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
V t2 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()
t1 = Triangle((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))
t2 = t1
print(t1" and\n"t2)
overlap(&t1, &t2, 0.0, 1B)
print()
t1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
t2 = Triangle((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()
t1.p3 = (2.5, 5.0)
t2 = Triangle((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()
t1 = Triangle((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))
t2 = Triangle((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()
t2 = Triangle((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()
t1 = Triangle((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))
t2 = Triangle((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))
print(t1" and\n"t2)
print(‘which have only a single corner in contact, if boundary points collide’)
overlap(&t1, &t2)
print()
print(t1" and\n"t2)
print(‘which have only a single corner in contact, if boundary points do not collide’)
overlap(&t1, &t2, 0.0, 0B, 0B) |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #11l | 11l | F s_permutations(seq)
V items = [[Int]()]
L(j) seq
[[Int]] new_items
L(item) items
V i = L.index
I i % 2
new_items [+]= (0 .. item.len).map(i -> @item[0 .< i] [+] [@j] [+] @item[i ..])
E
new_items [+]= (item.len .< -1).step(-1).map(i -> @item[0 .< i] [+] [@j] [+] @item[i ..])
items = new_items
R enumerate(items).map((i, item) -> (item, I i % 2 {-1} E 1))
F det(a)
V result = 0.0
L(sigma, _sign_) s_permutations(Array(0 .< a.len))
V x = Float(_sign_)
L(i) 0 .< a.len
x *= a[i][sigma[i]]
result += x
R result
F perm(a)
V result = 0.0
L(sigma, _sign_) s_permutations(Array(0 .< a.len))
V x = 1.0
L(i) 0 .< a.len
x *= a[i][sigma[i]]
result += x
R result
V a = [[1.0, 2.0],
[3.0, 4.0]]
V b = [[Float( 1), 2, 3, 4],
[Float( 4), 5, 6, 7],
[Float( 7), 8, 9, 10],
[Float(10), 11, 12, 13]]
V c = [[Float( 0), 1, 2, 3, 4],
[Float( 5), 6, 7, 8, 9],
[Float(10), 11, 12, 13, 14],
[Float(15), 16, 17, 18, 19],
[Float(20), 21, 22, 23, 24]]
print(‘perm: ’perm(a)‘ det: ’det(a))
print(‘perm: ’perm(b)‘ det: ’det(b))
print(‘perm: ’perm(c)‘ det: ’det(c)) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #68000_Assembly | 68000 Assembly |
1 0 n:/ Inf? . cr
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
BYTE FUNC AreEqual(CHAR ARRAY a,b)
BYTE i
IF a(0)#b(0) THEN
RETURN (0)
FI
FOR i=1 to a(0)
DO
IF a(i)#b(i) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC IsNumeric(CHAR ARRAY s)
CHAR ARRAY tmp(20)
INT i
CARD c
REAL r
i=ValI(s)
StrI(i,tmp)
IF AreEqual(s,tmp) THEN
RETURN (1)
FI
c=ValC(s)
StrC(c,tmp)
IF AreEqual(s,tmp) THEN
RETURN (1)
FI
ValR(s,r)
StrR(r,tmp)
IF AreEqual(s,tmp) THEN
RETURN (1)
FI
RETURN (0)
PROC Test(CHAR ARRAY s)
BYTE res
res=IsNumeric(s)
Print(s)
Print(" is ")
IF res=0 THEN
Print("not ")
FI
PrintE("a number.")
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
Test("56233")
Test("-315")
Test("1.36")
Test("-5.126")
Test("3.7E-05")
Test("1.23BC")
Test("5.6.3")
RETURN |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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
| #ActionScript | ActionScript | public function isNumeric(num:String):Boolean
{
return !isNaN(parseInt(num));
} |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
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_Basic_.NET | Visual Basic .NET | Public Class DoubleLinkList(Of T)
Private m_Head As Node(Of T)
Private m_Tail As Node(Of T)
Public Sub AddHead(ByVal value As T)
Dim node As New Node(Of T)(Me, value)
If m_Head Is Nothing Then
m_Head = Node
m_Tail = m_Head
Else
node.Next = m_Head
m_Head = node
End If
End Sub
Public Sub AddTail(ByVal value As T)
Dim node As New Node(Of T)(Me, value)
If m_Tail Is Nothing Then
m_Head = node
m_Tail = m_Head
Else
node.Previous = m_Tail
m_Tail = node
End If
End Sub
Public ReadOnly Property Head() As Node(Of T)
Get
Return m_Head
End Get
End Property
Public ReadOnly Property Tail() As Node(Of T)
Get
Return m_Tail
End Get
End Property
Public Sub RemoveTail()
If m_Tail Is Nothing Then Return
If m_Tail.Previous Is Nothing Then 'empty
m_Head = Nothing
m_Tail = Nothing
Else
m_Tail = m_Tail.Previous
m_Tail.Next = Nothing
End If
End Sub
Public Sub RemoveHead()
If m_Head Is Nothing Then Return
If m_Head.Next Is Nothing Then 'empty
m_Head = Nothing
m_Tail = Nothing
Else
m_Head = m_Head.Next
m_Head.Previous = Nothing
End If
End Sub
End Class
Public Class Node(Of T)
Private ReadOnly m_Value As T
Private m_Next As Node(Of T)
Private m_Previous As Node(Of T)
Private ReadOnly m_Parent As DoubleLinkList(Of T)
Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)
m_Parent = parent
m_Value = value
End Sub
Public Property [Next]() As Node(Of T)
Get
Return m_Next
End Get
Friend Set(ByVal value As Node(Of T))
m_Next = value
End Set
End Property
Public Property Previous() As Node(Of T)
Get
Return m_Previous
End Get
Friend Set(ByVal value As Node(Of T))
m_Previous = value
End Set
End Property
Public ReadOnly Property Value() As T
Get
Return m_Value
End Get
End Property
Public Sub InsertAfter(ByVal value As T)
If m_Next Is Nothing Then
m_Parent.AddTail(value)
ElseIf m_Previous Is Nothing Then
m_Parent.AddHead(value)
Else
Dim node As New Node(Of T)(m_Parent, value)
node.Previous = Me
node.Next = Me.Next
Me.Next.Previous = node
Me.Next = node
End If
End Sub
Public Sub Remove()
If m_Next Is Nothing Then
m_Parent.RemoveTail()
ElseIf m_Previous Is Nothing Then
m_Parent.RemoveHead()
Else
m_Previous.Next = Me.Next
m_Next.Previous = Me.Previous
End If
End Sub
End Class |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
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
| #Action.21 | Action! | PROC PrintBH(BYTE a)
BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
Put(hex(a RSH 4))
Put(hex(a&$0F))
RETURN
PROC Test(CHAR ARRAY s)
BYTE i,j,n,pos1,pos2
pos1=0 pos2=0
n=s(0)-1
IF n=255 THEN n=0 FI
FOR i=1 TO n
DO
FOR j=i+1 TO s(0)
DO
IF s(j)=s(i) THEN
pos1=i
pos2=j
EXIT
FI
OD
IF pos1#0 THEN
EXIT
FI
OD
PrintF("""%S"" (len=%B) -> ",s,s(0))
IF pos1=0 THEN
PrintE("all characters are unique.")
ELSE
PrintF("""%C"" (hex=$",s(pos1))
PrintBH(s(pos1))
PrintF(") is duplicated at pos. %B and %B.%E",pos1,pos2)
FI
PutE()
RETURN
PROC Main()
Test("")
Test(".")
Test("abcABC")
Test("XYZ ZYX")
Test("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
RETURN |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
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.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
procedure All_Chars_Unique (S : in String) is
begin
Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
for I in S'First .. S'Last - 1 loop
for J in I + 1 .. S'Last loop
if S(I) = S(J) then
Put (" First duplicate at positions" & I'Image &
" and" & J'Image & ", character = '" & S(I) &
"', hex = ");
Put (Character'Pos (S(I)), Width => 0, Base => 16);
New_Line;
return;
end if;
end loop;
end loop;
Put_Line (" All characters are unique.");
end All_Chars_Unique;
begin
All_Chars_Unique ("");
All_Chars_Unique (".");
All_Chars_Unique ("abcABC");
All_Chars_Unique ("XYZ ZYX");
All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
|
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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 | collapsible_string(str){
for i, ch in StrSplit(str){
if (ch <> prev)
res .= ch
prev := ch
}
return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»"
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK
BEGIN {
for (i=1; i<=9; i++) {
for (j=1; j<=i; j++) {
arr[0] = arr[0] i
}
}
arr[++n] = ""
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. "
arr[++n] = " --- Harry S Truman "
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
arr[++n] = "headmistressship"
for (i=0; i<=n; i++) {
main(arr[i])
}
exit(0)
}
function main(str, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (prev_c != c) {
prev_c = c
new_str = new_str c
}
}
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #R | R | probability <- function(facesCount1, diceCount1, facesCount2, diceCount2)
{
mean(replicate(10^6, sum(sample(facesCount1, diceCount1, replace = TRUE)) > sum(sample(facesCount2, diceCount2, replace = TRUE))))
}
cat("Player 1's probability of victory is", probability(4, 9, 6, 6),
"in the first game and", probability(10, 5, 7, 6), "in the second.") |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Racket | Racket | #lang racket
(define probs# (make-hash))
(define (NdD n d)
(hash-ref!
probs# (cons n d)
(λ ()
(cond
[(= n 0) ; every chance of nothing!
(hash 0 1)]
[else
(for*/fold ((hsh (hash))) (((i p) (in-hash (NdD (sub1 n) d))) (r (in-range 1 (+ d 1))))
(hash-update hsh (+ r i) (λ (p+) (+ p+ (/ p d))) 0))]))))
(define (game-probs N1 D1 N2 D2)
(define P1 (NdD N1 D1))
(define P2 (NdD N2 D2))
(define-values (W D L)
(for*/fold ((win 0) (draw 0) (lose 0)) (((r1 p1) (in-hash P1)) ((r2 p2) (in-hash P2)))
(define p (* p1 p2))
(cond
[(< r1 r2) (values win draw (+ lose p))]
[(= r1 r2) (values win (+ draw p) lose)]
[(> r1 r2) (values (+ win p) draw lose)])))
(printf "P(P1 win): ~a~%" (real->decimal-string W 6))
(printf "P(draw): ~a~%" (real->decimal-string D 6))
(printf "P(P2 win): ~a~%" (real->decimal-string L 6))
(list W D L))
(printf "GAME 1 (9D4 vs 6D6)~%")
(game-probs 9 4 6 6)
(newline)
(printf "GAME 2 (5D10 vs 6D7) [what is a D7?]~%")
(game-probs 5 10 6 7) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_THE_SAME_CHARACTERS.AWK
BEGIN {
for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value
n = split(", ,2,333,.55,tttTTT,4444 444k",arr,",")
for (i in arr) {
width = max(width,length(arr[i]))
}
width += 2
fmt = "| %-*s | %-6s | %-8s | %-8s | %-3s | %-8s |\n"
head1 = head2 = sprintf(fmt,width,"string","length","all same","1st diff","hex","position")
gsub(/[^|\n]/,"-",head1)
printf(head1 head2 head1) # column headings
for (i=1; i<=n; i++) {
main(arr[i])
}
printf(head1) # column footing
exit(0)
}
function main(str, c,first_diff,hex,i,leng,msg,position) {
msg = "yes"
leng = length(str)
for (i=1; i<leng; i++) {
c = substr(str,i+1,1)
if (substr(str,i,1) != c) {
msg = "no"
first_diff = "'" c "'"
hex = sprintf("%2X",ord_arr[c])
position = i + 1
break
}
}
printf(fmt,width,"'" str "'",leng,msg,first_diff,hex,position)
}
function max(x,y) { return((x > y) ? x : y) }
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Scala | Scala | import java.io.IOException
import java.net.{InetAddress, ServerSocket}
object SingletonApp extends App {
private val port = 65000
try {
val s = new ServerSocket(port, 10, InetAddress.getLocalHost)
}
catch {
case _: IOException =>
// port taken, so app is already running
println("Application is already running, so terminating this instance.")
sys.exit(-1)
}
println("OK, only this instance is running but will terminate in 10 seconds.")
Thread.sleep(10000)
sys.exit(0)
} |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Sidef | Sidef | # For this to work, you need to explicitly
# store the returned fh inside a variable.
var fh = File(__FILE__).open_r
# Now call the flock() method on it
fh.flock(File.LOCK_EX | File.LOCK_NB) ->
|| die "I'm already running!"
# Your code here...
say "Running..."
Sys.sleep(20)
say 'Done!' |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Swift | Swift | import Foundation
let globalCenter = NSDistributedNotificationCenter.defaultCenter()
let time = NSDate().timeIntervalSince1970
globalCenter.addObserverForName("OnlyOne", object: nil, queue: NSOperationQueue.mainQueue()) {not in
if let senderTime = not.userInfo?["time"] as? NSTimeInterval where senderTime != time {
println("More than one running")
exit(0)
} else {
println("Only one")
}
}
func send() {
globalCenter.postNotificationName("OnlyOne", object: nil, userInfo: ["time": time])
let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))
dispatch_after(waitTime, dispatch_get_main_queue()) {
send()
}
}
send()
CFRunLoopRun() |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Tcl | Tcl | package require Tcl 8.6
try {
# Pick a port number based on the name of the main script executing
socket -server {apply {{chan args} {close $chan}}} -myaddr localhost \
[expr {1024 + [zlib crc32 [file normalize $::argv0]] % 30000}]
} trap {POSIX EADDRINUSE} {} {
# Generate a nice error message
puts stderr "Application $::argv0 already running?"
exit 1
} |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Groovy | Groovy | import groovy.transform.Canonical
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
@Canonical
class Fork {
String name
Lock lock = new ReentrantLock()
void pickUp(String philosopher) {
lock.lock()
println " $philosopher picked up $name"
}
void putDown(String philosopher) {
lock.unlock()
println " $philosopher put down $name"
}
}
@Canonical
class Philosopher extends Thread {
Fork f1
Fork f2
@Override
void run() {
def random = new Random()
(1..20).each { bite ->
println "$name is hungry"
f1.pickUp name
f2.pickUp name
println "$name is eating bite $bite"
Thread.sleep random.nextInt(300) + 100
f2.putDown name
f1.putDown name
}
}
}
void diningPhilosophers(names) {
def forks = (1..names.size()).collect { new Fork(name: "Fork $it") }
def philosophers = []
names.eachWithIndex{ n, i ->
def (i1, i2) = [i, (i + 1) % 5]
if (i2 < i1) (i1, i2) = [i2, i]
def p = new Philosopher(name: n, f1: forks[i1], f2: forks[i2])
p.start()
philosophers << p
}
philosophers.each { it.join() }
}
diningPhilosophers(['Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell']) |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #FreeBASIC | FreeBASIC | #Include "datetime.bi"
meses:
Data "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"
dias_laborales:
Data "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle"
dias_previos_al_1er_mes:
' ene feb mar abr may jun jul ago sep oct nov dic
Data 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Function cJuliano(d As Double) As Integer
'no tiene en cuenta los años bisiestos (no es necesario para ddate)
Dim tmp As Integer, i As Integer
Restore dias_previos_al_1er_mes
For i = 1 To Month(d)
Read tmp
Next i
Function = tmp + Day(d)
End Function
Sub cDiscordiano(Fecha As String)
Dim As Integer dyear, dday, j, jday
Dim As Double tempfecha = Datevalue(Fecha)
Dim As String ddate, dseason, dweekday
dyear = Year(tempfecha) + 1166
If (2 = Month(tempfecha)) And (29 = Day(tempfecha)) Then
ddate = "Saint Tib's Day, " & Str(dyear) & " YOLD"
Else
jday = cJuliano(tempfecha)
Restore meses
For j = 1 To ((jday - 1) \ 73) + 1
Read dseason
Next j
dday = (jday Mod 73)
If 0 = dday Then dday = 73
Restore dias_laborales
For j = 1 To (jday Mod 5) + 1
Read dweekday
Next j
ddate = dweekday & ", " & dseason & " " & Trim(Str(dday)) & ", " & Trim(Str(dyear)) & " YOLD"
End If
Print Fecha & " -> " & ddate
End Sub
cDiscordiano("01/01/2020")
cDiscordiano("05/01/2020")
cDiscordiano("28/02/2020")
cDiscordiano("01/03/2020")
cDiscordiano("22/07/2020")
cDiscordiano("31/12/2020")
cDiscordiano("20/04/2022")
cDiscordiano("24/05/2020")
cDiscordiano("29/02/2020")
cDiscordiano("15/07/2019")
cDiscordiano("19/03/2025")
Sleep |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #J | J |
NB. verbs and adverb
parse_table=: ;:@:(LF&= [;._2 -.&CR)
mp=: $:~ :(+/ .*) NB. matrix product
min=: <./ NB. minimum
Index=: (i.`)(`:6) NB. Index adverb
dijkstra=: dyad define
'LINK WEIGHT'=. , (0 _ ,. 2) <;.3 y
'SOURCE SINK'=. |: LINK
FRONTIER=. , < {. x
GOAL=. {: x
enumerate=. 2&([\)&.>
while. FRONTIER do.
PATH_MASK=. FRONTIER (+./@:(-:"1/)&:>"0 _~ enumerate)~ LINK
I=. PATH_MASK min Index@:mp WEIGHTS
PATH=. I >@{ FRONTIER
STATE=. {: PATH
if. STATE -: GOAL do. PATH return. end.
FRONTIER=. (<<< I) { FRONTIER NB. elision
ADJACENCIES=. (STATE = SOURCE) # SINK
FRONTIER=. FRONTIER , PATH <@,"1 0 ADJACENCIES
end.
EMPTY
)
NB. The specific problem
INPUT=: noun define
a b 7
a c 9
a f 14
b c 10
b d 15
c d 11
c f 2
d e 6
e f 9
)
T=: parse_table INPUT
NAMED_LINKS=: _ 2 {. T
NODES=: ~. , NAMED_LINKS NB. vector of boxed names
NUMBERED_LINKS=: NODES i. NAMED_LINKS
WEIGHTS=: _ ".&> _ _1 {. T
GRAPH=: NUMBERED_LINKS ,. WEIGHTS NB. GRAPH is the numerical representation
TERMINALS=: NODES (i. ;:) 'a e'
NODES {~ TERMINALS dijkstra GRAPH
Note 'Output'
┌─┬─┬─┬─┐
│a│c│d│e│
└─┴─┴─┴─┘
TERMINALS and GRAPH are integer arrays:
TERMINALS
0 5
GRAPH
0 1 7
0 2 9
0 3 14
1 2 10
1 4 15
2 4 11
2 3 2
4 5 6
5 3 9
)
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Dc | Dc | ?[10~rd10<p]sp[+z1<q]sq[lpxlqxd10<r]dsrxp |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #DCL | DCL | $ x = p1
$ count = 0
$ sum = x
$ loop1:
$ length = f$length( x )
$ if length .eq. 1 then $ goto done
$ i = 0
$ sum = 0
$ loop2:
$ digit = f$extract( i, 1, x )
$ sum = sum + digit
$ i = i + 1
$ if i .lt. length then $ goto loop2
$ x = f$string( sum )
$ count = count + 1
$ goto loop1
$ done:
$ write sys$output p1, " has additive persistence ", count, " and digital root of ", sum |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #PARI.2FGP | PARI/GP | a(n)=my(i);while(n>9,n=factorback(digits(n));i++);[i,n];
apply(a, [123321, 7739, 893, 899998])
v=vector(10,i,[]); forstep(n=0,oo,1, t=a(n)[2]+1; if(#v[t]<5,v[t]=concat(v[t],n); if(vecmin(apply(length,v))>4, return(v)))) |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #J | J | possible=: ((i.!5) A. i.5) { 'BCFMS' |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Erlang | Erlang | dotProduct(A,B) when length(A) == length(B) -> dotProduct(A,B,0);
dotProduct(_,_) -> erlang:error('Vectors must have the same length.').
dotProduct([H1|T1],[H2|T2],P) -> dotProduct(T1,T2,P+H1*H2);
dotProduct([],[],P) -> P.
dotProduct([1,3,-5],[4,-2,-1]). |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# | using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
} |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Ada | Ada |
WITH Ada.Text_IO; USE Ada.Text_IO;
PROCEDURE Main IS
TYPE Vertex IS MOD 3;
TYPE Point IS ARRAY (0 .. 1) OF Float;
TYPE Triangle IS ARRAY (Vertex) OF Point;
TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float;
FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS
FUNCTION Aff (U : Point) RETURN Float IS
((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1)));
BEGIN
RETURN Aff (M) * Aff (N) >= 0.0;
END Same_Side;
FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS
(FOR ALL V IN Vertex =>
(FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P)));
FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS
(In_Side (T1, T2) AND THEN In_Side (T2, T1));
FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS
((T (0), T (1)), (T (2), T (3)), (T (4), T (5)));
PROCEDURE Put (T1, T2 : Triangle_Vertices) IS
BEGIN
Put_Line (Overlap (+T1, +T2)'Img);
END Put;
BEGIN
Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0));
Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0));
Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0));
Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0));
Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0));
Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0));
Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0));
END Main;
|
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #360_Assembly | 360 Assembly | * Matrix arithmetic 13/05/2016
MATARI START
STM R14,R12,12(R13) save caller's registers
LR R12,R15 set R12 as base register
USING MATARI,R12 notify assembler
LA R11,SAVEAREA get the address of my savearea
ST R13,4(R11) save caller's savearea pointer
ST R11,8(R13) save my savearea pointer
LR R13,R11 set R13 to point to my savearea
LA R1,TT @tt
BAL R14,DETER call deter(tt)
LR R2,R0 R2=deter(tt)
LR R3,R1 R3=perm(tt)
XDECO R2,PG1+12 edit determinant
XPRNT PG1,80 print determinant
XDECO R3,PG2+12 edit permanent
XPRNT PG2,80 print permanent
EXITALL L R13,SAVEAREA+4 restore caller's savearea address
LM R14,R12,12(R13) restore caller's registers
XR R15,R15 set return code to 0
BR R14 return to caller
SAVEAREA DS 18F main savearea
TT DC F'3' matrix size
DC F'2',F'9',F'4',F'7',F'5',F'3',F'6',F'1',F'8' <==input
PG1 DC CL80'determinant='
PG2 DC CL80'permanent='
XDEC DS CL12
* recursive function (R0,R1)=deter(t) (python style)
DETER CNOP 0,4 returns determinant and permanent
STM R14,R12,12(R13) save all registers
LR R9,R1 save R1
L R2,0(R1) n
BCTR R2,0 n-1
LR R11,R2 n-1
MR R10,R2 (n-1)*(n-1)
SLA R11,2 (n-1)*(n-1)*4
LA R11,1(R11) size of q array
A R11,=A(STACKLEN) R11 storage amount required
GETMAIN RU,LV=(R11) allocate storage for stack
USING STACK,R10 make storage addressable
LR R10,R1 establish stack addressability
LA R1,SAVEAREB get the address of my savearea
ST R13,4(R1) save caller's savearea pointer
ST R1,8(R13) save my savearea pointer
LR R13,R1 set R13 to point to my savearea
LR R1,R9 restore R1
LR R9,R1 @t
L R4,0(R9) t(0)
ST R4,N n=t(0)
IF1 CH R4,=H'1' if n=1
BNE SIF1 then
L R2,4(R9) t(1)
ST R2,R r=t(1)
ST R2,S s=t(1)
B EIF1 else
SIF1 L R2,N n
BCTR R2,0 n-1
ST R2,Q q(0)=n-1
ST R2,NM1 nm1=n-1
LA R0,1 1
ST R0,SGN sgn=1
SR R0,R0 0
ST R0,R r=0
ST R0,S s=0
LA R6,1 k=1
LOOPK C R6,N do k=1 to n
BH ELOOPK leave k
SR R0,R0 0
ST R0,JQ jq=0
ST R0,KTI kti=0
LA R7,1 iq=1
LOOPIQ C R7,NM1 do iq=1 to n-1
BH ELOOPIQ leave iq
LR R2,R7 iq
LA R2,1(R2) iq+1
ST R2,IT it=iq+1
L R2,KTI kti
A R2,N kti+n
ST R2,KTI kti=kti+n
ST R2,KT kt=kti
LA R8,1 jt=1
LOOPJT C R8,N do jt=1 to n
BH ELOOPJT leave jt
L R2,KT kt
LA R2,1(R2) kt+1
ST R2,KT kt=kt+1
IF2 CR R8,R6 if jt<>k
BE EIF2 then
L R2,JQ jq
LA R2,1(R2) jq+1
ST R2,JQ jq=jq+1
L R1,KT kt
SLA R1,2 *4
L R2,0(R1,R9) t(kt)
L R1,JQ jq
SLA R1,2 *4
ST R2,Q(R1) q(jq)=t(kt)
EIF2 EQU * end if
LA R8,1(R8) jt=jt+1
B LOOPJT next jt
ELOOPJT LA R7,1(R7) iq=iq+1
B LOOPIQ next iq
ELOOPIQ LR R1,R6 k
SLA R1,2 *4
L R5,0(R1,R9) t(k)
LR R2,R5 R2,R5=t(k)
LA R1,Q @q
BAL R14,DETER call deter(q)
LR R3,R0 R3=deter(q)
ST R1,P p=perm(q)
MR R4,R3 R5=t(k)*deter(q)
M R4,SGN R5=sgn*t(k)*deter(q)
A R5,R +r
ST R5,R r=r+sgn*t(k)*deter(q)
LR R5,R2 t(k)
M R4,P R5=t(k)*perm(q)
A R5,S +s
ST R5,S s=s+t(k)*perm(q)
L R2,SGN sgn
LCR R2,R2 -sgn
ST R2,SGN sgn=-sgn
LA R6,1(R6) k=k+1
B LOOPK next k
ELOOPK EQU * end do
EIF1 EQU * end if
EXIT L R13,SAVEAREB+4 restore caller's savearea address
L R2,R return value (determinant)
L R3,S return value (permanent)
XR R15,R15 set return code to 0
FREEMAIN A=(R10),LV=(R11) free allocated storage
LR R0,R2 first return value
LR R1,R3 second return value
L R14,12(R13) restore caller's return address
LM R2,R12,28(R13) restore registers R2 to R12
BR R14 return to caller
IT DS F static area (out of stack)
KT DS F "
JQ DS F "
KTI DS F "
P DS F "
DROP R12 base no longer needed
STACK DSECT dynamic area (stack)
SAVEAREB DS 18F function savearea
N DS F n
NM1 DS F n-1
R DS F determinant accu
S DS F permanent accu
SGN DS F sign
STACKLEN EQU *-STACK
Q DS F sub matrix q((n-1)*(n-1)+1)
YREGS
END MATARI |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Arturo | Arturo | printMatrix: function [m][
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
print "--------------------------------"
]
permutations: function [arr][
d: 1
c: array.of: size arr 0
xs: new arr
sign: 1
ret: new @[@[xs, sign]]
while [true][
while [d > 1][
d: d-1
c\[d]: 0
]
while [c\[d] >= d][
d: d+1
if d >= size arr -> return ret
]
i: (1 = and d 1)? -> c\[d] -> 0
tmp: xs\[i]
xs\[i]: xs\[d]
xs\[d]: tmp
sign: neg sign
'ret ++ @[new @[xs, sign]]
c\[d]: c\[d] + 1
]
return ret
]
perm: function [a][
n: 0..dec size a
result: new 0.0
loop permutate n 'sigma [
x: 1.0
loop n 'i -> x: x * get a\[i] sigma\[i]
'result + x
]
return result
]
det: function [a][
n: 0..dec size a
result: new 0.0
loop.with:'i permutations n 'p[
x: p\1
loop n 'i -> x: x * get a\[i] p\0\[i]
'result + x
]
return result
]
A: [[1.0 2.0]
[3.0 4.0]]
B: [[ 1.0 2 3 4]
[ 4.0 5 6 7]
[ 7.0 8 9 10]
[10.0 11 12 13]]
C: [[ 0.0 1 2 3 4]
[ 5.0 6 7 8 9]
[10.0 11 12 13 14]
[15.0 16 17 18 19]
[20.0 21 22 23 24]]
print ["A: perm ->" perm A "det ->" det A]
print ["B: perm ->" perm B "det ->" det B]
print ["C: perm ->" perm C "det ->" det C] |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #8th | 8th |
1 0 n:/ Inf? . cr
|
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #ABAP | ABAP | report zdiv_zero
data x type i.
try.
x = 1 / 0.
catch CX_SY_ZERODIVIDE.
write 'Divide by zero.'.
endtry.
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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 | package Numeric_Tests is
function Is_Numeric (Item : in String) return Boolean;
end Numeric_Tests; |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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
| #Aime | Aime | integer
is_numeric(text s)
{
return !trap_q(alpha, s, 0);
}
integer
main(void)
{
if (!is_numeric("8192&*")) {
o_text("Not numeric.\n");
}
if (is_numeric("8192")) {
o_text("Numeric.\n");
}
return 0;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
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 | import "/llist" for DLinkedList
var dll = DLinkedList.new()
for (i in 1..3) dll.add(i)
System.print(dll)
for (i in 1..3) dll.remove(i)
System.print(dll) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
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 | BEGIN
# mode to hold the positions of duplicate characters in a string #
MODE DUPLICATE = STRUCT( INT original, first duplicate );
# finds the first non-unique character in s and returns its position #
# and the position of the original character in a DUPLICATE #
# if all characters in s are uniue, returns LWB s - 1, UPB s + 1 #
PROC first duplicate position = ( STRING s )DUPLICATE:
BEGIN
BOOL all unique := TRUE;
INT o pos := LWB s - 1;
INT d pos := UPB s + 1;
FOR i FROM LWB s TO UPB s WHILE all unique DO
FOR j FROM i + 1 TO UPB s WHILE all unique DO
IF NOT ( all unique := s[ i ] /= s[ j ] ) THEN
o pos := i;
d pos := j
FI
OD
OD;
DUPLICATE( o pos, d pos )
END # first duplicate position # ;
# task test cases #
[]STRING tests = ( "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" );
FOR t pos FROM LWB tests TO UPB tests DO
IF STRING s = tests[ t pos ];
DUPLICATE d = first duplicate position( s );
print( ( "<<<", s, ">>> (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), "): " ) );
original OF d < LWB s
THEN
print( ( " all characters are unique", newline ) )
ELSE
# have at least one duplicate #
print( ( " first duplicate character: """, s[ original OF d ], """"
, " at: ", whole( original OF d, 0 ), " and ", whole( first duplicate OF d, 0 )
, newline
)
)
FI
OD
END |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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 | DATA ""
DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
DATA " --- Harry S Truman "
DATA "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
DATA "headmistressship"
DOTIMES 7
READ x$
found = 0
PRINT "<<<", x$, ">>> - length: ", LEN(x$)
PRINT "<<<";
FOR y = 1 TO LEN(x$)
IF MID$(x$, y, 1) <> MID$(x$, y+1, 1) THEN
PRINT MID$(x$, y, 1);
INCR found
ENDIF
NEXT
PRINT ">>> - length: ", found
DONE |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | 10 READ N%
20 FOR A% = 1 TO N%
30 READ I$: GOSUB 100
40 PRINT LEN(I$); "<<<"; I$; ">>>"
50 PRINT LEN(O$); "<<<"; O$; ">>>"
55 PRINT
60 NEXT
70 END
100 REM Collapse I$ into O$
105 IF I$="" THEN O$=I$: RETURN
110 O$=SPACE$(LEN(I$))
120 P$=LEFT$(I$,1)
130 MID$(O$,1,1)=P$
140 O%=2
150 FOR I%=2 TO LEN(I$)
160 C$=MID$(I$,I%,1)
170 IF P$<>C$ THEN MID$(O$,O%,1)=C$: O%=O%+1: P$=C$
180 NEXT
190 O$=LEFT$(O$,O%-1)
200 RETURN
400 DATA 5: REM There are 5 strings
410 DATA ""
420 DATA "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
430 DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
440 DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
450 DATA " --- Harry S Truman " |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Raku | Raku | sub likelihoods ($roll) {
my ($dice, $faces) = $roll.comb(/\d+/);
my @counts;
@counts[$_]++ for [X+] |(1..$faces,) xx $dice;
return [@counts[]:p], $faces ** $dice;
}
sub beating-probability ([$roll1, $roll2]) {
my (@c1, $p1) := likelihoods $roll1;
my (@c2, $p2) := likelihoods $roll2;
my $p12 = $p1 * $p2;
[+] gather for flat @c1 X @c2 -> $p, $q {
take $p.value * $q.value / $p12 if $p.key > $q.key;
}
}
# We're using standard DnD notation for dice rolls here.
say .gist, "\t", .raku given beating-probability < 9d4 6d6 >;
say .gist, "\t", .raku given beating-probability < 5d10 6d7 >; |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC |
10 'SAVE"SAMECHAR", A
20 DEFINT A-Z
30 DATA ""," ","2","333",".55","tttTTT","4444 444k", "FIN"
40 ' Main program cycle
50 CLS
60 PRINT "Program SameChar"
70 PRINT "Determines if a string has the same character or not."
80 PRINT
90 WHILE S$<>"FIN"
100 READ S$
110 IF S$="FIN" THEN 150
120 GOSUB 190 ' Revision subroutine
130 PRINT "'";S$;"' of length";LEN(S$);
140 IF I<2 THEN PRINT "contains all the same character." ELSE PRINT "is different at possition";STR$(I);": '";DC$; "' (0x"; HEX$(ASC(DC$)); ")"
150 WEND
160 PRINT
170 PRINT "End of program run."
180 END
190 ' DifChar subroutine
200 C$ = LEFT$(S$,1)
210 I = 1
220 DC$=""
230 WHILE I<LEN(S$) AND DC$=""
240 IF MID$(S$,I,1)<>C$ THEN DC$=MID$(S$,I,1) ELSE I=I+1
250 WEND
260 IF DC$="" THEN I=1
270 RETURN |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #TXR | TXR | ;;; Define some typedefs for clear correspondence with Win32
(typedef HANDLE cptr)
(typedef LPSECURITY_ATTRIBUTES cptr)
(typedef WINERR (enum WINERR ERROR_SUCCESS
(ERROR_ALREADY_EXISTS 183)))
(typedef BOOL (enum BOOL FALSE TRUE))
(typedef LPCWSTR wstr)
;;; More familiar spelling for null pointer.
(defvarl NULL cptr-null)
;;; Define access to foreign functions.
(with-dyn-lib "kernel32.dll"
(deffi CreateMutex "CreateMutexW" HANDLE (LPSECURITY_ATTRIBUTES BOOL LPCWSTR))
(deffi CloseHandle "CloseHandle" BOOL (HANDLE))
(deffi GetLastError "GetLastError" WINERR ()))
;;; Now, the single-instance program:
(defvar m (CreateMutex NULL 'TRUE "ApplicationName"))
(unless (eq (GetLastError) 'ERROR_ALREADY_EXISTS)
;; mutual exclusion here
)
(CloseHandle m) |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #UNIX_Shell | UNIX Shell |
# (c) Copyright 2005 Mark Hobley
#
# This is free software. This file can be redistributed or modified
# under the terms of version 1.2 of the GNU Free Documentation Licence
# as published by the Free Software Foundation.
#
singleinstance ()
{
if [ -d $SRUNDIR ] ; then
if [ -w $SRUNDIR ] ; then
if [ -d $SRUNDIR/$APPNAME ] ; then
echo "Process Already Running" >& 2
return 221
else
mkdir $SRUNDIR/$APPNAME
if [ "$?" -ne 0 ] ; then
if [ -d $SRUNDIR/$APPNAME ] ; then
echo "Process Already Running" >& 2
return 221
else
echo "Unexpected Error" >& 2
return 239
fi
fi
return 0 ; # This is a unique instance
fi
else
echo "Permission Denied" >& 2
return 210
fi
else
echo "Missing Directory" >& 2
return 199
fi
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Visual_Basic | Visual Basic | Dim onlyInstance as Boolean
onlyInstance = not App.PrevInstance |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Wren | Wren | import "io" for File, FileFlags
var specialFile = "wren-exclusive._sp"
var checkOneInstanceRunning = Fn.new {
// attempt to create the special file with exclusive access
var ff = FileFlags.create | FileFlags.exclusive
File.openWithFlags(specialFile, ff) { |file| } // closes automatically if successful
}
// check if the current instance is the only one running
var fiber = Fiber.new {
checkOneInstanceRunning.call()
}
var error = fiber.try()
if (error) {
System.print("An instance is already running.")
return
}
// do something that takes a while for testing purposes
var sum = 0
for (i in 1...1e8) {
sum = sum + i
}
System.print(sum)
File.delete(specialFile) // clean up |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Haskell | Haskell | module Philosophers where
import Control.Monad
import Control.Concurrent
import Control.Concurrent.STM
import System.Random
-- TMVars are transactional references. They can only be used in transactional actions.
-- They are either empty or contain one value. Taking an empty reference fails and
-- putting a value in a full reference fails. A transactional action only succeeds
-- when all the component actions succeed, else it rolls back and retries until it
-- succeeds.
-- The Int is just for display purposes.
type Fork = TMVar Int
newFork :: Int -> IO Fork
newFork i = newTMVarIO i
-- The basic transactional operations on forks
takeFork :: Fork -> STM Int
takeFork fork = takeTMVar fork
releaseFork :: Int -> Fork -> STM ()
releaseFork i fork = putTMVar fork i
type Name = String
runPhilosopher :: Name -> (Fork, Fork) -> IO ()
runPhilosopher name (left, right) = forever $ do
putStrLn (name ++ " is hungry.")
-- Run the transactional action atomically.
-- The type system ensures this is the only way to run transactional actions.
(leftNum, rightNum) <- atomically $ do
leftNum <- takeFork left
rightNum <- takeFork right
return (leftNum, rightNum)
putStrLn (name ++ " got forks " ++ show leftNum ++ " and " ++ show rightNum ++ " and is now eating.")
delay <- randomRIO (1,10)
threadDelay (delay * 1000000) -- 1, 10 seconds. threadDelay uses nanoseconds.
putStrLn (name ++ " is done eating. Going back to thinking.")
atomically $ do
releaseFork leftNum left
releaseFork rightNum right
delay <- randomRIO (1, 10)
threadDelay (delay * 1000000)
philosophers :: [String]
philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"]
main = do
forks <- mapM newFork [1..5]
let namedPhilosophers = map runPhilosopher philosophers
forkPairs = zip forks (tail . cycle $ forks)
philosophersWithForks = zipWith ($) namedPhilosophers forkPairs
putStrLn "Running the philosophers. Press enter to quit."
mapM_ forkIO philosophersWithForks
-- All threads exit when the main thread exits.
getLine
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Go | Go | package ddate
import (
"strconv"
"strings"
"time"
)
// Predefined formats for DiscDate.Format
const (
DefaultFmt = "Pungenday, Discord 5, 3131 YOLD"
OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131
Celebrate Mojoday`
)
// Formats passed to DiscDate.Format are protypes for formated dates.
// Format replaces occurrences of prototype elements (the constant strings
// listed here) with values corresponding to the date being formatted.
// If the date is St. Tib's Day, the string from the first date element
// through the last is replaced with "St. Tib's Day".
const (
protoLongSeason = "Discord"
protoShortSeason = "Dsc"
protoLongDay = "Pungenday"
protoShortDay = "PD"
protoOrdDay = "5"
protoCardDay = "5th"
protoHolyday = "Mojoday"
protoYear = "3131"
)
var (
longDay = []string{"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"}
shortDay = []string{"SM", "BT", "PD", "PP", "SO"}
longSeason = []string{
"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"}
holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"},
{"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}}
)
type DiscDate struct {
StTibs bool
Dayy int // zero based day of year, meaningless if StTibs is true
Year int // gregorian + 1166
}
func New(eris time.Time) DiscDate {
t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),
eris.Second(), eris.Nanosecond(), eris.Location())
bob := int(eris.Sub(t).Hours()) / 24
raw := eris.Year()
hastur := DiscDate{Year: raw + 1166}
if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {
if bob > 59 {
bob--
} else if bob == 59 {
hastur.StTibs = true
return hastur
}
}
hastur.Dayy = bob
return hastur
}
func (dd DiscDate) Format(f string) (r string) {
var st, snarf string
var dateElement bool
f6 := func(proto, wibble string) {
if !dateElement {
snarf = r
dateElement = true
}
if st > "" {
r = ""
} else {
r += wibble
}
f = f[len(proto):]
}
f4 := func(proto, wibble string) {
if dd.StTibs {
st = "St. Tib's Day"
}
f6(proto, wibble)
}
season, day := dd.Dayy/73, dd.Dayy%73
for f > "" {
switch {
case strings.HasPrefix(f, protoLongDay):
f4(protoLongDay, longDay[dd.Dayy%5])
case strings.HasPrefix(f, protoShortDay):
f4(protoShortDay, shortDay[dd.Dayy%5])
case strings.HasPrefix(f, protoCardDay):
funkychickens := "th"
if day/10 != 1 {
switch day % 10 {
case 0:
funkychickens = "st"
case 1:
funkychickens = "nd"
case 2:
funkychickens = "rd"
}
}
f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)
case strings.HasPrefix(f, protoOrdDay):
f4(protoOrdDay, strconv.Itoa(day+1))
case strings.HasPrefix(f, protoLongSeason):
f6(protoLongSeason, longSeason[season])
case strings.HasPrefix(f, protoShortSeason):
f6(protoShortSeason, shortSeason[season])
case strings.HasPrefix(f, protoHolyday):
if day == 4 {
r += holyday[season][0]
} else if day == 49 {
r += holyday[season][1]
}
f = f[len(protoHolyday):]
case strings.HasPrefix(f, protoYear):
r += strconv.Itoa(dd.Year)
f = f[4:]
default:
r += f[:1]
f = f[1:]
}
}
if st > "" {
r = snarf + st + r
}
return
} |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Java | Java |
import java.io.*;
import java.util.*;
public class Dijkstra {
private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),
};
private static final String START = "a";
private static final String END = "e";
public static void main(String[] args) {
Graph g = new Graph(GRAPH);
g.dijkstra(START);
g.printPath(END);
//g.printAllPaths();
}
}
class Graph {
private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges
/** One edge of the graph (only used by Graph constructor) */
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
/** One vertex of the graph, complete with mappings to neighbouring vertices */
public static class Vertex implements Comparable<Vertex>{
public final String name;
public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
public Vertex previous = null;
public final Map<Vertex, Integer> neighbours = new HashMap<>();
public Vertex(String name)
{
this.name = name;
}
private void printPath()
{
if (this == this.previous)
{
System.out.printf("%s", this.name);
}
else if (this.previous == null)
{
System.out.printf("%s(unreached)", this.name);
}
else
{
this.previous.printPath();
System.out.printf(" -> %s(%d)", this.name, this.dist);
}
}
public int compareTo(Vertex other)
{
if (dist == other.dist)
return name.compareTo(other.name);
return Integer.compare(dist, other.dist);
}
@Override public String toString()
{
return "(" + name + ", " + dist + ")";
}
}
/** Builds a graph from a set of edges */
public Graph(Edge[] edges) {
graph = new HashMap<>(edges.length);
//one pass to find all vertices
for (Edge e : edges) {
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
}
//another pass to set neighbouring vertices
for (Edge e : edges) {
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
//graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
}
}
/** Runs dijkstra using a specified source vertex */
public void dijkstra(String startName) {
if (!graph.containsKey(startName)) {
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();
// set-up vertices
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 : Integer.MAX_VALUE;
q.add(v);
}
dijkstra(q);
}
/** Implementation of dijkstra's algorithm using a binary heap. */
private void dijkstra(final NavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
//look at distances to each neighbour
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
v = a.getKey(); //the neighbour in this iteration
final int alternateDist = u.dist + a.getValue();
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
/** Prints a path from the source to the specified vertex */
public void printPath(String endName) {
if (!graph.containsKey(endName)) {
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
return;
}
graph.get(endName).printPath();
System.out.println();
}
/** Prints the path from the source to every vertex (output order is not guaranteed) */
public void printAllPaths() {
for (Vertex v : graph.values()) {
v.printPath();
System.out.println();
}
}
} |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Delphi | Delphi |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
digital_root_test_values: ARRAY [INTEGER_64]
-- Test values.
once
Result := <<670033, 39390, 588225, 393900588225>> -- base 10
end
digital_root_expected_result: ARRAY [INTEGER_64]
-- Expected result values.
once
Result := <<1, 6, 3, 9>> -- base 10
end
make
local
results: ARRAY [INTEGER_64]
i: INTEGER
do
from
i := 1
until
i > digital_root_test_values.count
loop
results := compute_digital_root (digital_root_test_values [i], 10)
if results [2] ~ digital_root_expected_result [i] then
print ("%N" + digital_root_test_values [i].out + " has additive persistence " + results [1].out + " and digital root " + results [2].out)
else
print ("Error in the calculation of the digital root of " + digital_root_test_values [i].out + ". Expected value: " + digital_root_expected_result [i].out + ", produced value: " + results [2].out)
end
i := i + 1
end
end
compute_digital_root (a_number: INTEGER_64; a_base: INTEGER): ARRAY [INTEGER_64]
-- Returns additive persistence and digital root of `a_number' using `a_base'.
require
valid_number: a_number >= 0
valid_base: a_base > 1
local
temp_num: INTEGER_64
do
create Result.make_filled (0, 1, 2)
from
Result [2] := a_number
until
Result [2] < a_base
loop
from
temp_num := Result [2]
Result [2] := 0
until
temp_num = 0
loop
Result [2] := Result [2] + (temp_num \\ a_base)
temp_num := temp_num // a_base
end
Result [1] := Result [1] + 1
end
end
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Pascal | Pascal | program MultRoot;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;
type
tMul3Dgt = array[0..999] of Uint32;
tMulRoot = record
mrNum,
mrMul,
mrPers : Uint64;
end;
const
Testnumbers : array[0..16] of Uint64 =(123321,7739,893,899998,
18446743999999999999,
//first occurence of persistence 0..11
0,10,25,39,77,679, 6788, 68889, 2677889,
26888999, 3778888999, 277777788888899);
var
Mul3Dgt : tMul3Dgt;
procedure InitMulDgt;
var
i,j,k,l : Int32;
begin
l := 999;
For i := 9 downto 0 do
For j := 9 downto 0 do
For k := 9 downto 0 do
Begin
Mul3Dgt[l] := i*j*k;
dec(l);
end;
end;
function GetMulDigits(n:Uint64):UInt64;inline;
var
pMul3Dgt :^tMul3Dgt;
q :Uint64;
begin
pMul3Dgt := @Mul3Dgt[0];
result := 1;
while n >= 1000 do
begin
q := n div 1000;
result *= pMul3Dgt^[n-1000*q];
n := q;
end;
If n>=100 then
result *= pMul3Dgt^[n]
else
if n>=10 then
result *= pMul3Dgt^[n+100]
else
result *= n;//Mul3Dgt[n+110]
end;
procedure GetMulRoot(var MulRoot:tMulRoot);
var
mr,
pers : UInt64;
Begin
pers := 0;
mr := MulRoot.mrNum;
while mr >=10 do
Begin
mr := GetMulDigits(mr);
inc(pers);
end;
MulRoot.mrMul:= mr;
MulRoot.mrPers:= pers;
end;
const
MaxDgtCount = 9;
var
//all initiated with 0
MulRoot:tMulRoot;
Sol : array[0..9,0..MaxDgtCount-1] of tMulRoot;
SolIds : array[0..9] of Int32;
i,idx,mr,AlreadyDone : Int32;
BEGIN
InitMulDgt;
AlreadyDone := 10;//0..9
MulRoot.mrNum := 0;
repeat
GetMulRoot(MulRoot);
mr := MulRoot.mrMul;
idx := SolIds[mr];
If idx<MaxDgtCount then
begin
Sol[mr,idx]:= MulRoot;
inc(idx);
SolIds[mr]:= idx;
if idx =MaxDgtCount then
dec(AlreadyDone);
end;
inc(MulRoot.mrNum);
until AlreadyDone = 0;
writeln('MDR: First');
For i := 0 to 9 do
begin
write(i:3,':');
For idx := 0 to MaxDgtCount-1 do
write(Sol[i,idx].mrNum:MaxDgtCount+1);
writeln;
end;
writeln;
writeln('number':20,' mulroot persitance');
For i := 0 to High(Testnumbers) do
begin
MulRoot.mrNum := Testnumbers[i];
GetMulRoot(MulRoot);
With MulRoot do
writeln(mrNum:20,mrMul:8,mrPers:8);
end;
{$IFDEF WINDOWS}
readln;
{$ENDIF}
END. |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #Java | Java | import java.util.*;
class DinesmanMultipleDwelling {
private static void generatePermutations(String[] apartmentDwellers, Set<String> set, String curPermutation) {
for (String s : apartmentDwellers) {
if (!curPermutation.contains(s)) {
String nextPermutation = curPermutation + s;
if (nextPermutation.length() == apartmentDwellers.length) {
set.add(nextPermutation);
} else {
generatePermutations(apartmentDwellers, set, nextPermutation);
}
}
}
}
private static boolean topFloor(String permutation, String person) { //Checks to see if the person is on the top floor
return permutation.endsWith(person);
}
private static boolean bottomFloor(String permutation, String person) {//Checks to see if the person is on the bottom floor
return permutation.startsWith(person);
}
public static boolean livesAbove(String permutation, String upperPerson, String lowerPerson) {//Checks to see if the person lives above the other person
return permutation.indexOf(upperPerson) > permutation.indexOf(lowerPerson);
}
public static boolean adjacent(String permutation, String person1, String person2) { //checks to see if person1 is adjacent to person2
return (Math.abs(permutation.indexOf(person1) - permutation.indexOf(person2)) == 1);
}
private static boolean isPossible(String s) {
/*
What this does should be obvious...proper explaination can be given if needed
Conditions here Switching any of these to ! or reverse will change what is given as a result
example
if(topFloor(s, "B"){
}
to
if(!topFloor(s, "B"){
}
or the opposite
if(!topFloor(s, "B"){
}
to
if(topFloor(s, "B"){
}
*/
if (topFloor(s, "B")) {//B is on Top Floor
return false;
}
if (bottomFloor(s, "C")) {//C is on Bottom Floor
return false;
}
if (topFloor(s, "F") || bottomFloor(s, "F")) {// F is on top or bottom floor
return false;
}
if (!livesAbove(s, "M", "C")) {// M does not live above C
return false;
}
if (adjacent(s, "S", "F")) { //S lives adjacent to F
return false;
}
return !adjacent(s, "F", "C"); //F does not live adjacent to C
}
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
generatePermutations(new String[]{"B", "C", "F", "M", "S"}, set, ""); //Generates Permutations
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {//Loops through iterator
String permutation = iterator.next();
if (!isPossible(permutation)) {//checks to see if permutation is false if so it removes it
iterator.remove();
}
}
for (String s : set) {
System.out.println("Possible arrangement: " + s);
/*
Prints out possible arranagement...changes depending on what you change in the "isPossible method"
*/
}
}
}
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Euphoria | Euphoria | function dotprod(sequence a, sequence b)
atom sum
a *= b
sum = 0
for n = 1 to length(a) do
sum += a[n]
end for
return sum
end function
? dotprod({1,3,-5},{4,-2,-1}) |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
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 <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
} |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #ALGOL_68 | ALGOL 68 | BEGIN # find all primes with strictly decreasing digits #
PR read "primes.incl.a68" PR # include prime utilities #
PR read "rows.incl.a68" PR # include array utilities #
[ 1 : 512 ]INT primes; # there will be at most 512 (2^9) primes #
INT p count := 0; # number of primes found so far #
FOR d1 FROM 0 TO 1 DO
INT n1 = IF d1 = 1 THEN 9 ELSE 0 FI;
FOR d2 FROM 0 TO 1 DO
INT n2 = IF d2 = 1 THEN ( n1 * 10 ) + 8 ELSE n1 FI;
FOR d3 FROM 0 TO 1 DO
INT n3 = IF d3 = 1 THEN ( n2 * 10 ) + 7 ELSE n2 FI;
FOR d4 FROM 0 TO 1 DO
INT n4 = IF d4 = 1 THEN ( n3 * 10 ) + 6 ELSE n3 FI;
FOR d5 FROM 0 TO 1 DO
INT n5 = IF d5 = 1 THEN ( n4 * 10 ) + 5 ELSE n4 FI;
FOR d6 FROM 0 TO 1 DO
INT n6 = IF d6 = 1 THEN ( n5 * 10 ) + 4 ELSE n5 FI;
FOR d7 FROM 0 TO 1 DO
INT n7 = IF d7 = 1 THEN ( n6 * 10 ) + 3 ELSE n6 FI;
FOR d8 FROM 0 TO 1 DO
INT n8 = IF d8 = 1 THEN ( n7 * 10 ) + 2 ELSE n7 FI;
FOR d9 FROM 0 TO 1 DO
INT n9 = IF d9 = 1 THEN ( n8 * 10 ) + 1 ELSE n8 FI;
IF n9 > 0 THEN
IF is probably prime( n9 ) THEN
# have a prime with strictly descending digits #
primes[ p count +:= 1 ] := n9
FI
FI
OD
OD
OD
OD
OD
OD
OD
OD
OD;
QUICKSORT primes FROMELEMENT 1 TOELEMENT p count; # sort the primes #
# display the primes #
FOR i TO p count DO
print( ( " ", whole( primes[ i ], -8 ) ) );
IF i MOD 10 = 0 THEN print( ( newline ) ) FI
OD
END |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #ALGOL_W | ALGOL W | begin % determine if two triangles overlap %
record Point ( real x, y );
record Triangle ( reference(Point) p1, p2, p3 );
procedure WritePoint ( reference(Point) value p ) ;
writeon( r_w := 3, r_d := 1, r_format := "A", s_w := 0, "(", x(p), ", ", y(p), ")" );
procedure WriteTriangle ( reference(Triangle) value t ) ;
begin
WritePoint( p1(t) );
writeon( ", " );
WritePoint( p2(t) );
writeon( ", " );
WritePoint( p3(t) )
end WriteTriangle ;
real procedure Det2D ( reference(Triangle) value t ) ;
( ( x(p1(t)) * ( y(p2(t)) - y(p3(t)) ) )
+ ( x(p2(t)) * ( y(p3(t)) - y(p1(t)) ) )
+ ( x(p3(t)) * ( y(p1(t)) - y(p2(t)) ) )
);
procedure CheckTriWinding ( reference(Triangle) value t ; logical value allowReversed ) ;
begin
real detTri;
detTri := Det2D(t);
if detTri < 0.0 then begin
if allowReversed then begin
reference(Point) a;
a := p3(t);
p3(t) := p2(t);
p2(t) := a
end
else begin
write( "triangle has wrong winding direction" );
assert( false )
end
end if_detTri_lt_0
end CheckTriWinding ;
logical procedure BoundaryCollideChk( reference(Triangle) value t ; real value eps ) ; Det2D( t ) < eps ;
logical procedure BoundaryDoesntCollideChk( reference(Triangle) value t ; real value eps ) ; Det2D( t ) <= eps ;
logical procedure TriTri2D( reference(Triangle) value t1, t2 ; real value eps ; logical value allowReversed, onBoundary ) ;
begin
logical procedure ChkEdge( reference(Triangle) value t ) ;
if onBoundary then % Points on the boundary are considered as colliding %
BoundaryCollideChk( t, eps )
else % Points on the boundary are not considered as colliding %
BoundaryDoesntCollideChk( t, eps )
;
reference(Point) array lp1, lp2 ( 0 :: 2 );
logical overlap;
overlap := true;
% Triangles must be expressed anti-clockwise %
CheckTriWinding( t1, allowReversed );
CheckTriWinding( t2, allowReversed );
lp1( 0 ) := p1(t1); lp1( 1 ) := p2(t1); lp1( 2 ) := p3(t1);
lp2( 0 ) := p1(t2); lp2( 1 ) := p2(t2); lp2( 2 ) := p3(t2);
% for each edge E of t1 %
for i := 0 until 2 do begin
integer j;
j := ( i + 1 ) rem 3;
% Check all points of t2 lay on the external side of edge E. %
% if they do, the triangles do not overlap. %
if ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 0 ) ) )
and ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 1 ) ) )
and ChkEdge( Triangle( lp1( i ), lp1( j ), lp2( 2 ) ) )
then begin
overlap := false;
goto return
end
end for_i ;
% for each edge E of t2 %
for i := 0 until 2 do begin
integer j;
j := ( i + 1 ) rem 3;
% Check all points of t1 lay on the external side of edge E. %
% if they do, the triangles do not overlap. %
if ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 0 ) ) )
and ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 1 ) ) )
and ChkEdge( Triangle( lp2( i ), lp2( j ), lp1( 2 ) ) )
then begin
overlap := false;
goto return
end
end for_i;
% if we get here, The triangles overlap %
return: overlap
end TriTri2D ;
procedure CheckOverlap( reference(Triangle) value t1, t2
; real value eps
; logical value allowReversed, onBoundary
) ;
begin
write( "Triangles " );
WriteTriangle( t1 );
writeon( " and " );
WriteTriangle( t2 );
writeon( if TriTri2D( t1, t2, eps, allowReversed, onBoundary ) then " overlap" else " do not overlap" );
end CheckOverlap ;
begin % main %
reference(Triangle) t1, t2;
t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 5.0 ) );
t2 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 6.0 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 0.0, 5.0 ), Point( 5.0, 0.0 ) );
t2 := Triangle( Point( 0.0, 0.0 ), Point( 0.0, 5.0 ), Point( 5.0, 0.0 ) );
CheckOverlap(t1, t2, 0.0, true, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 0.0, 5.0 ) );
t2 := Triangle( Point( -10.0, 0.0 ), Point( -5.0, 0.0 ), Point( -1.0, 6.0 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 5.0, 0.0 ), Point( 2.5, 5.0 ) );
t2 := Triangle( Point( 0.0, 4.0 ), Point( 2.5, -1.0 ), Point( 5.0, 4.0 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 1.0 ), Point( 0.0, 2.0 ) );
t2 := Triangle( Point( 2.0, 1.0 ), Point( 3.0, 0.0 ), Point( 3.0, 2.0 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 1.0 ), Point( 0.0, 2.0 ) );
t2 := Triangle( Point( 2.0, 1.0 ), Point( 3.0, -2.0 ), Point( 3.0, 4.0 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 0.0 ), Point( 0.0, 1.0 ) );
t2 := Triangle( Point( 1.0, 0.0 ), Point( 2.0, 0.0 ), Point( 1.0, 1.1 ) );
CheckOverlap( t1, t2, 0.0, false, true );
t1 := Triangle( Point( 0.0, 0.0 ), Point( 1.0, 0.0 ), Point( 0.0, 1.0 ) );
t2 := Triangle( Point( 1.0, 0.0 ), Point( 2.0, 0.0 ), Point( 1.0, 1.1 ) );
CheckOverlap( t1, t2, 0.0, false, false );
end
end. |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
double det_in(double **in, int n, int perm)
{
if (n == 1) return in[0][0];
double sum = 0, *m[--n];
for (int i = 0; i < n; i++)
m[i] = in[i + 1] + 1;
for (int i = 0, sgn = 1; i <= n; i++) {
sum += sgn * (in[i][0] * det_in(m, n, perm));
if (i == n) break;
m[i] = in[i] + 1;
if (!perm) sgn = -sgn;
}
return sum;
}
/* wrapper function */
double det(double *in, int n, int perm)
{
double *m[n];
for (int i = 0; i < n; i++)
m[i] = in + (n * i);
return det_in(m, n, perm);
}
int main(void)
{
double x[] = { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24 };
printf("det: %14.12g\n", det(x, 5, 0));
printf("perm: %14.12g\n", det(x, 5, 1));
return 0;
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Ada | Ada | -- Divide By Zero Detection
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
procedure Divide_By_Zero is
Fnum : Float := 1.0;
Fdenom : Float := 0.0;
Fresult : Float;
Inum : Integer := 1;
Idenom : Integer := 0;
Iresult : Integer;
begin
begin
Put("Integer divide by zero: ");
Iresult := Inum / Idenom;
Put(Item => Iresult);
exception
when Constraint_Error =>
Put("Division by zero detected.");
end;
New_Line;
Put("Floating point divide by zero: ");
Fresult := Fnum / Fdenom;
if Fresult > Float'Last or Fresult < Float'First then
Put("Division by zero detected (infinite value).");
else
Put(Item => Fresult, Aft => 9, Exp => 0);
end if;
New_Line;
end Divide_By_Zero; |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Aime | Aime | integer
divide(integer n, integer d)
{
return n / d;
}
integer
can_divide(integer n, integer d)
{
return !trap(divide, n, d);
}
integer
main(void)
{
if (!can_divide(9, 0)) {
o_text("Division by zero.\n");
}
return 0;
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
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 | PROC is numeric = (REF STRING string) BOOL: (
BOOL out := TRUE;
PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE);
FILE memory;
associate(memory, string);
on value error(memory, call back false);
on logical file end(memory, call back false);
UNION (INT, REAL, COMPL) numeric:=0.0;
# use a FORMAT pattern instead of a regular expression #
getf(memory, ($gl$, numeric));
out
);
test:(
STRING
s1 := "152",
s2 := "-3.1415926",
s3 := "Foo123";
print((
s1, " results in ", is numeric(s1), new line,
s2, " results in ", is numeric(s2), new line,
s3, " results in ", is numeric(s3), new line
))
)
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
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 | class Node{
fcn init(_value,_prev=Void,_next=Void)
{ var value=_value, prev=_prev, next=_next; }
fcn toString{ value.toString() }
fcn append(value){ // loops not allowed: create a new Node
b,c := Node(value,self,next),next;
next=b;
if(c) c.prev=b;
b
}
fcn delete{
if(prev) prev.next=next;
if(next) next.prev=prev;
self
}
fcn last { n,p := self,self; while(n){ p,n = n,n.next } p }
fcn first { n,p := self,self; while(n){ p,n = n,n.prev } p }
fcn walker(forward=True){
dir:=forward and "next" or "prev";
Walker(fcn(rn,dir){
if(not (n:=rn.value)) return(Void.Stop);
rn.set(n.setVar(dir));
n.value;
}.fp(Ref(self),dir))
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
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.4"
use framework "Foundation"
use scripting additions
on run
script showSource
on |λ|(s)
quoted("'", s) & " (" & length of s & ")"
end |λ|
end script
script showDuplicate
on |λ|(mb)
script go
on |λ|(tpl)
set {c, ixs} to tpl
quoted("'", c) & " at " & intercalate(", ", ixs)
end |λ|
end script
maybe("None", go, mb)
end |λ|
end script
fTable("Indices (1-based) of any duplicated characters:\n", ¬
showSource, showDuplicate, ¬
duplicatedCharIndices, ¬
{"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"})
end run
------------------CHARACTER DUPLICATIONS-------------------
-- duplicatedCharIndices :: String -> Maybe (Char, [Int])
on duplicatedCharIndices(s)
script positionRecord
on |λ|(dct, c, i)
set k to (id of c) as string
script additional
on |λ|(xs)
insertDict(k, xs & i, dct)
end |λ|
end script
maybe(insertDict(k, {i}, dct), additional, lookupDict(k, dct))
end |λ|
end script
script firstDuplication
on |λ|(sofar, idxs)
set {iCode, xs} to idxs
if 1 < length of xs then
script earliest
on |λ|(kxs)
if item 1 of xs < (item 1 of (item 2 of kxs)) then
Just({chr(iCode), xs})
else
sofar
end if
end |λ|
end script
maybe(Just({chr(iCode), xs}), earliest, sofar)
else
sofar
end if
end |λ|
end script
foldl(firstDuplication, Nothing(), ¬
assocs(foldl(positionRecord, {name:""}, chars(s))))
end duplicatedCharIndices
--------------------------GENERIC--------------------------
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values, possibly of two different types.
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- assocs :: Map k a -> [(k, a)]
on assocs(m)
script go
on |λ|(k)
set mb to lookupDict(k, m)
if true = |Nothing| of mb then
{}
else
{{k, |Just| of mb}}
end if
end |λ|
end script
concatMap(go, keys(m))
end assocs
-- keys :: Dict -> [String]
on keys(rec)
(current application's ¬
NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list
end keys
-- chr :: Int -> Char
on chr(n)
character id n
end chr
-- chars :: String -> [Char]
on chars(s)
characters of s
end chars
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
mf's |λ|(mg's |λ|(x))
end |λ|
end script
end compose
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
return acc
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- 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
-- fst :: (a, b) -> a
on fst(tpl)
if class of tpl is record then
|1| of tpl
else
item 1 of tpl
end if
end fst
-- fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
on fTable(s, xShow, fxShow, f, xs)
set ys to map(xShow, xs)
set w to maximum(map(my |length|, ys))
script arrowed
on |λ|(a, b)
justifyRight(w, space, a) & " -> " & b
end |λ|
end script
s & linefeed & unlines(zipWith(arrowed, ¬
ys, map(compose(fxShow, f), xs)))
end fTable
-- insertDict :: String -> a -> Dict -> Dict
on insertDict(k, v, rec)
tell current application
tell dictionaryWithDictionary_(rec) of its NSMutableDictionary
its setValue:v forKey:(k as string)
it as record
end tell
end tell
end insertDict
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set str to xs as text
set my text item delimiters to dlm
str
end intercalate
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- lookupDict :: a -> Dict -> Maybe b
on lookupDict(k, dct)
-- Just the value of k in the dictionary,
-- or Nothing if k is not found.
set ca to current application
set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k
if missing value ≠ v then
Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))
else
Nothing()
end if
end lookupDict
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of 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
-- maximum :: Ord a => [a] -> a
on maximum(xs)
script
on |λ|(a, b)
if a is missing value or b > a then
b
else
a
end if
end |λ|
end script
foldl(result, missing value, xs)
end maximum
-- maybe :: b -> (a -> b) -> Maybe a -> b
on maybe(v, f, mb)
-- The 'maybe' function takes a default value, a function, and a 'Maybe'
-- value. If the 'Maybe' value is 'Nothing', the function returns the
-- default value. Otherwise, it applies the function to the value inside
-- the 'Just' and returns the result.
if Nothing of mb then
v
else
tell mReturn(f) to |λ|(Just of mb)
end if
end maybe
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- quoted :: Char -> String -> String
on quoted(c, s)
-- string flanked on both sides
-- by a specified quote character.
c & s & c
end quoted
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
zipWith(Tuple, xs, ys)
end zip
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BCPL | BCPL | get "libhdr"
// Collapse a string
let collapse(in, out) = valof
$( let o = 0
for i = 1 to in%0
unless i>1 & in%i = in%(i-1)
$( o := o + 1
out%o := in%i
$)
out%0 := o
resultis out
$)
// Print string with brackets and length
let brackets(s) be
writef("%N: <<<%S>>>*N", s%0, s)
// Print original and collapsed version
let show(s) be
$( let v = vec 1+255/BYTESPERWORD
brackets(s)
brackets(collapse(s, v))
wrch('*N')
$)
let start() be
$( show("")
show("*"If I were two-faced, would I be wearing this one?*" --- Abraham Lincoln ")
show("..1111111111111111111111111111111111111111111111111111111111111111111788")
show("I never give 'em hell, I just tell the truth, and they think it's hell. ")
show(" --- Harry S Truman ")
$) |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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 | ( colapse
= previous
. str
$ ( vap
$ ( (
=
. !arg:!previous&
| !arg:?previous
)
. !arg
)
)
)
& ( testcolapse
= len
. (len=.@(!arg:? [?arg)&!arg)
& out$(str$(««« !arg "»»» " len$!arg))
& colapse$!arg:?arg
& out$(str$(««« !arg "»»» " len$!arg))
)
& testcolapse$
& testcolapse
$ "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
& testcolapse
$ "..1111111111111111111111111111111111111111111111111111111111111117777888"
& testcolapse
$ "I never give 'em hell, I just tell the truth, and they think it's hell. "
& testcolapse
$ " --- Harry S Truman " |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
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<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
/*
Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.
Comment this out if testing on a compiler where it is already defined.
*/
int strcmpi(char* str1,char* str2){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #REXX | REXX | /* REXX */
Numeric Digits 30
Call test '9 4 6 6'
Call test '5 10 6 7'
Exit
test:
Parse Arg w1 s1 w2 s2
plist1=pp(w1,s1)
p1.=0
Do x=w1 To w1*s1
Parse Var plist1 p1.x plist1
End
plist2=pp(w2,s2)
p2.=0
Do x=w2 To w2*s2
Parse Var plist2 p2.x plist2
End
p2low.=0
Do x=w1 To w1*s1
Do y=0 To x-1
p2low.x=p2low.x+p2.y
End
End
pwin1=0
Do x=w1 To w1*s1
pwin1=pwin1+p1.x*p2low.x
End
Say 'Player 1 has' w1 'dice with' s1 'sides each'
Say 'Player 2 has' w2 'dice with' s2 'sides each'
Say 'Probability for player 1 to win:' pwin1
Say ''
Return
pp: Procedure
/*---------------------------------------------------------------------
* Compute and return the probabilities to get a sum x
* when throwing w dice each having s sides (marked from 1 to s)
*--------------------------------------------------------------------*/
Parse Arg w,s
str=''
cnt.=0
Do wi=1 To w
str=str||'Do v'wi'=1 To' s';'
End
str=str||'sum='
Do wi=1 To w-1
str=str||'v'wi'+'
End
str=str||'v'w';'
str=str||'cnt.'sum'=cnt.'sum'+1;'
Do wi=1 To w
str=str||'End;'
End
Interpret str
psum=0
Do x=0 To w*s
p.x=cnt.x/(s**w)
psum=psum+p.x
End
res=''
Do x=w To s*w
res=res p.x
End
Return res |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BCPL | BCPL | get "libhdr"
let diffchar(s) = valof
$( for i=2 to s%0
unless s%i = s%1 resultis i
resultis 0
$)
let show(s) be
$( let i = diffchar(s)
writef("*"%S*" (length %N): ", s, s%0)
test i=0
do writes("all the same.*N")
or writef("'%C' at index %N.*N", s%i, i)
$)
let start() be
$( show("")
show(" ")
show("2")
show("333")
show(".55")
show("tttTTT")
show("4444 444k")
$) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
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<string.h>
#include<stdio.h>
int main(int argc,char** argv)
{
int i,len;
char reference;
if(argc>2){
printf("Usage : %s <Test String>\n",argv[0]);
return 0;
}
if(argc==1||strlen(argv[1])==1){
printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1]));
return 0;
}
reference = argv[1][0];
len = strlen(argv[1]);
for(i=1;i<len;i++){
if(argv[1][i]!=reference){
printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1);
return 0;
}
}
printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len);
return 0;
}
|
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Icon_and_Unicon | Icon and Unicon | global forks, names
procedure main(A)
names := ["Aristotle","Kant","Spinoza","Marks","Russell"]
write("^C to terminate")
nP := *names
forks := [: |mutex([])\nP :]
every p := !nP do thread philosopher(p)
delay(-1)
end
procedure philosopher(n)
f1 := forks[min(n, n%*forks+1)]
f2 := forks[max(n, n%*forks+1)]
repeat {
write(names[n]," thinking")
delay(1000*?5)
write(names[n]," hungry")
repeat {
fork1 := lock(f1)
if fork2 := trylock(f2) then {
write(names[n]," eating")
delay(1000*?5)
break (unlock(fork2), unlock(fork1)) # full
}
unlock(fork1) # Free first fork and go back to waiting
}
}
end |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Haskell | Haskell | import Data.Time (isLeapYear)
import Data.Time.Calendar.MonthDay (monthAndDayToDayOfYear)
import Text.Printf (printf)
type Year = Integer
type Day = Int
type Month = Int
data DDate = DDate Weekday Season Day Year
| StTibsDay Year deriving (Eq, Ord)
data Season = Chaos
| Discord
| Confusion
| Bureaucracy
| TheAftermath
deriving (Show, Enum, Eq, Ord, Bounded)
data Weekday = Sweetmorn
| Boomtime
| Pungenday
| PricklePrickle
| SettingOrange
deriving (Show, Enum, Eq, Ord, Bounded)
instance Show DDate where
show (StTibsDay y) = printf "St. Tib's Day, %d YOLD" y
show (DDate w s d y) = printf "%s, %s %d, %d YOLD" (show w) (show s) d y
fromYMD :: (Year, Month, Day) -> DDate
fromYMD (y, m, d)
| leap && dayOfYear == 59 = StTibsDay yold
| leap && dayOfYear >= 60 = mkDDate $ dayOfYear - 1
| otherwise = mkDDate dayOfYear
where
yold = y + 1166
dayOfYear = monthAndDayToDayOfYear leap m d - 1
leap = isLeapYear y
mkDDate dayOfYear = DDate weekday season dayOfSeason yold
where
weekday = toEnum $ dayOfYear `mod` 5
season = toEnum $ dayOfYear `div` 73
dayOfSeason = 1 + dayOfYear `mod` 73 |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #JavaScript | JavaScript |
const dijkstra = (edges,source,target) => {
const Q = new Set(),
prev = {},
dist = {},
adj = {}
const vertex_with_min_dist = (Q,dist) => {
let min_distance = Infinity,
u = null
for (let v of Q) {
if (dist[v] < min_distance) {
min_distance = dist[v]
u = v
}
}
return u
}
for (let i=0;i<edges.length;i++) {
let v1 = edges[i][0],
v2 = edges[i][1],
len = edges[i][2]
Q.add(v1)
Q.add(v2)
dist[v1] = Infinity
dist[v2] = Infinity
if (adj[v1] === undefined) adj[v1] = {}
if (adj[v2] === undefined) adj[v2] = {}
adj[v1][v2] = len
adj[v2][v1] = len
}
dist[source] = 0
while (Q.size) {
let u = vertex_with_min_dist(Q,dist),
neighbors = Object.keys(adj[u]).filter(v=>Q.has(v)) //Neighbor still in Q
Q.delete(u)
if (u===target) break //Break when the target has been found
for (let v of neighbors) {
let alt = dist[u] + adj[u][v]
if (alt < dist[v]) {
dist[v] = alt
prev[v] = u
}
}
}
{
let u = target,
S = [u],
len = 0
while (prev[u] !== undefined) {
S.unshift(prev[u])
len += adj[u][prev[u]]
u = prev[u]
}
return [S,len]
}
}
//Testing algorithm
let graph = []
graph.push(["a", "b", 7])
graph.push(["a", "c", 9])
graph.push(["a", "f", 14])
graph.push(["b", "c", 10])
graph.push(["b", "d", 15])
graph.push(["c", "d", 11])
graph.push(["c", "f", 2])
graph.push(["d", "e", 6])
graph.push(["e", "f", 9])
let [path,length] = dijkstra(graph, "a", "e");
console.log(path) //[ 'a', 'c', 'f', 'e' ]
console.log(length) //20
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
digital_root_test_values: ARRAY [INTEGER_64]
-- Test values.
once
Result := <<670033, 39390, 588225, 393900588225>> -- base 10
end
digital_root_expected_result: ARRAY [INTEGER_64]
-- Expected result values.
once
Result := <<1, 6, 3, 9>> -- base 10
end
make
local
results: ARRAY [INTEGER_64]
i: INTEGER
do
from
i := 1
until
i > digital_root_test_values.count
loop
results := compute_digital_root (digital_root_test_values [i], 10)
if results [2] ~ digital_root_expected_result [i] then
print ("%N" + digital_root_test_values [i].out + " has additive persistence " + results [1].out + " and digital root " + results [2].out)
else
print ("Error in the calculation of the digital root of " + digital_root_test_values [i].out + ". Expected value: " + digital_root_expected_result [i].out + ", produced value: " + results [2].out)
end
i := i + 1
end
end
compute_digital_root (a_number: INTEGER_64; a_base: INTEGER): ARRAY [INTEGER_64]
-- Returns additive persistence and digital root of `a_number' using `a_base'.
require
valid_number: a_number >= 0
valid_base: a_base > 1
local
temp_num: INTEGER_64
do
create Result.make_filled (0, 1, 2)
from
Result [2] := a_number
until
Result [2] < a_base
loop
from
temp_num := Result [2]
Result [2] := 0
until
temp_num = 0
loop
Result [2] := Result [2] + (temp_num \\ a_base)
temp_num := temp_num // a_base
end
Result [1] := Result [1] + 1
end
end
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Perl | Perl | use warnings;
use strict;
sub mdr {
my $n = shift;
my($count, $mdr) = (0, $n);
while ($mdr > 9) {
my($m, $dm) = ($mdr, 1);
while ($m) {
$dm *= $m % 10;
$m = int($m/10);
}
$mdr = $dm;
$count++;
}
($count, $mdr);
}
print "Number: (MP, MDR)\n====== =========\n";
foreach my $n (123321, 7739, 893, 899998) {
printf "%6d: (%d, %d)\n", $n, mdr($n);
}
print "\nMP: [n0..n4]\n== ========\n";
foreach my $target (0..9) {
my $i = 0;
my @n = map { $i++ while (mdr($i))[1] != $target; $i++; } 1..5;
print " $target: [", join(", ", @n), "]\n";
} |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #JavaScript | JavaScript | (() => {
'use strict';
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
// range :: Int -> Int -> [Int]
const range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// and :: [Bool] -> Bool
const and = xs => {
let i = xs.length;
while (i--)
if (!xs[i]) return false;
return true;
}
// nubBy :: (a -> a -> Bool) -> [a] -> [a]
const nubBy = (p, xs) => {
const x = xs.length ? xs[0] : undefined;
return x !== undefined ? [x].concat(
nubBy(p, xs.slice(1)
.filter(y => !p(x, y)))
) : [];
}
// PROBLEM DECLARATION
const floors = range(1, 5);
return concatMap(b =>
concatMap(c =>
concatMap(f =>
concatMap(m =>
concatMap(s =>
and([ // CONDITIONS
nubBy((a, b) => a === b, [b, c, f, m, s]) // all floors singly occupied
.length === 5,
b !== 5, c !== 1, f !== 1, f !== 5,
m > c, Math.abs(s - f) > 1, Math.abs(c - f) > 1
]) ? [{
Baker: b,
Cooper: c,
Fletcher: f,
Miller: m,
Smith: s
}] : [],
floors), floors), floors), floors), floors);
// --> [{"Baker":3, "Cooper":2, "Fletcher":4, "Miller":5, "Smith":1}]
})(); |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #F.23 | F# | let dot_product (a:array<'a>) (b:array<'a>) =
if Array.length a <> Array.length b then failwith "invalid argument: vectors must have the same lengths"
Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.