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/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
| #Maxima | Maxima | a: matrix([2, 9, 4], [7, 5, 3], [6, 1, 8])$
determinant(a);
-360
permanent(a);
900 |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П4 ИПE П2 КИП0 ИП0 П1 С/П ИП4 / КП2
L1 06 ИПE П3 ИП0 П1 Сx КП2 L1 17
ИП0 ИП2 + П1 П2 ИП3 - x#0 34 С/П
ПП 80 БП 21 КИП0 ИП4 С/П КИП2 - *
П4 ИП0 П3 x#0 35 Вx С/П КИП2 - <->
/ КП1 L3 45 ИП1 ИП0 + П3 ИПE П1
П2 КИП1 /-/ ПП 80 ИП3 + П3 ИП1 -
x=0 61 ИП0 П1 КИП3 КП2 L1 74 БП 12
ИП0 <-> ^ КИП3 * КИП1 + КП2 -> L0
82 -> П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.
| #Haskell | Haskell | import qualified Control.Exception as C
check x y = C.catch (x `div` y `seq` return False)
(\_ -> return True) |
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
| #ERRE | ERRE |
PROGRAM NUMERIC
PROCEDURE IS_NUMERIC(S$->ANS%)
LOCAL T1,T1$
T1=VAL(S$)
T1$=STR$(T1)
ANS%=(T1$=S$) OR T1$=" "+S$
END PROCEDURE
BEGIN
PRINT(CHR$(12);)
INPUT("Enter a string",S$)
IS_NUMERIC(S$->ANS%)
IF ANS% THEN PRINT("is num") ELSE PRINT("not num")
END PROGRAM
|
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
| #Euphoria | Euphoria | include get.e
function is_numeric(sequence s)
sequence val
val = value(s)
return val[1]=GET_SUCCESS and atom(val[2])
end function |
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
| #jq | jq | # Emit null if there is no duplicate, else [c, [ix1, ix2]]
def firstDuplicate:
label $out
| foreach explode[] as $i ({ix: -1};
.ix += 1
| .ix as $ix
| .iu = ([$i] | implode)
| .[.iu] += [ $ix] ;
if .[.iu]|length == 2 then [.iu, .[.iu]], break $out else empty end )
// null ; |
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
| #Julia | Julia | arr(s) = [c for c in s]
alldup(a) = filter(x -> length(x) > 1, [findall(x -> x == a[i], a) for i in 1:length(a)])
firstduplicate(s) = (a = arr(s); d = alldup(a); isempty(d) ? nothing : first(d))
function testfunction(strings)
println("String | Length | All Unique | First Duplicate | Positions\n" *
"-------------------------------------------------------------------------------------")
for s in strings
n = firstduplicate(s)
a = arr(s)
println(rpad(s, 38), rpad(length(s), 11), n == nothing ? "yes" :
rpad("no $(a[n[1]])", 26) * rpad(n[1], 4) * "$(n[2])")
end
end
testfunction([
"",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡",
])
|
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
| #Quackery | Quackery | [ false -1 rot
witheach
[ 2dup = iff
[ drop dip not
conclude ]
else nip ]
drop ] is collapsible ( $ --> b )
[ [] -1 rot
witheach
[ 2dup = iff drop
else
[ nip dup dip join ] ]
drop ] is collapse ( $ --> $ )
[ dup collapsible iff
[ dup collapse
swap 2 ]
else
[ say "(Not collapsible.)" cr
1 ]
times
[ say "<<<"
dup echo$
say ">>>" cr
say " Length: "
size echo
say " characters" cr cr ]
cr ] is task ( $ --> )
$ "" task
$ '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ' task
$ "..1111111111111111111111111111111111111111111111111111111111111117777888" task
$ "I never give 'em hell, I just tell the truth, and they think it's hell. " task
$ " --- Harry S Truman " task |
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
| #R | R | collapse_string <- function(string){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable)))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable)==0) break
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
collapsed_string <- paste(str_iterable[detect],collapse = "")
message(paste0("Collapsed string: ", "<<<",collapsed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
test_strings <- c(
"",
"'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 ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"Ciao Mamma, guarda come mi diverto!!"
)
for(test in test_strings){
collapse_string(test)
}
|
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
| #Racket | Racket | #lang racket
(define (collapse text)
(if (< (string-length text) 2)
text
(string-append
(if (equal? (substring text 0 1) (substring text 1 2))
"" (substring text 0 1))
(collapse (substring text 1)))))
; Test cases
(define tcs
'(""
"\"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 "
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
"headmistressship"
"aardvark"
"😍😀🙌💃😍😍😍🙌"))
(for ([text tcs])
(let ([collapsed (collapse text)])
(display (format "Original (size ~a): «««~a»»»\nCollapsed (size ~a): «««~a»»»\n\n"
(string-length text) text
(string-length collapsed) collapsed))))
|
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
| #OCaml | OCaml |
(* Task: Determine if a string has all the same characters *)
(* Create a function that determines whether all characters in a string are identical,
or returns the index of first different character.
Using the option type here to combine the functionality.
*)
let str_first_diff_char (s : string) : int option =
let len = String.length s in
if len = 0
then None
else
let first = s.[0] in
let rec helper idx =
if idx >= len
then None
else if s.[idx] = first
then helper (idx + 1)
else Some idx
in
helper 1
;;
(* Task display: using format of Ada
Example:
Input = "333", length = 3
All characters are the same.
Input = ".55", length = 3
First difference at position 2, character = '5', hex = 16#35#
*)
let format_answer s =
let first_line = "Input = \"" ^ s ^ "\", length = " ^ (s |> String.length |> string_of_int) in
let second_line = match str_first_diff_char s with
| None -> " All characters are the same."
| Some idx -> Printf.sprintf " First difference at position %d, character = %C, hex = %#x" (idx+1) s.[idx] (Char.code s.[idx])
in
print_endline first_line; print_endline second_line
;;
let _ =
[""; " "; "2"; "333"; ".55"; "tttTTT"; "4444 444k"]
|> List.iter format_answer
;;
|
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.
| #PureBasic | PureBasic | Macro Tell(Mutex, Message) ; Make a macro to easy send info back to main thread
LockMutex(Mutex)
LastElement(Queue())
AddElement(Queue())
Queue() = Message
SignalSemaphore(Semaphore)
UnlockMutex(Mutex)
EndMacro
;Set up a data structure to pass needed info into the threads
Structure Thread_Parameters
Name.s
fork1.i
fork2.i
EndStructure
; Declare function to be used
Declare.i TryFork(n)
Declare PutDownFork(n)
Declare Invite(Namn.s, Fork1, Fork2)
Declare _philosophers(*arg.Thread_Parameters)
Global Semaphore = CreateSemaphore()
Global Mutex1 = CreateMutex() ; Eg. fork 1
Global Mutex2 = CreateMutex() ; Eg. fork 2
Global Mutex3 = CreateMutex() ; Eg. fork 3
Global Mutex4 = CreateMutex() ; Eg. fork 4
Global Mutex5 = CreateMutex() ; Eg. fork 5
Global Mutex_main = CreateMutex() ; locking communication with the main thread which do all output.
Global NewList Queue.s()
If OpenConsole()
Invite("Aristotle",1,2) ; Get all Philosophers activated
Invite("Kant", 2,3)
Invite("Spinoza", 3,4)
Invite("Marx", 4,5)
Invite("Russell", 5,1)
CompilerIf #PB_Compiler_OS=#PB_OS_Windows
SetConsoleTitle_("Dining philosophers, by Jofur") ; Using a Windows-API here, so checking before
CompilerEndIf
; Wait and see if any Philosophers want to tell me anything
Repeat
WaitSemaphore(Semaphore)
LockMutex(Mutex_main)
ForEach Queue()
PrintN( Queue() ) ; Print what the Philosopher(s) told me
i-1
Next Queue()
ClearList(Queue())
UnlockMutex(Mutex_main)
ForEver
EndIf
Procedure TryFork(n) ; Se is fork #n is free and if so pick it up
Select n
Case 1: ProcedureReturn TryLockMutex(Mutex1)
Case 2: ProcedureReturn TryLockMutex(Mutex2)
Case 3: ProcedureReturn TryLockMutex(Mutex3)
Case 4: ProcedureReturn TryLockMutex(Mutex4)
Default:ProcedureReturn TryLockMutex(Mutex5)
EndSelect
EndProcedure
Procedure PutDownFork(n) ; put down fork #n and free it to be used by neighbors.
Select n
Case 1: UnlockMutex(Mutex1)
Case 2: UnlockMutex(Mutex2)
Case 3: UnlockMutex(Mutex3)
Case 4: UnlockMutex(Mutex4)
Default:UnlockMutex(Mutex5)
EndSelect
EndProcedure
Procedure Invite(Namn.s, Fork1, Fork2)
Protected *arg.Thread_Parameters ;create the structure containing the parameters
Protected Thread
*arg = AllocateMemory(SizeOf(Thread_Parameters))
*arg\Name = Namn
*arg\fork1 = Fork1
*arg\fork2 = Fork2
Thread=CreateThread(@_philosophers(), *arg) ;send the thread a pointer to our structure
ProcedureReturn Thread
EndProcedure
Procedure _philosophers(*arg.Thread_Parameters)
Protected Iam.s=*arg\Name, j=*arg\fork1, k=*arg\fork2
Protected f1, f2
ClearStructure(*arg, Thread_Parameters)
FreeMemory(*arg)
;
Repeat
Tell(Mutex_main,Iam+": Going to the table")
Repeat ;Trying to get my two forks
f1=TryFork(j)
If f1
f2=TryFork(k)
If Not f2 ; I got only one fork
PutDownFork(j)
f1=0
EndIf
EndIf
If Not f2
Delay(Random(100)) ; Take a short breath, then try the forks in the other order
Swap j,k
EndIf
Until f1 And f2
Tell(Mutex_main,Iam+": I have fork #"+Str(j)+" & #"+Str(k)+" and I'm eating now")
Delay(Random(1500)+15)
Tell(Mutex_main,Iam+": release fork #"+Str(j)+" & #"+Str(k)+"")
Delay(Random(45)+15)
PutDownFork(j)
PutDownFork(k)
f1=0:f2=0
Tell(Mutex_main,Iam+": Thinking about the nature of the universe...")
Delay(Random(2500)+25)
ForEver
EndProcedure |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #PowerShell | PowerShell |
function ConvertTo-Discordian ( [datetime]$GregorianDate )
{
$DayOfYear = $GregorianDate.DayOfYear
$Year = $GregorianDate.Year + 1166
If ( [datetime]::IsLeapYear( $GregorianDate.Year ) -and $DayOfYear -eq 60 )
{ $Day = "St. Tib's Day" }
Else
{
If ( [datetime]::IsLeapYear( $GregorianDate.Year ) -and $DayOfYear -gt 60 )
{ $DayOfYear-- }
$Weekday = @( 'Sweetmorn', 'Boomtime', 'Pungenday', 'Prickle-Prickle', 'Setting Orange' )[(($DayOfYear - 1 ) % 5 )]
$Season = @( 'Chaos', 'Discord', 'Confusion', 'Bureaucracy', 'The Aftermath' )[( [math]::Truncate( ( $DayOfYear - 1 ) / 73 ) )]
$DayOfSeason = ( $DayOfYear - 1 ) % 73 + 1
$Day = "$Weekday, $Season $DayOfSeason"
}
$DiscordianDate = "$Day, $Year YOLD"
return $DiscordianDate
}
ConvertTo-Discordian ([datetime]'1/5/2016')
ConvertTo-Discordian ([datetime]'2/29/2016')
ConvertTo-Discordian ([datetime]'12/8/2016')
|
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)
| #Racket | Racket |
#lang racket
(require (planet jaymccarthy/dijkstra:1:2))
(define edges
'([a . ((b 7)(c 9)(f 14))]
[b . ((c 10)(d 15))]
[c . ((d 11)(f 2))]
[d . ((e 6))]
[e . ((f 9))]))
(define (node-edges n)
(cond [(assoc n edges) => rest] ['()]))
(define edge-weight second)
(define edge-end first)
(match/values (shortest-path node-edges edge-weight edge-end 'a (λ(n) (eq? n 'e)))
[(dists prevs)
(displayln (~a "Distances from a: " (for/list ([(n d) dists]) (list n d))))
(displayln (~a "Shortest path: "
(let loop ([path '(e)])
(cond [(eq? (first path) 'a) path]
[(loop (cons (hash-ref prevs (first path)) path))]))))])
|
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
| #Nim | Nim | import strutils
proc droot(n: int64): auto =
var x = @[n]
while x[x.high] > 10:
var s = 0'i64
for dig in $x[x.high]:
s += parseInt("" & dig)
x.add s
return (x.len - 1, x[x.high])
for n in [627615'i64, 39390'i64, 588225'i64, 393900588225'i64]:
let (a, d) = droot(n)
echo align($n, 12)," has additive persistence ",a," and digital root of ",d |
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
| #Oforth | Oforth | : sumDigits(n, base) 0 while(n) [ n base /mod ->n + ] ;
: digitalRoot(n, base)
0 while(n 9 >) [ 1 + sumDigits(n, base) ->n ] n swap Pair new ; |
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?
| #REXX | REXX | /*REXX program solves the Dinesman's multiple─dwelling problem with "natural" wording.*/
names= 'Baker Cooper Fletcher Miller Smith' /*names of multiple─dwelling tenants. */
#tenants= words(names) /*the number of tenants in the building*/
floors= 5; top= floors; bottom= 1 /*floor 1 is the ground (bottom) floor.*/
#= 0 /*the number of solutions found so far.*/
do @.1=1 for floors /*iterate through all floors for rules.*/
do @.2=1 for floors /* " " " " " " */
do @.3=1 for floors /* " " " " " " */
do @.4=1 for floors /* " " " " " " */
do @.5=1 for floors /* " " " " " " */
call set
do j=1 for floors-1; a= @.j /* [↓] people don't live on same floor*/
do k=j+1 to floors /*see if any people live on same floor.*/
if [email protected] then iterate @.5 /*Is anyone cohabiting? Then not valid*/
end /*k*/
end /*j*/
call Waldo /* ◄══ where the rubber meets the road.*/
end /*@.5*/
end /*@.4*/
end /*@.3*/
end /*@.2*/
end /*@.1*/
say 'found ' # " solution"s(#). /*display the number of solutions found*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
set: do p=1 for #tenants; call value word(names, p), @.p; end; return
s: if arg(1)=1 then return ''; return "s" /*a simple pluralizer function.*/
th: arg x; x=abs(x); return word('th st nd rd', 1 +x// 10* (x//100%10\==1)*(x//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
Waldo: if Baker == top then return
if Cooper == bottom then return
if Fletcher == bottom | Fletcher == top then return
if Miller \> Cooper then return
if Smith == Fletcher - 1 | Smith == Fletcher + 1 then return
if Fletcher == Cooper - 1 | Fletcher == Cooper + 1 then return
#= # + 1 /* [↑] "|" is REXX's "or" comparator.*/
say; do p=1 for #tenants; tenant= word(names, p)
say right(tenant, 35) 'lives on the' @.p || th(@.p) "floor."
end /*p*/ /* [↑] "||" is REXX's concatenation. */
return /* [↑] show tenants in order in NAMES.*/ |
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
| #Lambdatalk | Lambdatalk |
{def dotp
{def dotp.r
{lambda {:v1 :v2 :acc}
{if {A.empty? :v1}
then :acc
else {dotp.r {A.rest :v1} {A.rest :v2}
{+ {* {A.first :v1} {A.first :v2}} :acc}}}}}
{lambda {:v1 :v2}
{if {= {A.length :v1} {A.length :v2}}
then {dotp.r :v1 :v2 0}
else Vectors must be of equal length}}}
-> dotp
{dotp {A.new 1 3 -5} {A.new 4 -2}}
-> Vectors must be of equal length
{dotp {A.new 1 3 -5} {A.new 4 -2 -1}}
-> 3
|
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
| #Ruby | Ruby | strings = ["",
'"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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««#{str}»»» (size #{str.size})"
st.chars.each do |c|
ssq = str.squeeze(c)
puts "#{c.inspect}-squeezed: «««#{ssq}»»» (size #{ssq.size})"
end
puts
end
|
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
| #Rust | Rust | fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a {
let mut previous = None;
s.chars().filter(move |c| match previous {
Some(p) if p == squeezable && p == *c => false,
_ => {
previous = Some(*c);
true
}
})
}
fn main() {
fn show(input: &str, c: char) {
println!("Squeeze: '{}'", c);
println!("Input ({} chars): \t{}", input.chars().count(), input);
let output: String = squeezable_string(input, c).collect();
println!("Output ({} chars): \t{}", output.chars().count(), output);
println!();
}
let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell.
--- Harry S Truman"#;
#[rustfmt::skip]
let inputs = [
("", ' '),
(r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'),
("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
(harry, ' '),
(harry, '-'),
(harry, 'r'),
("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'),
("headmistressship", 's'),
];
inputs.iter().for_each(|(input, c)| show(input, *c));
} |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Swift | Swift | import Foundation
let dxs = [
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087
]
let dys = [
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032
]
extension Collection where Element: FloatingPoint {
@inlinable
public func mean() -> Element {
return reduce(0, +) / Element(count)
}
@inlinable
public func stdDev() -> Element {
let m = mean()
return map({ ($0 - m) * ($0 - m) }).mean().squareRoot()
}
}
typealias Rule = (Double, Double) -> Double
func funnel(_ arr: [Double], rule: Rule) -> [Double] {
var x = 0.0
var res = [Double](repeating: 0, count: arr.count)
for (i, d) in arr.enumerated() {
res[i] = x + d
x = rule(x, d)
}
return res
}
func experiment(label: String, rule: Rule) {
let rxs = funnel(dxs, rule: rule)
let rys = funnel(dys, rule: rule)
print("\(label)\t: x y")
print("Mean\t:\(String(format: "%7.4f, %7.4f", rxs.mean(), rys.mean()))")
print("Std Dev\t:\(String(format: "%7.4f, %7.4f", rxs.stdDev(), rys.stdDev()))")
print()
}
experiment(label: "Rule 1", rule: {_, _ in 0 })
experiment(label: "Rule 2", rule: {_, dz in -dz })
experiment(label: "Rule 3", rule: {z, dz in -(z + dz) })
experiment(label: "Rule 4", rule: {z, dz in z + dz }) |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Tcl | Tcl | package require Tcl 8.6
namespace path {tcl::mathop tcl::mathfunc}
proc funnel {items rule} {
set x 0.0
set result {}
foreach item $items {
lappend result [+ $x $item]
set x [apply $rule $x $item]
}
return $result
}
proc mean {items} {
/ [+ {*}$items] [double [llength $items]]
}
proc stddev {items} {
set m [mean $items]
sqrt [mean [lmap x $items {** [- $x $m] 2}]]
}
proc experiment {label dxs dys rule} {
set rxs [funnel $dxs $rule]
set rys [funnel $dys $rule]
puts $label
puts [format "Mean x, y : %7.4f, %7.4f" [mean $rxs] [mean $rys]]
puts [format "Std dev x, y : %7.4f, %7.4f" [stddev $rxs] [stddev $rys]]
puts ""
}
set dxs {
-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401
0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034
-0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095
0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099
-0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024
-0.181 -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348
-0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247
-0.310 0.171 0.000 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521
0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521
-0.799 0.087
}
set dys {
0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.490 -0.682 -0.065
0.242 -0.288 0.658 0.459 0.000 0.426 0.205 -0.765 -2.188 -0.742 -0.010
0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025
-0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.790 0.723
0.881 -0.508 0.393 -0.226 0.710 0.038 -0.217 0.831 0.480 0.407 0.447
-0.295 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491
1.347 -0.141 1.230 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064
0.721 0.104 -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477 1.537
-0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032
}
puts "USING STANDARD DATA"
experiment "Rule 1:" $dxs $dys {{z dz} {expr {0}}}
experiment "Rule 2:" $dxs $dys {{z dz} {expr {-$dz}}}
experiment "Rule 3:" $dxs $dys {{z dz} {expr {-($z+$dz)}}}
experiment "Rule 4:" $dxs $dys {{z dz} {expr {$z+$dz}}} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Clojure | Clojure | (let [n (range 1 8)]
(for [police n
sanitation n
fire n
:when (distinct? police sanitation fire)
:when (even? police)
:when (= 12 (+ police sanitation fire))]
(println police sanitation fire))) |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
\\ there are some kinds of objects in M2000, one of them is the Group, the user object
\\ the delegate is a pointer to group
\\ 1. We pass parameters to function operations$(), $ means that this function return string value
\\ 2. We see how this can be done with pointers to group
global doc$ \\ first define a global (for this module) to log output
document doc$="Output:"+{
}
class Delegator {
private:
group delegate
group null
public:
function operation$ {
if not .delegate is .null then
try ok {
ret$="Delegate implementation:"+.delegate=>operation$(![])
\\ [] is the stack of values (leave empty stack), ! used to place this to callee stack
}
if not ok or error then ret$="No implementation"
else
ret$= "Default implementation"
end if
\\ a global variable and all group members except arrays use <= not =. Simple = used for declaring local variables
doc$<=ret$+{
}
=ret$
}
class:
Module Delegator {
class none {}
.null->none()
If match("G") then .delegate->(group) else .delegate<=.null
}
}
Class Thing {
function operation$(a,b) {
=str$(a*b)
}
}
Module CallbyReference (&z as group) {
Print Z.operation$(5,30)
}
Module CallbyValue (z as group) {
Print Z.operation$(2,30)
}
Module CallbyReference2 (&z as pointer) {
Print Z=>operation$(5,30)
}
Module CallbyValue2 (z as pointer) {
Print Z=>operation$(2,30)
}
\\ Normal Group ' no logging to doc$
N=Thing()
Print N.operation$(10,20)
CallbyReference &N
CallbyValue N
N1->N ' N1 is a pointer to a named group
Print N1=>operation$(10,20)
CallbyReference2 &N1
CallbyValue2 N1
N1->(N) ' N1 now is a pointer to a float group (a copy of N)
Print N1=>operation$(10,20)
CallbyReference2 &N1
CallbyValue2 N1
\\ using named groups (A is a group, erased when this module exit)
A=Delegator()
B=Delegator(Thing())
Print A.operation$(10,20)
Print B.operation$(10,20)
A=B
CallbyReference &A
CallbyValue A
\\ M2000 has two kinds of pointers to groups
\\ one is a pointer to a no named group (a float group)
\\ a float group leave until no pointer refer to it
\\ using pointers to groups (A1 is a pointer to Group)
A1->Delegator()
B1->Delegator(Thing())
Print A1=>operation$(10,20)
Print B1=>operation$(10,20)
A1=B1
CallbyReference2 &A1
CallbyValue2 A1
\\ Second type is a pointer to a named group
\\ the pointer hold a weak reference to named group
\\ so a returned pointer of thid kind can be invalid if actual reference not exist
A=Delegator() ' copy a float group to A
A1->A
B1->B
Print A1=>operation$(10,20)
Print B1=>operation$(10,20)
A1=B1
CallbyReference2 &A1
CallbyValue2 A1
Group Something {
}
B=Delegator(Something)
Print B.operation$(10,20)
CallbyReference &B
CallbyValue B
Report Doc$
Clipboard Doc$
}
Checkit
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | delegator[del_]@operate :=
If[StringQ[del@operate], del@operate, "default implementation"];
del1 = Null;
del2@banana = "phone";
del3@operate = "delegate implementation";
Print[delegator[#]@operate] & /@ {del1, del2, del3}; |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #NGS | NGS | {
type Delegator
F init(d:Delegator) d.delegate = null
F default_impl(d:Delegator) 'default implementation'
F operation(d:Delegator) default_impl(d)
F operation(d:Delegator) {
guard defined thing
guard thing is Fun
try {
d.delegate.thing()
}
catch(e:ImplNotFound) {
# Might be unrelated exception, so check and optionally rethrow
e.callable !== thing throws e
default_impl(d)
}
}
F operation(d:Delegator) {
guard d.delegate is Null
default_impl(d)
}
a = Delegator()
echo(a.operation())
# There is no method thing(s:Str)
a.delegate = "abc"
echo(a.operation())
# ... now there is method thing(s:Str)
F thing(s:Str) 'delegate implementation'
echo(a.operation())
} |
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)
| #Nim | Nim | import strformat
type Point = tuple[x, y: float]
type Triangle = array[3, Point]
func `$`(p: Point): string =
fmt"({p.x:.1f}, {p.y:.1f})"
func `$`(t: Triangle): string =
fmt"Triangle {t[0]}, {t[1]}, {t[2]}"
func det2D(t: Triangle): float =
t[0].x * (t[1].y - t[2].y) +
t[1].x * (t[2].y - t[0].y) +
t[2].x * (t[0].y - t[1].y)
func checkTriWinding(t: var Triangle; allowReversed: bool) =
let det = t.det2D()
if det < 0:
if allowReversed:
swap t[1], t[2]
else:
raise newException(ValueError, "Triangle has wrong winding direction.")
func boundaryCollideChk(t: Triangle; eps: float): bool =
t.det2D() < eps
func boundaryDoesntCollideChk(t: Triangle; eps: float): bool =
t.det2D() <= eps
func triTri2D(t1, t2: var Triangle; eps = 0.0;
allowReversed = false; onBoundary = true): bool =
# Triangles must be expressed anti-clockwise.
t1.checkTriWinding(allowReversed)
t2.checkTriWinding(allowReversed)
# "onBoundary" determines whether points on boundary are considered as colliding or not.
let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk
# For each edge E of t1.
for i in 0..2:
let j = (i + 1) mod 3
# Check that all points of t2 lay on the external side of edge E.
# If they do, the triangles do not overlap.
if chkEdge([t1[i], t1[j], t2[0]], eps) and
chkEdge([t1[i], t1[j], t2[1]], eps) and
chkEdge([t1[i], t1[j], t2[2]], eps):
return false
# For each edge E of t2.
for i in 0..2:
let j = (i + 1) mod 3
# Check that all points of t1 lay on the external side of edge E.
# If they do, the triangles do not overlap.
if chkEdge([t2[i], t2[j], t1[0]], eps) and
chkEdge([t2[i], t2[j], t1[1]], eps) and
chkEdge([t2[i], t2[j], t1[2]], eps):
return false
# The triangles overlap.
result = true
when isMainModule:
var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]
var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)]
echo t1, " and\n", t2
var overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
# Need to allow reversed for this pair to avoid exception.
t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)]
t2 = t1
echo t1, " and\n", t2
overlapping = triTri2D(t1, t2, 0, true, true)
echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n"
t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]
t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)]
echo t1, " and\n", t2
overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
t1[2] = (2.5, 5.0)
t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)]
echo t1, " and\n", t2
overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)]
t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)]
echo t1, " and\n", t2
overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)]
echo t1, " and\n", t2
overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)]
t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)]
echo t1, " and\n", t2
echo "which have only a single corner in contact, if boundary points collide"
overlapping = triTri2D(t1, t2, 0, false, true)
echo if overlapping: "overlap\n" else: "do not overlap\n"
echo t1, " and\n", t2
echo "which have only a single corner in contact, if boundary points do not collide"
overlapping = triTri2D(t1, t2, 0, false, false)
echo if overlapping: "overlap\n" else: "do not overlap\n" |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Free_Pascal | Free Pascal | program deletion(input, output, stdErr);
const
rootDirectory = '/'; // might have to be altered for other platforms
inputTextFilename = 'input.txt';
docsFilename = 'docs';
var
fd: file;
begin
assign(fd, inputTextFilename);
erase(fd);
rmDir(docsFilename);
assign(fd, rootDirectory + inputTextFilename);
erase(fd);
rmDir(rootDirectory + docsFilename);
end. |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' delete file and empty sub-directory in current directory
Kill "input.txt"
RmDir "docs"
' delete file and empty sub-directory in root directory c:\
' deleting file in root requires administrative privileges in Windows 10
'Kill "c:\input.txt"
'RmDir "c:\docs"
Print "Press any key to quit"
Sleep
|
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
| #Nim | Nim | import sequtils, permutationsswap
type Matrix[M,N: static[int]] = array[M, array[N, float]]
proc det[M,N](a: Matrix[M,N]): float =
let n = toSeq 0..a.high
for sigma, sign in n.permutations:
var x = sign.float
for i in n: x *= a[i][sigma[i]]
result += x
proc perm[M,N](a: Matrix[M,N]): float =
let n = toSeq 0..a.high
for sigma, sign in n.permutations:
var x = 1.0
for i in n: x *= a[i][sigma[i]]
result += x
const
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]
]
echo "perm: ", a.perm, " det: ", a.det
echo "perm: ", b.perm, " det: ", b.det
echo "perm: ", c.perm, " det: ", c.det |
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
| #Ol | Ol |
; helper function that returns rest of matrix by col/row
(define (rest matrix i j)
(define (exclude1 l x) (append (take l (- x 1)) (drop l x)))
(exclude1
(map exclude1
matrix (repeat i (length matrix)))
j))
; superfunction for determinant and permanent
(define (super matrix math)
(let loop ((n (length matrix)) (matrix matrix))
(if (eq? n 1)
(caar matrix)
(fold (lambda (x a j)
(+ x (* a (lref math (mod j 2)) (super (rest matrix j 1) math))))
0
(car matrix)
(iota n 1)))))
; det/per calculators
(define (det matrix) (super matrix '(-1 1)))
(define (per matrix) (super matrix '( 1 1)))
; ---=( testing )=---------------------
(print (det '(
(1 2)
(3 4))))
; ==> -2
(print (per '(
(1 2)
(3 4))))
; ==> 10
(print (det '(
( 1 2 3 1)
(-1 -1 -1 2)
( 1 3 1 1)
(-2 -2 0 -1))))
; ==> 26
(print (per '(
( 1 2 3 1)
(-1 -1 -1 2)
( 1 3 1 1)
(-2 -2 0 -1))))
; ==> -10
(print (det '(
( 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))))
; ==> 0
(print (per '(
( 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))))
; ==> 6778800
|
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.
| #hexiscript | hexiscript | let a 1
let b 0
if tostr (a / (b + 0.)) = "inf"
println "Divide by Zero"
else
println a / b
endif |
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.
| #HicEst | HicEst | FUNCTION zero_divide(num, denom)
XEQ( num// "/" // denom, *99) ! on error jump to label 99
zero_divide = 0 ! division OK
RETURN
99 zero_divide = 1
END |
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
| #F.23 | F# | let is_numeric a = fst (System.Double.TryParse a) |
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
| #Factor | Factor | : numeric? ( string -- ? ) string>number >boolean ; |
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
| #Kotlin | Kotlin | import java.util.HashMap
fun main() {
System.out.printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
System.out.printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
for (s in arrayOf("", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")) {
processString(s)
}
}
private fun processString(input: String) {
val charMap: MutableMap<Char, Int?> = HashMap()
var dup = 0.toChar()
var index = 0
var pos1 = -1
var pos2 = -1
for (key in input.toCharArray()) {
index++
if (charMap.containsKey(key)) {
dup = key
pos1 = charMap[key]!!
pos2 = index
break
}
charMap[key] = index
}
val unique = if (dup.toInt() == 0) "yes" else "no"
val diff = if (dup.toInt() == 0) "" else "'$dup'"
val hex = if (dup.toInt() == 0) "" else Integer.toHexString(dup.toInt()).toUpperCase()
val position = if (dup.toInt() == 0) "" else "$pos1 $pos2"
System.out.printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length, unique, diff, hex, position)
} |
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
| #Raku | Raku | map {
my $squish = .comb.squish.join;
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
.chars, $_, .chars != $squish.chars, $squish.chars, $squish
}, lines
q:to/STRINGS/;
"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
The American people have a right to know if their president is a crook.
--- Richard Nixon
AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
STRINGS
|
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
| #REXX | REXX | /*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
@.= /*define a default for the @. array. */
parse arg x /*obtain optional argument from the CL.*/
if x\='' then @.1= x /*if user specified an arg, use that. */
else do; @.1=
@.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 '
end
do j=1; L= length(@.j) /*obtain the length of an array element*/
say copies('═', 105) /*show a separator line between outputs*/
if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */
new= collapse(@.j)
say 'string' word("isn't is",1+collapsible) 'collapsible' /*display semaphore value*/
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
collapse: procedure expose collapsible; parse arg y 1 $ 2 /*get the arg; get 1st char. */
do k=2 to length(y) /*traipse through almost all the chars.*/
_= substr(y, k, 1) /*pick a character from Y (1st arg). */
if _==right($, 1) then iterate /*Is this the same character? Skip it.*/
$= $ || _ /*append the character, it's different.*/
end /*j*/
collapsible= y\==$; return $ /*set boolean to true if collapsible.*/ |
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
| #Pascal | Pascal | program SameNessOfChar;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;//Format
const
TestData : array[0..6] of String =
('',' ','2','333','.55','tttTTT','4444 444k');
function PosOfDifferentChar(const s: String):NativeInt;
var
i: Nativeint;
ch:char;
Begin
result := length(s);
IF result < 2 then
EXIT;
ch := s[1];
i := 2;
while (i< result) AND (S[i] =ch) do
inc(i);
result := i;
end;
procedure OutIsAllSame(const s: String);
var
l,len: NativeInt;
Begin
l := PosOfDifferentChar(s);
len := Length(s);
write('"',s,'" of length ',len);
IF l = len then
writeln(' contains all the same character')
else
writeln(Format(' is different at position %d "%s" (0x%X)',[l,s[l],Ord(s[l])]));
end;
var
i : NativeInt;
begin
For i := Low(TestData) to HIgh(TestData) do
OutIsAllSame(TestData[i]);
end. |
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.
| #Python | Python | import threading
import random
import time
# Dining philosophers, 5 Phillies with 5 forks. Must have two forks to eat.
#
# Deadlock is avoided by never waiting for a fork while holding a fork (locked)
# Procedure is to do block while waiting to get first fork, and a nonblocking
# acquire of second fork. If failed to get second fork, release first fork,
# swap which fork is first and which is second and retry until getting both.
#
# See discussion page note about 'live lock'.
class Philosopher(threading.Thread):
running = True
def __init__(self, xname, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.name = xname
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
while(self.running):
# Philosopher is thinking (but really is sleeping).
time.sleep( random.uniform(3,13))
print '%s is hungry.' % self.name
self.dine()
def dine(self):
fork1, fork2 = self.forkOnLeft, self.forkOnRight
while self.running:
fork1.acquire(True)
locked = fork2.acquire(False)
if locked: break
fork1.release()
print '%s swaps forks' % self.name
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print '%s starts eating '% self.name
time.sleep(random.uniform(1,10))
print '%s finishes eating and leaves to think.' % self.name
def DiningPhilosophers():
forks = [threading.Lock() for n in range(5)]
philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')
philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
for i in range(5)]
random.seed(507129)
Philosopher.running = True
for p in philosophers: p.start()
time.sleep(100)
Philosopher.running = False
print ("Now we're finishing.")
DiningPhilosophers() |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Prolog | Prolog | % See https://en.wikipedia.org/wiki/Discordian_calendar
main:-
test(2022, 4, 20),
test(2020, 5, 24),
test(2020, 2, 29),
test(2019, 7, 15),
test(2025, 3, 19),
test(2017, 12, 8).
test(Gregorian_year, Gregorian_month, Gregorian_day):-
ddate(Gregorian_year, Gregorian_month, Gregorian_day,
Discordian_date),
format('~|~`0t~d~2+-~|~`0t~d~2+-~|~`0t~d~2+: ~w~n', [Gregorian_year,
Gregorian_month, Gregorian_day, Discordian_date]).
ddate(Gregorian_year, 2, 29, Discordian_date):-
convert_year(Gregorian_year, Discordian_year),
swritef(Discordian_date, 'St. Tib\'s Day in the YOLD %w',
[Discordian_year]),
!.
ddate(Gregorian_year, Gregorian_month, Gregorian_day,
Discordian_date):-
convert_year(Gregorian_year, Discordian_year),
day_of_year(Gregorian_month, Gregorian_day, Daynum),
Season is Daynum//73,
Weekday is Daynum mod 5,
Day_of_season is 1 + Daynum mod 73,
season(Season, Season_name),
week_day(Weekday, Day_name),
(holy_day(Season, Day_of_season, Holy_day) ->
swritef(Discordian_date, '%w, day %w of %w in the YOLD %w. Celebrate %w!',
[Day_name, Day_of_season, Season_name, Discordian_year, Holy_day])
;
swritef(Discordian_date, '%w, day %w of %w in the YOLD %w',
[Day_name, Day_of_season, Season_name, Discordian_year])
).
convert_year(Gregorian_year, Discordian_year):-
Discordian_year is Gregorian_year + 1166.
day_of_year(M, D, N):-
month_days(M, Days),
N is Days + D - 1.
month_days(1, 0).
month_days(2, 31).
month_days(3, 59).
month_days(4, 90).
month_days(5, 120).
month_days(6, 151).
month_days(7, 181).
month_days(8, 212).
month_days(9, 243).
month_days(10, 273).
month_days(11, 304).
month_days(12, 334).
season(0, 'Chaos').
season(1, 'Discord').
season(2, 'Confusion').
season(3, 'Bureacracy').
season(4, 'The Aftermath').
week_day(0, 'Sweetmorn').
week_day(1, 'Boomtime').
week_day(2, 'Pungenday').
week_day(3, 'Prickle-Prickle').
week_day(4, 'Setting Orange').
holy_day(0, 5, 'Mungday').
holy_day(0, 50, 'Chaoflux').
holy_day(1, 5, 'Mojoday').
holy_day(1, 50, 'Discoflux').
holy_day(2, 5, 'Syaday').
holy_day(2, 50, 'Confuflux').
holy_day(3, 5, 'Zaraday').
holy_day(3, 50, 'Bureflux').
holy_day(4, 5, 'Maladay').
holy_day(4, 50, 'Afflux'). |
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)
| #Raku | Raku | class Graph {
has (%.edges, %.nodes);
method new(*@args){
my (%edges, %nodes);
for @args {
%edges{.[0] ~ .[1]} = $_;
%nodes{.[0]}.push( .[0] ~ .[1] );
%nodes{.[1]}.push( .[0] ~ .[1] );
}
self.bless(edges => %edges, nodes => %nodes);
}
method neighbours ($source) {
my (%neighbours, $edges);
$edges = self.nodes{$source};
for @$edges -> $x {
for self.edges{$x}[0..1] -> $y {
if $y ne $source {
%neighbours{$y} = self.edges{$x}
}
}
}
return %neighbours
}
method dijkstra ($source, $dest) {
my (%node_data, $v, $u);
my @q = self.nodes.keys;
for self.nodes.keys {
%node_data{$_}{'dist'} = Inf;
%node_data{$_}{'prev'} = '';
}
%node_data{$source}{'dist'} = 0;
while @q {
# %node_data.perl.say;
my ($mindist, $idx) =
@((map {[%node_data{@q[$_]}{'dist'},$_]},^@q).min(*[0]));
$u = @q[$idx];
if $mindist eq Inf {
return ()
}
elsif $u eq $dest {
my @s;
while %node_data{$u}{'prev'} {
@s.unshift($u);
$u = %node_data{$u}{'prev'}
}
@s.unshift($source);
return @s;
}
else {
@q.splice($idx,1);
}
for self.neighbours($u).kv -> $v, $edge {
my $alt = %node_data{$u}{'dist'} + $edge[2];
if $alt < %node_data{$v}{'dist'} {
%node_data{$v}{'dist'} = $alt;
%node_data{$v}{'prev'} = $u
}
}
}
}
}
my $a = Graph.new([
["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]
]).dijkstra('a', 'e').say; |
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
| #Ol | Ol |
(define (digital-root num)
(if (less? num 10)
num
(let loop ((num num) (sum 0))
(if (zero? num)
(digital-root sum)
(loop (div num 10) (+ sum (mod num 10)))))))
(print (digital-root 627615))
(print (digital-root 39390))
(print (digital-root 588225))
(print (digital-root 393900588225))
|
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?
| #Ring | Ring |
floor1 = "return baker!=cooper and baker!=fletcher and baker!=miller and
baker!=smith and cooper!=fletcher and cooper!=miller and
cooper!=smith and fletcher!=miller and fletcher!=smith and
miller!=smith"
floor2 = "return baker!=4"
floor3 = "return cooper!=0"
floor4 = "return fletcher!=0 and fletcher!=4"
floor5 = "return miller>cooper"
floor6 = "return fabs(smith-fletcher)!=1"
floor7 = "return fabs(fletcher-cooper)!=1"
for baker = 0 to 4
for cooper = 0 to 4
for fletcher = 0 to 4
for miller = 0 to 4
for smith = 0 to 4
if eval(floor2) if eval(floor3) if eval(floor5)
if eval(floor4) if eval(floor6) if eval(floor7)
if eval(floor1)
see "baker lives on floor " + baker + nl
see "cooper lives on floor " + cooper + nl
see "fletcher lives on floor " + fletcher + nl
see "miller lives on floor " + miller + nl
see "smith lives on floor " + smith + nl ok ok ok ok ok ok ok
next
next
next
next
next
|
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
| #LFE | LFE | (defun dot-product (a b)
(: lists foldl #'+/2 0
(: lists zipwith #'*/2 a b)))
|
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
| #Liberty_BASIC | Liberty BASIC | vectorA$ = "1, 3, -5"
vectorB$ = "4, -2, -1"
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
print DotProduct(vectorA$, vectorB$)
'arbitrary length
vectorA$ = "3, 14, 15, 9, 26"
vectorB$ = "2, 71, 18, 28, 1"
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
print DotProduct(vectorA$, vectorB$)
end
function DotProduct(a$, b$)
DotProduct = 0
i = 1
while 1
x$=word$( a$, i, ",")
y$=word$( b$, i, ",")
if x$="" or y$="" then exit function
DotProduct = DotProduct + val(x$)*val(y$)
i = i+1
wend
end function |
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
| #Sidef | Sidef | func squeeze(str, c) {
str.gsub(Regex("(" + c.escape + ")" + '\1+'), {|s1| s1 })
}
var strings = ["",
'"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 ",
"😍😀🙌💃😍😍😍🙌"]
var squeeze_these = ["", "-", "7", ".", " -r", "😍"]
[strings, squeeze_these].zip {|str,st|
say " original: «««#{str}»»» (length: #{str.len})"
st.each {|c|
var ssq = squeeze(str, c)
say "'#{c}'-squeezed: «««#{ssq}»»» (length: #{ssq.len})"
}
say ''
} |
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
| #Tcl | Tcl | # Set test data as a list pairing even and odd values
# as test string and squeeze character(s) respectively.
set test {
{} {" "}
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln } {"-"}
{..1111111111111111111111111111111111111111111111111111111111111117777888} {"7"}
{I never give 'em hell, I just tell the truth, and they think it's hell. } {"."} ;# '
{ --- Harry S Truman } {" " "-" "r"}
{The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {"e"} ;# '
{headmistressship} {"s"}
}
foreach {str chrs} $test {
foreach c $chrs {
# Escape non-word replacement characters (such as .)
set c [regsub -all {\W} $c {\\&}]
# Uses regexp lookbehind to detect repeated characters
set re [subst -noback {($c)(\1+)}] ;# build expression
set sub [regsub -all $re $str {\1}]
# Output
puts [format "Original (length %3d): %s" [string length $str] $str]
puts [format "Subbed (length %3d): %s" [string length $sub] $sub]
puts ----------------------
}
}
|
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Vlang | Vlang | import math
type Rule = fn(f64, f64) f64
const (
dxs = [
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
]
dys = [
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
]
)
fn funnel(fa []f64, r Rule) []f64 {
mut x := 0.0
mut result := []f64{len: fa.len}
for i, f in fa {
result[i] = x + f
x = r(x, f)
}
return result
}
fn mean(fa []f64) f64 {
mut sum := 0.0
for f in fa {
sum += f
}
return sum / f64(fa.len)
}
fn std_dev(fa []f64) f64 {
m := mean(fa)
mut sum := 0.0
for f in fa {
sum += (f - m) * (f - m)
}
return math.sqrt(sum / f64(fa.len))
}
fn experiment(label string, r Rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
println("$label : x y")
println("Mean : ${mean(rxs):7.4f}, ${mean(rys):7.4f}")
println("Std Dev : ${std_dev(rxs):7.4f}, ${std_dev(rys):7.4f}")
println('')
}
fn main() {
experiment("Rule 1", fn(_ f64, _ f64) f64 {
return 0.0
})
experiment("Rule 2", fn(_ f64, dz f64) f64 {
return -dz
})
experiment("Rule 3", fn(z f64, dz f64) f64 {
return -(z + dz)
})
experiment("Rule 4", fn(z f64, dz f64) f64 {
return z + dz
})
} |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Wren | Wren | import "/math" for Nums
import "/fmt" for Fmt
var dxs = [
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087
]
var dys = [
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032
]
var funnel = Fn.new { |fa, r|
var x = 0
var res = List.filled(fa.count, 0)
for (i in 0...fa.count) {
var f = fa[i]
res[i] = x + f
x = r.call(x, f)
}
return res
}
var experiment = Fn.new { |label, r|
var rxs = funnel.call(dxs, r)
var rys = funnel.call(dys, r)
System.print("%(label) : x y")
System.print("Mean : %(Fmt.f(7, Nums.mean(rxs), 4)), %(Fmt.f(7, Nums.mean(rys), 4))")
System.print("Std Dev : %(Fmt.f(7, Nums.popStdDev(rxs), 4)), %(Fmt.f(7, Nums.popStdDev(rys), 4))")
System.print()
}
experiment.call("Rule 1") { |z, dz| 0 }
experiment.call("Rule 2") { |z, dz| -dz }
experiment.call("Rule 3") { |z, dz| -(z + dz) }
experiment.call("Rule 4") { |z, dz| z + dz } |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #CLU | CLU | start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, "P S F\n- - -")
for police: int in int$from_to_by(2,7,2) do
for sanitation: int in int$from_to(1,7) do
for fire: int in int$from_to(1,7) do
if police~=sanitation
& sanitation~=fire
& police~=fire
& police+sanitation+fire = 12
then
stream$putl(po, int$unparse(police) || " " ||
int$unparse(sanitation) || " " ||
int$unparse(fire))
end
end
end
end
end start_up |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. DEPARTMENT-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE".
01 COMBINATION.
03 FILLER PIC X(5) VALUE SPACES.
03 POLICE PIC 9.
03 FILLER PIC X(11) VALUE SPACES.
03 SANITATION PIC 9.
03 FILLER PIC X(5) VALUE SPACES.
03 FIRE PIC 9.
01 TOTAL PIC 99.
PROCEDURE DIVISION.
BEGIN.
DISPLAY BANNER.
PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2
UNTIL POLICE IS GREATER THAN 6.
STOP RUN.
POLICE-LOOP.
PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1
UNTIL SANITATION IS GREATER THAN 7.
SANITATION-LOOP.
PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1
UNTIL FIRE IS GREATER THAN 7.
FIRE-LOOP.
ADD POLICE, SANITATION, FIRE GIVING TOTAL.
IF POLICE IS NOT EQUAL TO SANITATION
AND POLICE IS NOT EQUAL TO FIRE
AND SANITATION IS NOT EQUAL TO FIRE
AND TOTAL IS EQUAL TO 12,
DISPLAY COMBINATION. |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Nim | Nim | ####################################################################################################
# Base delegate.
type Delegate = ref object of RootObj
nil
method thing(d: Delegate): string {.base.} =
## Default implementation of "thing".
## Using a method rather than a proc allows dynamic dispatch.
"default implementation"
####################################################################################################
# Delegator.
type Delegator = object
delegate: Delegate
proc initDelegator(d: Delegate = nil): Delegator =
## Create a delegator with given delegate or nil.
if d.isNil:
Delegator(delegate: Delegate()) # Will use a default delegate instance.
else:
Delegator(delegate: d) # Use the provided delegate instance.
proc operation(d: Delegator): string =
## Calls the delegate.
d.delegate.thing()
####################################################################################################
# Usage.
let d = initDelegator()
echo "Without any delegate: ", d.operation()
type Delegate1 = ref object of Delegate
let d1 = initDelegator(Delegate1())
echo "With a delegate which desn’t provide the “thing” method: ", d1.operation()
type Delegate2 = ref object of Delegate
method thing(d: Delegate2): string =
"delegate implementation"
let d2 = initDelegator(Delegate2())
echo "With a delegate which provided the “thing” method: ", d2.operation() |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Objeck | Objeck | interface Thingable {
method : virtual : public : Thing() ~ String;
}
class Delegator {
@delegate : Thingable;
New() {
}
method : public : SetDelegate(delegate : Thingable) ~ Nil {
@delegate := delegate;
}
method : public : Operation() ~ String {
if(@delegate = Nil) {
return "default implementation";
}
else {
return @delegate->Thing();
};
}
}
class Delegate implements Thingable {
New() {
}
method : public : Thing() ~ String {
return "delegate implementation";
}
}
class Example {
function : Main(args : String[]) ~ Nil {
# Without a delegate:
a := Delegator->New();
Runtime->Assert(a->Operation()->Equals("default implementation"));
# With a delegate:
d := Delegate->New();
a->SetDelegate(d);
Runtime->Assert(a->Operation()->Equals("delegate implementation"));
# Same as the above, but with an anonymous class:
a->SetDelegate(Base->New() implements Thingable {
method : public : Thing() ~ String {
return "anonymous delegate implementation";
}
});
Runtime->Assert(a->Operation()->Equals("anonymous delegate implementation"));
}
}
|
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)
| #ooRexx | ooRexx | /*--------------------------------------------------------------------
* Determine if two triangles overlap
* Fully (?) tested with integer coordinates of the 6 corners
* This was/is an exercise with ooRexx
* Removed the fraction arithmetic
*-------------------------------------------------------------------*/
Parse Version v
oid='trioo.txt'; 'erase' oid
Call o v
case=0
cc=0
Call trio_test '0 0 4 0 0 4 1 1 2 1 1 2'
Call trio_test '0 0 0 6 8 3 8 0 8 8 0 3'
Call trio_test '0 0 0 2 2 0 0 0 4 0 0 6'
/* The task's specified input */
Call trio_test '0 0 5 0 0 5 0 0 5 0 0 6'
Call trio_test '0 0 0 5 5 0 0 0 0 5 5 0'
Call trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'
Call trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4'
Call trio_test '0 0 1 1 0 2 2 1 3 0 3 2'
Call trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'
Call trio_test '0 0 1 0 0 1 1 0 2 0 1 1'
Exit
/* Other test cases */
Call trio_test '0 0 0 4 4 0 0 2 2 2 2 0'
Call trio_test '0 0 0 5 5 0 0 0 0 5 5 0'
Call trio_test '0 0 0 5 5 0 0 0 0 5 7 0'
Call trio_test '0 0 1 0 0 1 1 0 2 0 1 1'
Call trio_test '0 0 1 1 0 2 2 1 3 0 3 2'
Call trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'
Call trio_test '0 0 2 0 2 2 3 3 5 3 5 5'
Call trio_test '0 0 2 0 2 3 0 0 2 0 2 3'
Call trio_test '0 0 4 0 0 4 0 2 2 0 2 2'
Call trio_test '0 0 4 0 0 4 1 1 2 1 1 2'
Call trio_test '0 0 5 0 0 2 5 0 8 0 4 8'
Call trio_test '0 0 5 0 0 5 0 0 5 0 0 6'
Call trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'
Call trio_test '0 0 5 0 0 5 -5 0 -1 6 -3 0'
Call trio_test '0 0 5 0 3 5 0 4 3 -1 5 4'
Call trio_test '0 0 6 0 4 6 1 1 4 2 7 1'
Call trio_test '0 1 0 4 2 2 3 1 3 4 5 2'
Call trio_test '1 0 3 0 2 2 1 3 3 3 2 2'
Call trio_test '1 0 3 0 2 2 1 3 3 3 2 5'
Call trio_test '1 1 4 2 7 1 0 0 8 0 4 8'
Call trio_test '2 0 2 6 1 8 0 1 0 5 8 3'
Call trio_test '0 0 4 0 0 4 1 1 2 1 1 2'
Say case 'cases tested'
Say cc
Exit
trio_test:
Parse Arg tlist
cc+=1
tlist=space(tlist)
tl1=tlist ; Call trio_t tl1
tl2=reversex(tlist) ; Call trio_t tl2
tl3=''
tl=tlist
Do While tl<>''
Parse Var tl x y tl
tl3=tl3 y x
End
Call trio_t tl3
tl4=reversex(tl3) ; Call trio_t tl4
tl5=subword(tl4,7) subword(tl4,1,6) ; Call trio_t tl5
tl6=subword(tl5,7) subword(tl5,1,6) ; Call trio_t tl6
Return
trio_t:
Parse Arg tlist
tlist=space(tlist)
Say tlist
case+=1
Parse Arg ax ay bx by cx cy dx dy ex ey fx fy
/*---------------------------------------------------------------------
* First build the objects needed
*--------------------------------------------------------------------*/
a=.point~new(ax,ay); b=.point~new(bx,by); c=.point~new(cx,cy)
d=.point~new(dx,dy); e=.point~new(ex,ey); f=.point~new(fx,fy)
abc=.triangle~new(a,b,c)
def=.triangle~new(d,e,f)
Call o 'Triangle: ABC:' abc ,1
Call o 'Edges of ABC:'; Do i=1 To 3; Call o ' 'abc~edge(i); End
Call o 'Triangle: DEF:' def ,1
Call o 'Edges of DEF:'; Do i=1 To 3; Call o ' 'def~edge(i); End
pixl=' '
Do i=1 To 3
pixl=pixl abc~draw(i,'O')
pixl=pixl def~draw(i,'*')
End
res=0
fc=0
touch=0
bordl=''
Do i=1 To 3
p1=abc~point(i)
p2=def~point(i)
Do j=1 To 3
e1=abc~edge(j)
e2=def~edge(j)
If e1~contains(p2) Then Do
Call o e1 'contains' p2
ps=p2~string
If wordpos(ps,bordl)=0 Then Do
bordl=bordl ps
touch+=1
End
End
Else
Call o e1 'does not contain' p2 i j
If e2~contains(p1) Then Do
Call o e2 'contains' p1
ps=p1~string
If wordpos(ps,bordl)=0 Then Do
bordl=bordl ps
touch+=1
End
End
Else
Call o e2 'does not contain' p1
End
End
wb=words(bordl) /* how many of them? */
If wb>0 Then
Call o 'Corner(s) that touch the other triangle:' bordl,1
/*---------------------------------------------------------------------
* How many of them are corners of both triangles
*--------------------------------------------------------------------*/
m=0
cmatch=''
do i=1 To 3
If wordpos(abc~point(i),bordl)>0 &,
wordpos(abc~point(i),def)>0 Then Do
cmatch=cmatch abc~point(i)
m+=1
End
End
/*---------------------------------------------------------------------
* With two or three touching corners we show the result and return
*--------------------------------------------------------------------*/
Select
When wb=3 Then Do /* all three touch */
Call draw(pixl)
Select
When m=3 Then
Call o 'Triangles are identical',1
When m=2 Then
Call o 'Triangles have an edge in common:' cmatch,1
Otherwise
Call o 'Triangles overlap and touch on' bordl,1
End
Call o '',1
-- Pull .
Return
End
When wb=2 Then Do /* two of them match */
Call draw(pixl)
If m=2 Then
Call o 'Triangles have an edge in common:' cmatch,1
Else
Call o 'Triangles overlap and touch on' bordl,1
Call o ''
-- Pull .
Return
End
When wb=1 Then Do /* one of them matches */
Call o 'Triangles touch on' bordl,1 /* other parts may overlap */
Call o ' we analyze further',1
End
Otherwise /* we know nothing yet */
Nop
End
/*---------------------------------------------------------------------
* Now we look for corners of abc that are within the triangle def
*--------------------------------------------------------------------*/
in_def=0
Do i=1 To 3
p=abc~point(i)
Call o 'p ='p
Call o 'def='def
If def~contains(p) &,
wordpos(p,bordl)=0 Then Do
Call o def 'contains' p
in_def+=1
End
End
If in_def=3 Then Do
Call o abc 'is fully contained in' def,1
Call o '',1
Call draw(pixl)
fc=1
End
res=(in_def>0)
/*---------------------------------------------------------------------
* Now we look for corners of def that are within the triangle abc
*--------------------------------------------------------------------*/
If res=0 Then Do
in_abc=0
If res=0 Then Do
Do i=1 To 3
p=def~point(i)
Call o 'p ='p
Call o 'def='def
If abc~contains(p) &,
wordpos(p,bordl)=0 Then Do
Call o abc 'contains' p
in_abc+=1
End
End
End
If in_abc=3 Then Do
Call o def 'is fully contained in' abc,1
Call o '',1
Call draw(pixl)
fc=1
End
res=(in_abc>0)
End
/*---------------------------------------------------------------------
* Now we check if some edge of abc crosses any edge of def
*--------------------------------------------------------------------*/
If res=0 Then Do
Do i=1 To 3
Do j=1 To 3
e1=abc~edge(i); Call o 'e1='e1
e2=def~edge(j); Call o 'e2='e2
Call o 'crossing???'
res=e1~crosses(e2)
If res Then Do
End
If res Then
Call o 'edges cross'
Else
Call o 'edges don''t cross'
End
End
End
If fc=0 Then Do /* no fully contained */
Call draw(pixl)
If res=0 Then /* no overlap */
If wb=1 Then /* but one touching corner */
call o abc 'and' def 'don''t overlap but touch on' bordl,1
Else
call o abc 'and' def 'don''t overlap',1
Else /* overlap */
If wb>0 Then /* one touching corner */
call o abc 'and' def 'overlap and touch on' bordl,1
Else
call o abc 'and' def 'overlap',1
Call o '',1
-- Pull .
End
Return
/*---------------------------------------------------------------------
* And here are all the classes and methods needed:
* point init, x, y, string
* triangle init, point, edge, contains, string
* edge init, p1, p2, kdx, contains, crosses, string
*--------------------------------------------------------------------*/
::class point public
::attribute x
::attribute y
::method init
expose x y
use arg x,y
::method string
expose x y
return "("||x","y")"
::class triangle public
::method init
expose point edge
use arg p1,p2,p3
point=.array~new
point[1]=p1
point[2]=p2
point[3]=p3
edge=.array~new
Do i=1 To 3
ia=i+1; If ia=4 Then ia=1
edge[i]=.edge~new(point[i],point[ia])
End
::method point
expose point
use arg n
Return point[n]
::method edge
expose edge
use arg n
Return edge[n]
::method contains
expose point edge
use arg pp
Call o self
Call o 'pp='pp
xmin=1.e9
ymin=1.e9
xmax=-1.e9
ymax=-1.e9
Do i=1 To 3
e=edge[i]
Parse Value e~kdx With ka.i da.i xa.i
Call o show_g(ka.i,da.i,xa.i)
p1=e~p1
p2=e~p2
xmin=min(xmin,p1~x,p2~x)
xmax=max(xmax,p1~x,p2~x)
ymin=min(ymin,p1~y,p2~y)
ymax=max(ymax,p1~y,p2~y)
End
If pp~x<xmin|pp~x>xmax|pp~y<ymin|pp~y>ymax Then
res=0
Else Do
e=edge[1]
e2=edge[2]
p1=e2~p1
p2=e2~p2
Call o 'e:' e
Select
When ka.1='*' Then Do
y2=ka.2*pp~x+da.2
y3=ka.3*pp~x+da.3
res=between(y2,pp~y,y3)
End
When ka.2='*' Then Do
y2=ka.1*pp~x+da.1
res=between(p1~y,y2,p2~y)
End
Otherwise Do
dap=pp~y-ka.1*pp~x
If ka.3='*' Then
x3=xa.3
Else
x3=(da.3-dap)/(ka.1-ka.3)
x2=(da.2-dap)/(ka.1-ka.2)
res=between(x2,pp~x,x3)
End
End
End
Return res
::method string
expose point
ol=''
Do p over point
ol=ol p~string
End
return ol
::method draw
expose point
Use Arg i,c
p=self~point(i)
Return p~x p~y c
::class edge public
::method init
expose edge p1 p2
use arg p1,p2
edge=.array~new
edge[1]=p1
edge[2]=p2
::method p1
expose edge p1 p2
return p1
::method p2
expose edge p1 p2
return p2
::method kdx
expose edge p1 p2
x1=p1~x
y1=p1~y
x2=p2~x
y2=p2~y
If x1=x2 Then Do
Parse Value '*' '-' x1 With ka da xa
Call o show_g(ka,da,xa)
End
Else Do
ka=(y2-y1)/(x2-x1)
da=y2-ka*x2
xa='*'
End
Return ka da xa
::method contains
Use Arg p
p1=self~p1
p2=self~p2
parse Value self~kdx With k d x
If k='*' Then Do
res=(p~x=p1~x)&between(p1~y,p~y,p2~y,'I')
End
Else Do
ey=k*p~x+d
res=(ey=p~y)&between(p1~x,p~x,p2~x,'I')
End
If res Then Call o self 'contains' p
Else Call o self 'does not contain' p
Return res
::method crosses
expose p1 p2
Use Arg e
q1=e~p1
q2=e~p2
Call o 'Test if' e 'crosses' self
Call o self~kdx
Call o e~kdx
Parse Value self~kdx With ka da xa; Call o ka da xa
Call o show_g(ka,da,xa)
Parse Value e~kdx With kb db xb; Call o kb db xb
Call o show_g(kb,db,xb)
Call o 'ka='ka
Call o 'kb='kb
Select
When ka='*' Then Do
If kb='*' Then Do
res=(xa=xb)
End
Else Do
Call o 'kb='kb 'xa='||xa 'db='db
yy=kb*xa+db
res=between(q1~y,yy,q2~y)
End
End
When kb='*' Then Do
yy=ka*xb+da
res=between(p1~y,yy,p2~y)
End
When ka=kb Then Do
If da=db Then Do
If min(p1~x,p2~x)>max(q1~x,q2~x) |,
min(q1~x,q2~x)>max(p1~x,p2~x) Then
res=0
Else Do
res=1
End
End
Else
res=0
End
Otherwise Do
x=(db-da)/(ka-kb)
y=ka*x+da
Call o 'cross:' x y
res=between(p1~x,x,p2~x)
End
End
Return res
::method string
expose edge p1 p2
ol=p1~string'-'p2~string
return ol
::routine between /* check if a number is between two others */
Use Arg a,x,b,inc
Call o 'between:' a x b
Parse Var a anom '/' adenom
Parse Var x xnom '/' xdenom
Parse Var b bnom '/' bdenom
If adenom='' Then adenom=1
If xdenom='' Then xdenom=1
If bdenom='' Then bdenom=1
aa=anom*xdenom*bdenom
xx=xnom*adenom*bdenom
bb=bnom*xdenom*adenom
If inc='I' Then
res=sign(xx-aa)<>sign(xx-bb)
Else
res=sign(xx-aa)<>sign(xx-bb) & (xx-aa)*(xx-bb)<>0
Call o a x b 'res='res
Return res
::routine show_g /* show a straight line's forula */
/*---------------------------------------------------------------------
* given slope, y-distance, and (special) x-value
* compute y=k*x+d or, if a vertical line, k='*'; x=c
*--------------------------------------------------------------------*/
Use Arg k,d,x
Select
When k='*' Then res='x='||x /* vertical line */
When k=0 Then res='y='d /* horizontal line */
Otherwise Do /* ordinary line */
Select
When k=1 Then res='y=x'dd(d)
When k=-1 Then res='y=-x'dd(d)
Otherwise res='y='k'*x'dd(d)
End
End
End
Return res
::routine dd /* prepare a displacement for presenting it in show_g */
/*---------------------------------------------------------------------
* prepare y-distance for display
*--------------------------------------------------------------------*/
Use Arg dd
Select
When dd=0 Then dd='' /* omit dd if it's zero */
When dd<0 Then dd=dd /* use dd as is (-value) */
Otherwise dd='+'dd /* prepend '+' to positive dd */
End
Return dd
::routine o /* debug output */
Use Arg txt,say
If say=1 Then
Say txt
oid='trioo.txt'
Return lineout(oid,txt)
::routine draw
Use Arg pixl
Return /* remove to see the triangle corners */
Say 'pixl='pixl
pix.=' '
Do While pixl<>''
Parse Var pixl x y c pixl
x=2*x+16; y=2*y+4
If pix.x.y=' ' Then
pix.x.y=c
Else
pix.x.y='+'
End
Do j= 20 To 0 By -1
ol=''
Do i=0 To 40
ol=ol||pix.i.j
End
Say ol
End
Return
::routine reversex
Use Arg list
n=words(list)
res=word(list,n)
Do i=n-1 to 1 By -1
res=res word(list,i)
End
Return res |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Furor | Furor |
###sysinclude dir.uh
// ===================
argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end }
2 argv 'e !istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv removefile
end
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Gambas | Gambas | Public Sub Main()
Kill User.home &/ "input.txt"
Rmdir User.home &/ "docs"
'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!
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
| #PARI.2FGP | PARI/GP | matdet(M) |
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
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
sub permanent{
my $mat = shift;
my $n = shift // $mat->dim(0);
return undef if $mat->dim(0) != $mat->dim(1);
return $mat(0,0) if $n == 1;
my $sum = 0;
--$n;
my $m = $mat(1:,1:)->copy;
for(my $i = 0; $i <= $n; ++$i){
$sum += $mat($i,0) * permanent($m, $n);
last if $i == $n;
$m($i,:) .= $mat($i,1:);
}
return sclr($sum);
}
my $M = pdl([[2,9,4], [7,5,3], [6,1,8]]);
print "M = $M\n";
print "det(M) = " . $M->determinant . ".\n";
print "det(M) = " . $M->det . ".\n";
print "perm(M) = " . permanent($M) . ".\n"; |
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.
| #HolyC | HolyC | try {
Print("%d\n", 10 / 0);
} catch {
Print("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.
| #i | i | //Division by zero is defined in 'i' so the result can be checked to determine division by zero.
concept IsDivisionByZero(a, b) {
c = a/b
if c = 0 and a - 0 or a = 0 and c > 0
print( a, "/", b, " is a division by zero.")
return
end
print( a, "/", b, " is not division by zero.")
}
software {
IsDivisionByZero(5, 0)
IsDivisionByZero(5, 2)
IsDivisionByZero(0, 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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
&error := 1
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure")
end |
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
| #Fantom | Fantom |
class Main
{
// function to see if str contains a number of any of built-in types
static Bool readNum (Str str)
{
int := Int.fromStr (str, 10, false) // use base 10
if (int != null) return true
float := Float.fromStr (str, false)
if (float != null) return true
decimal := Decimal.fromStr (str, false)
if (decimal != null) return true
return false
}
public static Void main ()
{
echo ("For '2': " + readNum ("2"))
echo ("For '-2': " + readNum ("-2"))
echo ("For '2.5': " + readNum ("2.5"))
echo ("For '2a5': " + readNum ("2a5"))
echo ("For '-2.1e5': " + readNum ("-2.1e5"))
}
}
|
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
| #Forth | Forth | : is-numeric ( addr len -- )
2dup snumber? ?dup if \ not standard, but >number is more cumbersome to use
0< if
-rot type ." as integer = " .
else
2swap type ." as double = " <# #s #> type
then
else 2dup >float if
type ." as float = " f.
else
type ." isn't numeric in base " base @ dec.
then then ;
s" 1234" is-numeric \ 1234 as integer = 1234
s" 1234." is-numeric \ 1234. as double = 1234
s" 1234e" is-numeric \ 1234e as float = 1234.
s" $1234" is-numeric \ $1234 as integer = 4660 ( hex literal )
s" %1010" is-numeric \ %1010 as integer = 10 ( binary literal )
s" beef" is-numeric \ beef isn't numeric in base 10
hex
s" beef" is-numeric \ beef as integer = BEEF
s" &1234" is-numeric \ &1234 as integer = 4D2 ( decimal literal ) |
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
| #Lua | Lua | local find, format = string.find, string.format
local function printf(fmt, ...) print(format(fmt,...)) end
local pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'
function report_dup_char(subject)
local pos1, pos2, char = find(subject, pattern)
local prefix = format('"%s" (%d)', subject, #subject)
if pos1 then
local byte = char:byte()
printf("%s: '%s' (0x%02x) duplicates at %d, %d", prefix, char, byte, pos1, pos2)
else
printf("%s: no duplicates", prefix)
end
end
local show = report_dup_char
show('coccyx')
show('')
show('.')
show('abcABC')
show('XYZ ZYX')
show('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')
|
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
| #Ring | Ring |
load "stdlib.ring"
see "working..." + nl + nl
str = ["The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"I never give 'em hell, I just tell the truth, and they think it's hell.",
"..1111111111111111111111111111111111111111111111111111111111111117777888"]
strsave = str
for n = 1 to len(str)
for m = 1 to len(str[n])-1
if substr(str[n],m,1) = substr(str[n],m+1,1)
str[n] = left(str[n],m) + right(str[n],len(str[n])-m-1)
for p = len(str[n]) to 2 step -1
if substr(str[n],p,1) = substr(str[n],p-1,1)
str[n] = left(str[n],p-1) + right(str[n],len(str[n])-p)
ok
next
ok
next
next
for n = 1 to len(str)
see "" + len(strsave[n]) + "«««" + strsave[n] + "»»»" + nl
see "" + len(str[n]) + "«««" + str[n] + "»»»" + nl + nl
next
see "done..." + nl
|
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
| #Ruby | Ruby | strings = ["",
'"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 ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",]
strings.each do |str|
puts "«««#{str}»»» (size #{str.size})"
ssq = str.squeeze
puts "«««#{ssq}»»» (size #{ssq.size})"
puts
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
| #Rust | Rust | fn collapse_string(val: &str) -> String {
let mut output = String::new();
let mut chars = val.chars().peekable();
while let Some(c) = chars.next() {
while let Some(&b) = chars.peek() {
if b == c {
chars.next();
} else {
break;
}
}
output.push(c);
}
output
}
fn main() {
let tests = [
"122333444455555666666777777788888888999999999",
"",
"\"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 ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
];
for s in &tests {
println!("Old: {:>3} <<<{}>>>", s.len(), s);
let collapsed = collapse_string(s);
println!("New: {:>3} <<<{}>>>", collapsed.len(), collapsed);
println!();
}
} |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
use List::AllUtils qw(uniq);
use Unicode::UCD 'charinfo';
use Unicode::Normalize qw(NFC);
for my $str (
'',
' ',
'2',
'333',
'.55',
'tttTTT',
'4444 444k',
'Δ👍👨',
'🇬🇧🇬🇧🇬🇧🇬🇧',
"\N{LATIN CAPITAL LETTER A}\N{COMBINING DIAERESIS}\N{COMBINING MACRON}" .
"\N{LATIN CAPITAL LETTER A WITH DIAERESIS}\N{COMBINING MACRON}" .
"\N{LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON}"
) {
my @S;
push @S, NFC $1 while $str =~ /(\X)/g;
printf qq{\n"$str" (length: %d) has }, scalar @S;
my @U = uniq @S;
if (1 != @U and @U > 0) {
say 'different characters:';
for my $l (@U) {
printf "'%s' %s (0x%x) in positions: %s\n",
$l, charinfo(ord $l)->{'name'}, ord($l), join ', ', map { 1+$_ } grep { $l eq $S[$_] } 0..$#S;
}
} else {
say 'the same character in all positions.'
}
} |
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.
| #Racket | Racket |
#lang racket
;; Racket has traditional semaphores in addition to several higher level
;; synchronization tools. (Note that these semaphores are used for Racket's
;; green-threads, there are also "future semaphores" which are used for OS
;; threads, with a similar interface.)
;; ----------------------------------------------------------------------------
;; First, a bunch of code to run the experiments below
;; Only two philosophers to make it deadlock very fast
(define philosophers '(Aristotle Kant #|Spinoza Marx Russell|#))
(define (run-philosopher name fork1 fork2)
(define (show what) (displayln (~a name " " what)))
(define (loop)
(show "thinks") (sleep (* 2 (random))) (show "is hungry")
(grab-forks fork1 fork2 (λ() (show "eats") (sleep (random))))
(loop))
(thread loop))
(define (run:simple)
(define forks (for/list ([i philosophers]) (make-semaphore 1)))
(for ([i philosophers] [fork1 forks] [fork2 (cons (last forks) forks)])
(run-philosopher i fork1 fork2))
(sleep (* 60 60 24 365)))
;; ----------------------------------------------------------------------------
;; This is the naive implementation, which can be used to try getting a
;; deadlock.
(define (grab:naive fork1 fork2 eat!)
(semaphore-wait fork1)
(sleep (random)) ; to make deadlocks probable
(semaphore-wait fork2)
(eat!)
(semaphore-post fork1)
(semaphore-post fork2))
;; ----------------------------------------------------------------------------
;; One way to solve it is to release the first fork if the second is busy and
;; wait for a while.
(define (grab:release+wait fork1 fork2 eat!)
(semaphore-wait fork1)
(if (not (semaphore-try-wait? fork2))
;; couldn't grab the second fork, so release the first and wait
(begin (semaphore-post fork1)
(sleep (random))
(grab-forks fork1 fork2)) ; can swap them to improve chances
;; we have both forks
(begin (eat!)
(semaphore-post fork1)
(semaphore-post fork2))))
;; ----------------------------------------------------------------------------
;; Another solution is to label the forks and lock the lowest-id one first,
;; which makes the naive solution work.
(define (run:labeled-forks)
(define forks (for/list ([i philosophers]) (make-semaphore 1)))
;; the simple run used forks as (1 2 3 4) (4 1 2 3) -- so to implement this,
;; we can swap the two first ones: (4 2 3 4) (1 1 2 3)
(for ([i philosophers]
[fork1 (cons (last forks) (cdr forks))]
[fork2 (cons (first forks) forks)])
(run-philosopher i fork1 fork2))
(sleep (* 60 60 24 365)))
;; ----------------------------------------------------------------------------
;; Homework: implement the centralized waiter solution
;; ...
;; ----------------------------------------------------------------------------
;; Uncomment one of the following pairs to try it
;; (define grab-forks grab:naive)
;; (define run run:simple)
;; (define grab-forks grab:release+wait)
;; (define run run:simple)
;; (define grab-forks grab:naive)
;; (define run run:labeled-forks)
(run)
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #PureBasic | PureBasic | Procedure.s Discordian_Date(Y, M, D)
Protected DoY=DayOfYear(Date(Y,M,D,0,0,0)), Yold$=Str(Y+1166)
Dim S.s(4)
S(0)="Chaos": S(1)="Discord": S(2)="Confusion": S(3)="Bureaucracy"
S(4)="The Aftermath"
If (Y%4=0 And Y%100) Or Y%400=0
If M=2 And D=29
ProcedureReturn "St. Tib's Day, YOLD " + Yold$
ElseIf DoY>=2*30
DoY-1
EndIf
EndIf
ProcedureReturn S(DoY/73)+" "+Str(DoY%73)+", Yold "+Yold$
EndProcedure |
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)
| #REXX | REXX | /*REXX program determines the least costly path between two vertices given a list. */
$.= copies(9, digits() ) /*edge cost: indicates doesn't exist. */
xList= '!. @. $. beg fin bestP best$ xx yy' /*common EXPOSEd variables for subs. */
@abc= 'abcdefghijklmnopqrstuvwxyz' /*list of all the possible vertices. */
verts= 0; edges= 0 /*the number of vertices and also edges*/
do #=1 for length(@abc); _= substr(@abc, #, 1)
call value translate(_), #; @@.#= _
end /*#*/
call def$ a b 7 /*define an edge and its cost. */
call def$ a c 9 /* " " " " " " */
call def$ a f 14 /* " " " " " " */
call def$ b c 10 /* " " " " " " */
call def$ b d 15 /* " " " " " " */
call def$ c d 11 /* " " " " " " */
call def$ c f 2 /* " " " " " " */
call def$ d e 6 /* " " " " " " */
call def$ e f 9 /* " " " " " " */
beg= a; fin= e /*the BEGin and FINish vertexes. */
say; say 'number of edges = ' edges
say 'number of vertices = ' verts " ["left(@abc, verts)"]"
best$= $.; bestP=
say; do jv=2 to verts; call paths verts, jv; end /*jv*/
@costIs= right('cost =', 16)
if bestP==$. then say 'no path found.'
else say 'best path =' translate(bestP, @abc, 123456789) @costIs best$
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
apath: parse arg pathx 1 p1 2 p2 3; Lp= length(pathx); $= $.p1.p2
if $>=best$ then return
pv= p2; do ka=3 to Lp; _= substr(pathx, ka, 1)
if $.pv._>=best$ then return
$= $ + $.pv._; if $>=best$ then return; pv= _
end /*ka*/
best$= $; bestP= pathx
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
def$: parse arg xx yy $ .; if $.xx.yy<$ & $.yy.xx<$ | xx==yy then return
edges= edges + 1; verts= verts + ($.xx\==0) + ($.yy\==0)
$.xx= 0; $.yy= 0; $.xx.yy= $
say left('', 40) "cost of " @@.xx '───►' @@.yy " is " $
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
paths: procedure expose (xList); parse arg xx, yy, @.
do kp=1 for xx; _= kp; !.kp= _; end /*build a path list.*/
call .path 1
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
.path: procedure expose (xList); parse arg ?, _
if ?>yy then do; if @.1\==beg | @.yy\==fin then return
do #=1 for yy; _= _ || @.#; end /*#*/; call apath _
end
else do qq=1 for xx /*build vertex paths recursively*/
do kp=1 for ?-1; if @.kp==!.qq then iterate qq; end /*kp*/
@.?= !.qq; call .path ?+1 /*recursive call for next path. */
end /*qq*/
return |
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
| #PARI.2FGP | PARI/GP | dsum(n)=my(s); while(n, s+=n%10; n\=10); s
additivePersistence(n)=my(s); while(n>9, s++; n=dsum(n)); s
digitalRoot(n)=if(n, (n-1)%9+1, 0) |
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
| #Pascal | Pascal | program DigitalRoot;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
SysUtils, StrUtils;
// FPC has no Big mumbers implementation, Int64 will suffice.
procedure GetDigitalRoot(Value: Int64; Base: Byte; var DRoot, Pers: Integer);
var
i: Integer;
DigitSum: Int64;
begin
Pers := 0;
repeat
Inc(Pers);
DigitSum := 0;
while Value > 0 do
begin
Inc(DigitSum, Value mod Base);
Value := Value div Base;
end;
Value := DigitSum;
until Value < Base;
DRoot := Value;
End;
function IntToStrBase(Value: Int64; Base: Byte):String;
const
// usable up to 36-Base
DigitSymbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXY';
begin
Result := '';
while Value > 0 do
begin
Result := DigitSymbols[Value mod Base+1] + Result;
Value := Value div Base;
End;
End;
procedure Display(const Value: Int64; Base: Byte = 10);
var
DRoot, Pers: Integer;
StrValue: string;
begin
GetDigitalRoot(Value, Base, DRoot, Pers);
WriteLn(Format('%s(%d) has additive persistence %d and digital root %d.',
[IntToStrBase(Value, Base), Base, Pers, DRoot]));
End;
begin
WriteLn('--- Examples in 10-Base ---');
Display(627615);
Display(39390);
Display(588225);
Display(393900588225);
WriteLn('--- Examples in 16-Base ---');
Display(627615, 16);
Display(39390, 16);
Display(588225, 16);
Display(393900588225, 16);
ReadLn;
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?
| #Ruby | Ruby | def solve( problem )
lines = problem.split(".")
names = lines.first.scan( /[A-Z]\w*/ )
re_names = Regexp.union( names )
# Later on, search for these keywords (the word "not" is handled separately).
words = %w(first second third fourth fifth sixth seventh eighth ninth tenth
bottom top higher lower adjacent)
re_keywords = Regexp.union( words )
predicates = lines[1..-2].flat_map do |line| #build an array of lambda's
keywords = line.scan( re_keywords )
name1, name2 = line.scan( re_names )
keywords.map do |keyword|
l = case keyword
when "bottom" then ->(c){ c.first == name1 }
when "top" then ->(c){ c.last == name1 }
when "higher" then ->(c){ c.index( name1 ) > c.index( name2 ) }
when "lower" then ->(c){ c.index( name1 ) < c.index( name2 ) }
when "adjacent" then ->(c){ (c.index( name1 ) - c.index( name2 )).abs == 1 }
else ->(c){ c[words.index(keyword)] == name1 }
end
line =~ /\bnot\b/ ? ->(c){not l.call(c) } : l # handle "not"
end
end
names.permutation.detect{|candidate| predicates.all?{|predicate| predicate.(candidate)}}
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
| #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)
$"INTEGER_FORMAT" = comdat any
@main.a = private unnamed_addr constant [3 x i32] [i32 1, i32 3, i32 -5], align 4
@main.b = private unnamed_addr constant [3 x i32] [i32 4, i32 -2, i32 -1], align 4
@"INTEGER_FORMAT" = linkonce_odr unnamed_addr constant [4 x i8] c"%d\0A\00", comdat, align 1
; Function Attrs: noinline nounwind optnone uwtable
define i32 @dot_product(i32*, i32*, i64) #0 {
%4 = alloca i64, align 8 ;-- allocate copy of n
%5 = alloca i32*, align 8 ;-- allocate copy of b
%6 = alloca i32*, align 8 ;-- allocate copy of a
%7 = alloca i32, align 4 ;-- allocate sum
%8 = alloca i64, align 8 ;-- allocate i
store i64 %2, i64* %4, align 8 ;-- store a copy of n
store i32* %1, i32** %5, align 8 ;-- store a copy of b
store i32* %0, i32** %6, align 8 ;-- store a copy of a
store i32 0, i32* %7, align 4 ;-- store 0 in sum
store i64 0, i64* %8, align 8 ;-- store 0 in i
br label %loop
loop:
%9 = load i64, i64* %8, align 8 ;-- load i
%10 = load i64, i64* %4, align 8 ;-- load n
%11 = icmp ult i64 %9, %10 ;-- i < n
br i1 %11, label %loop_body, label %exit
loop_body:
%12 = load i32*, i32** %6, align 8 ;-- load a
%13 = load i64, i64* %8, align 8 ;-- load i
%14 = getelementptr inbounds i32, i32* %12, i64 %13 ;-- calculate a[i]
%15 = load i32, i32* %14, align 4 ;-- load a[i]
%16 = load i32*, i32** %5, align 8 ;-- load b
%17 = load i64, i64* %8, align 8 ;-- load i
%18 = getelementptr inbounds i32, i32* %16, i64 %17 ;-- calculate b[i]
%19 = load i32, i32* %18, align 4 ;-- load b[i]
%20 = mul nsw i32 %15, %19 ;-- temp = a[i] * b[i]
%21 = load i32, i32* %7, align 4 ;-- load sum
%22 = add nsw i32 %21, %20 ;-- add sum and temp
store i32 %22, i32* %7, align 4 ;-- store sum
%23 = load i64, i64* %8, align 8 ;-- load i
%24 = add i64 %23, 1 ;-- increment i
store i64 %24, i64* %8, align 8 ;-- store i
br label %loop
exit:
%25 = load i32, i32* %7, align 4 ;-- load sum
ret i32 %25 ;-- return sum
}
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
%1 = alloca [3 x i32], align 4 ;-- allocate a
%2 = alloca [3 x i32], align 4 ;-- allocate b
%3 = bitcast [3 x i32]* %1 to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* %3, i8* bitcast ([3 x i32]* @main.a to i8*), i64 12, i32 4, i1 false)
%4 = bitcast [3 x i32]* %2 to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* %4, i8* bitcast ([3 x i32]* @main.b to i8*), i64 12, i32 4, i1 false)
%5 = getelementptr inbounds [3 x i32], [3 x i32]* %2, i32 0, i32 0
%6 = getelementptr inbounds [3 x i32], [3 x i32]* %1, i32 0, i32 0
%7 = call i32 @dot_product(i32* %6, i32* %5, i64 3)
%8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"INTEGER_FORMAT", i32 0, i32 0), i32 %7)
ret i32 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } |
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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze: '{0}'", c)
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #zkl | zkl | fcn funnel(dxs, rule){
x:=0.0; rxs:=L();
foreach dx in (dxs){
rxs.append(x + dx);
x = rule(x,dx);
}
rxs
}
fcn mean(xs){ xs.sum(0.0)/xs.len() }
fcn stddev(xs){
m:=mean(xs);
(xs.reduce('wrap(sum,x){ sum + (x-m)*(x-m) },0.0)/xs.len()).sqrt();
}
fcn experiment(label,dxs,dys,rule){
rxs:=funnel(dxs,rule); rys:=funnel(dys,rule);
label.println();
"Mean x, y : %7.4f, %7.4f".fmt(mean(rxs), mean(rys)) .println();
"Std dev x, y : %7.4f, %7.4f".fmt(stddev(rxs),stddev(rys)).println();
println();
} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Cowgol | Cowgol | include "cowgol.coh";
typedef Dpt is int(1, 7);
# print combination if valid
sub print_comb(p: Dpt, s: Dpt, f: Dpt) is
var out: uint8[] := {'*',' ','*',' ','*','\n',0};
out[0] := p + '0';
out[2] := s + '0';
out[4] := f + '0';
if p != s and p != f and f != s and p+s+f == 12 then
print(&out[0]);
end if;
end sub;
print("P S F\n"); # header
var pol: Dpt := 2;
while pol <= 7 loop
var san: Dpt := 1;
while san <= 7 loop
var fire: Dpt := 1;
while fire <= 7 loop
print_comb(pol, san, fire);
fire := fire + 1;
end loop;
san := san + 1;
end loop;
pol := pol + 2;
end loop; |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #D | D |
import std.stdio, std.range;
void main() {
int sol = 1;
writeln("\t\tFIRE\t\tPOLICE\t\tSANITATION");
foreach( f; iota(1,8) ) {
foreach( p; iota(1,8) ) {
foreach( s; iota(1,8) ) {
if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
writefln("SOLUTION #%2d:\t%2d\t\t%3d\t\t%6d", sol++, f, p, s);
}
}
}
}
}
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface Delegator : NSObject {
id delegate;
}
- (id)delegate;
- (void)setDelegate:(id)obj;
- (NSString *)operation;
@end
@implementation Delegator
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)obj {
delegate = obj; // Weak reference
}
- (NSString *)operation {
if ([delegate respondsToSelector:@selector(thing)])
return [delegate thing];
return @"default implementation";
}
@end
// Any object may implement these
@interface NSObject (DelegatorDelegating)
- (NSString *)thing;
@end
@interface Delegate : NSObject
// Don't need to declare -thing because any NSObject has this method
@end
@implementation Delegate
- (NSString *)thing {
return @"delegate implementation";
}
@end
// Example usage
// Memory management ignored for simplification
int main() {
// Without a delegate:
Delegator *a = [[Delegator alloc] init];
NSLog(@"%d\n", [[a operation] isEqualToString:@"default implementation"]);
// With a delegate that does not implement thing:
[a setDelegate:@"A delegate may be any object"];
NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]);
// With a delegate that implements "thing":
Delegate *d = [[Delegate alloc] init];
[a setDelegate:d];
NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]);
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)
| #Pascal | Pascal |
program TrianglesOverlap;
{
The program looks for a separating line between the triangles. It's known that
only the triangle sides (produced) need to be considered as possible separators
(except in the degenerate case when both triangles are reduced to a point).
If there's a strong separator, i.e. one that is disjoint from at least one
of the triangles, then the triangles are disjoint. If there's only a weak
separator, i.e. one that intersects both triangles, then the triangles intersect
in a point or a line segment (this program doesn't work out which).
If there's no separator, then the triangles have an overlap of positive area.
}
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}}
uses Math, SysUtils;
{$DEFINE USE_FP}
{$IFDEF USE_FP}
type TCoordinate = double;
const TOLERANCE = 1.0E-6;
{$ELSE}
type TCoordinate = integer;
const TOLERANCE = 0;
{$ENDIF}
type TVertex = record
x, y : TCoordinate;
end;
function Vertex( x_in, y_in : TCoordinate) : TVertex;
begin
result.x := x_in;
result.y := y_in;
end;
// Result of testing sides of a triangle for separator.
// Values are arbitrary but must be in this numerical order
const
SEP_NO_TEST = -1; // triangle is a single point, no sides to be tested
SEP_NONE = 0; // didn't find a separator
SEP_WEAK = 1; // found a weak separator only
SEP_STRONG = 2; // found a strong separator
function EqualVertices( V, W : TVertex) : boolean;
begin
result := (Abs(V.x - W.x) <= TOLERANCE)
and (Abs(V.y - W.y) <= TOLERANCE);
end;
// Determinant: twice the signed area of triangle PQR.
function Det( P, Q, R : TVertex) : TCoordinate;
begin
result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y;
end;
// Get result of trying sides of LMN as separators.
function TrySides( L, M, N, P, Q, R : TVertex) : integer;
var
s, sMin, sMax: TCoordinate;
H, K : TVertex;
function TestSide( V, W : TVertex) : integer;
var
detP, detQ, detR, tMin, tMax : TCoordinate;
begin
result := SEP_NONE;
detP := Det( V, W, P);
detQ := Det( V, W, Q);
detR := Det( V, W, R);
tMin := Math.Min( Math.Min( detP, detQ), detR);
tMax := Math.Max( Math.Max( detP, detQ), detR);
if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then
result := SEP_STRONG
else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then
result := SEP_WEAK;
end;
begin
sMin := 0;
sMax := 0;
s := Det( L, M, N);
if (s <> 0) then begin // L, M, N are not collinear
if (s < 0) then sMin := s else sMax := s;
// Once we've found a strong separator, there's no need for further testing
result := TestSide( M, N);
if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L));
if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M));
end
else begin // s = 0 so L, M, N are collinear
// Look for distinct vertices from among L, M, N
H := L;
K := M;
if EqualVertices( H, K) then K := N;
if EqualVertices( H, K) then result := SEP_NO_TEST // L = M = N
else result := TestSide( H, K);
end;
end;
function Algo_5( A, B, C, D, E, F : TVertex) : integer;
begin
result := TrySides( A, B, C, D, E, F);
if (result < SEP_STRONG) then begin
result := Math.Max( result, TrySides( D, E, F, A, B, C));
if (result = SEP_NO_TEST) then begin // A = B = C and D = E = F
if EqualVertices( A, D) then result := SEP_WEAK
else result := SEP_STRONG;
end;
end;
end;
procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy,
Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate);
var
ovStr : string;
begin
case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy),
Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of
SEP_STRONG : ovStr := 'Disjoint';
SEP_NONE : ovStr := 'Overlap';
else ovStr := 'Borderline';
end;
WriteLn( SysUtils.Format(
'(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s',
[Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr]));
end;
// Main routine
begin
TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6);
TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0);
TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6);
TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4);
TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2);
TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4);
TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1);
end.
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #GAP | GAP | # Apparently GAP can only remove a file, not a directory
RemoveFile("input.txt");
# true
RemoveFile("docs");
# fail |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Go | Go | package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
// recursively removes contents:
os.RemoveAll("docs")
os.RemoveAll("/docs")
} |
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
| #Phix | Phix | with javascript_semantics
function minor(sequence a, integer x, integer y)
integer l = length(a)-1
sequence result = repeat(repeat(0,l),l)
for i=1 to l do
for j=1 to l do
result[i][j] = a[i+(i>=x)][j+(j>=y)]
end for
end for
return result
end function
function det(sequence a)
if length(a)=1 then
return a[1][1]
end if
integer res = 0,
sgn = 1
for i=1 to length(a) do
res += sgn*a[1][i]*det(minor(a,1,i))
sgn *= -1
end for
return res
end function
function perm(sequence a)
if length(a)=1 then
return a[1][1]
end if
integer res = 0
for i=1 to length(a) do
res += a[1][i]*perm(minor(a,1,i))
end for
return res
end function
constant tests = {
{{1, 2},
{3, 4}},
--Determinant: -2, permanent: 10
{{2, 9, 4},
{7, 5, 3},
{6, 1, 8}},
--Determinant: -360, permanent: 900
{{ 1, 2, 3, 4},
{ 4, 5, 6, 7},
{ 7, 8, 9, 10},
{10, 11, 12, 13}},
--Determinant: 0, permanent: 29556
{{ 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}},
--Determinant: 0, permanent: 6778800
{{5}},
--Determinant: 5, permanent: 5
{{1,0,0},
{0,1,0},
{0,0,1}},
--Determinant: 1, permanent: 1
{{0,0,1},
{0,1,0},
{1,0,0}},
--Determinant: -1, Permanent: 1
{{4,3},
{2,5}},
--Determinant: 14, Permanent: 26
{{2,5},
{4,3}},
--Determinant: -14, Permanent: 26
{{4,4},
{2,2}},
--Determinant: 0, Permanent: 16
{{7, 2, -2, 4},
{4, 4, 1, 7},
{11, -8, 9, 10},
{10, 5, 12, 13}},
--det: -4319 permanent: 10723
{{-2, 2, -3},
{-1, 1, 3},
{2 , 0, -1}}
--det: 18 permanent: 10
}
for i=1 to length(tests) do
sequence ti = tests[i]
?{det(ti),perm(ti)}
end for
|
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.
| #IDL | IDL | if not finite( <i>expression</i> ) then ... |
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.
| #J | J | funnydiv=: 0 { [: (,:'division by zero detected')"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %"_1 _ ] |
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.
| #Java | Java | public static boolean infinity(double numer, double denom){
return Double.isInfinite(numer/denom);
} |
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
| #Fortran | Fortran | FUNCTION is_numeric(string)
IMPLICIT NONE
CHARACTER(len=*), INTENT(IN) :: string
LOGICAL :: is_numeric
REAL :: x
INTEGER :: e
READ(string,*,IOSTAT=e) x
is_numeric = e == 0
END FUNCTION is_numeric |
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
| #Free_Pascal | Free Pascal | function isNumeric(const potentialNumeric: string): boolean;
var
potentialInteger: integer;
potentialReal: real;
integerError: integer;
realError: integer;
begin
integerError := 0;
realError := 0;
// system.val attempts to convert numerical value representations.
// It accepts all notations as they are accepted by the language,
// as well as the '0x' (or '0X') prefix for hexadecimal values.
val(potentialNumeric, potentialInteger, integerError);
val(potentialNumeric, potentialReal, realError);
isNumeric := (integerError = 0) or (realError = 0);
end; |
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
| #Maple | Maple | CheckUnique:=proc(s)
local i, index;
printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
for i from 1 to StringTools:-Length(s) do
index := StringTools:-SearchAll(s[i], s);
if (numelems([index]) > 1) then
printf("The given string has duplicated characters.\n");
printf("The first duplicated character is %a (0x%x) which appears at index %a.\n\n",
s[i], convert(s[i], 'bytes')[1], {index});
return;
end if;
end do;
# if no repeated found
printf("The given string has all unique characters.\n\n");
end proc:
# Test
CheckUnique("");
CheckUnique(".");
CheckUnique("abcABC");
CheckUnique("XYZ ZYX");
CheckUnique("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"); |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[UniqueCharacters]
UniqueCharacters[s_String] := Module[{c, len, good = True},
c = Characters[s];
len = Length[c];
Print[s, " with length ", len];
Do[
If[c[[i]] == c[[j]],
Print["Character ", c[[i]], " is repeated at positions ", i,
" and ", j];
good = False
]
,
{i, len - 1},
{j, i + 1, len}
];
If[good,
Print["No repeats"];
True
,
False
]
]
UniqueCharacters[""]
UniqueCharacters["."]
UniqueCharacters["abcABC"]
UniqueCharacters["XYZ ZYX"]
UniqueCharacters["1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"] |
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
| #Scala | Scala | object CollapsibleString {
/**Collapse a string (if possible)*/
def collapseString (s : String) : String = {
var res = s
var isOver = false
var i = 0
if(res.size == 0) res
else while(!isOver){
if(res(i) == res(i+1)){
res = res.take(i) ++ res.drop(i+1)
i-=1
}
i+=1
if(i==res.size-1) isOver = true
}
res
}
/**Check if a string is collapsible*/
def isCollapsible (s : String) : Boolean = collapseString(s).length != s.length
/**Display results as asked in the task*/
def reportResults (s : String) : String = {
val sCollapsed = collapseString(s)
val originalRes = "ORIGINAL : length = " + s.length() + ", string = «««" + s + "»»»"
val collapsedRes = "COLLAPSED : length = " + sCollapsed.length() + ", string = «««" + sCollapsed + "»»»"
//In order to avoid useless computations, the function isCollapsible isn't called
if(s.length != sCollapsed.length) originalRes + "\n" + collapsedRes + "\n" + "This string IS collapsible !"
else originalRes + "\n" + collapsedRes + "\n" + "This string is NOT collapsible !"
}
def main(args: Array[String]): Unit = {
println(reportResults(""))
println("------------")
println(reportResults("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "))
println("------------")
println(reportResults("..1111111111111111111111111111111111111111111111111111111111111117777888"))
println("------------")
println(reportResults("I never give 'em hell, I just tell the truth, and they think it's hell. "))
println("------------")
println(reportResults(" --- Harry S Truman "))
println("------------")
println(reportResults("The better the 4-wheel drive, the further you'll be from help when ya get stuck!"))
println("------------")
println(reportResults("headmistressship"))
println("------------")
println(reportResults("aardvark"))
}
} |
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
| #Phix | Phix | with javascript_semantics
procedure samechar(sequence s)
string msg = "all characters are the same"
integer l = length(s)
if l>=2 then
integer ch = s[1]
for i=2 to l do
integer si = s[i]
if si!=ch then
string su = utf32_to_utf8({si})
msg = sprintf(`first different character "%s"(#%02x) at position %d`,{su,si,i})
exit
end if
end for
end if
printf(1,"\"%s\" (length %d): %s\n",{utf32_to_utf8(s),l,msg})
end procedure
constant tests = {""," ","2","333",".55","tttTTT","4444 444k",
utf8_to_utf32("🐶🐶🐺🐶"),utf8_to_utf32("🎄🎄🎄🎄")}
for i=1 to length(tests) do samechar(tests[i]) end for
|
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.
| #Raku | Raku | class Fork {
has $!lock = Lock.new;
method grab($who, $which) {
say "$who grabbing $which fork";
$!lock.lock;
}
method drop($who, $which) {
say "$who dropping $which fork";
$!lock.unlock;
}
}
class Lollipop {
has $!channel = Channel.new;
method mine($who) { $!channel.send($who) }
method yours { $!channel.receive }
}
sub dally($sec) { sleep 0.01 + rand * $sec }
sub MAIN(*@names) {
@names ||= <Aristotle Kant Spinoza Marx Russell>;
my @lfork = Fork.new xx @names;
my @rfork = @lfork.rotate;
my $lollipop = Lollipop.new;
start { $lollipop.yours; }
my @philosophers = do for flat @names Z @lfork Z @rfork -> $n, $l, $r {
start {
sleep 1 + rand*4;
loop {
$l.grab($n,'left');
dally 1; # give opportunity for deadlock
$r.grab($n,'right');
say "$n eating";
dally 10;
$l.drop($n,'left');
$r.drop($n,'right');
$lollipop.mine($n);
sleep 1; # lick at least once
say "$n lost lollipop to $lollipop.yours(), now digesting";
dally 20;
}
}
}
sink await @philosophers;
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Python | Python | import datetime, calendar
DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
def ddate(year, month, day):
today = datetime.date(year, month, day)
is_leap_year = calendar.isleap(year)
if is_leap_year and month == 2 and day == 29:
return "St. Tib's Day, YOLD " + (year + 1166)
day_of_year = today.timetuple().tm_yday - 1
if is_leap_year and day_of_year >= 60:
day_of_year -= 1 # Compensate for St. Tib's Day
season, dday = divmod(day_of_year, 73)
return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
|
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)
| #Ring | Ring |
# Project : Dijkstra's algorithm
graph = [["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]]
dbegin = "a"
dend = "e"
powlen = pow(2,len(graph)) - 1
dgraph = list(powlen)
dtemp = list(powlen)
lenold = 10
lennew = 0
sumold = 30
sumnew = 0
powerset(graph)
for n = 1 to len(dgraph)
dtemp[n] = str2list(substr(dgraph[n], " ", nl))
next
for n = 1 to len(dtemp)
if len(dtemp[n]) > 3 and dtemp[n][1] = dbegin and dtemp[n][len(dtemp[n])-1] = dend
flag = 1
for m = 1 to len(dtemp[n])/3-1
if dtemp[n][m*3-1] != dtemp[n][m*3+1]
flag = 0
ok
next
if flag = 1
lennew = len(dtemp[n])
if lennew <= lenold
lenold = lennew
sumnew = 0
for m = 1 to len(dtemp[n])/3
sumnew = sumnew + dtemp[n][m*3]
next
if sumnew < sumold
sumold = sumnew
gend = dtemp[n]
ok
ok
ok
ok
next
str = ""
see dbegin + " " + dend + " : "
for m = 1 to len(gend)/3
str = str + gend[(m-1)*3 + 1] + " " + gend[(m-1)*3 + 2] + " " + gend[(m-1)*3 + 3] + " -> "
next
str = left(str,len(str)-4)
str = str + " cost : " + sumold + nl
see str + nl
func powerset(list)
s = "{"
p = 0
for i = 2 to (2 << len(list)) - 1 step 2
s = ""
for j = 1 to len(list)
if i & (1 << j)
s = s + list[j][1] + " " + list[j][2] + " " + list[j][3] + " "
ok
next
if right(s,1) = " "
s = left(s,len(s)-1)
ok
p = p + 1
dgraph[p] = s
next
|
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
| #Perl | Perl | #!perl
use strict;
use warnings;
use List::Util qw(sum);
my @digit = (0..9, 'a'..'z');
my %digit = map { +$digit[$_], $_ } 0 .. $#digit;
sub base {
my ($n, $b) = @_;
$b ||= 10;
die if $b > @digit;
my $result = '';
while( $n ) {
$result .= $digit[ $n % $b ];
$n = int( $n / $b );
}
reverse($result) || '0';
}
sub digi_root {
my ($n, $b) = @_;
my $inbase = base($n, $b);
my $additive_persistance = 0;
while( length($inbase) > 1 ) {
++$additive_persistance;
$n = sum @digit{split //, $inbase};
$inbase = base($n, $b);
}
$additive_persistance, $n;
}
MAIN: {
my @numbers = (5, 627615, 39390, 588225, 393900588225);
my @bases = (2, 3, 8, 10, 16, 36);
my $fmt = "%25s(%2s): persistance = %s, root = %2s\n";
if( eval { require Math::BigInt; 1 } ) {
push @numbers, Math::BigInt->new("5814271898167303040368".
"1039458302204471300738980834668522257090844071443085937");
}
for my $base (@bases) {
for my $num (@numbers) {
my $inbase = base($num, $base);
$inbase = 'BIG' if length($inbase) > 25;
printf $fmt, $inbase, $base, digi_root($num, $base);
}
print "\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?
| #Scala | Scala | import scala.math.abs
object Dinesman3 extends App {
val tenants = List("Baker", "Cooper2", "Fletcher4", "Miller", "Smith")
val (groundFloor, topFloor) = (1, tenants.size)
/** Rules with related tenants and restrictions*/
val exclusions =
List((suggestedFloor0: Map[String, Int]) => suggestedFloor0("Baker") != topFloor,
(suggestedFloor1: Map[String, Int]) => suggestedFloor1("Cooper2") != groundFloor,
(suggestedFloor2: Map[String, Int]) => !List(groundFloor, topFloor).contains(suggestedFloor2("Fletcher4")),
(suggestedFloor3: Map[String, Int]) => suggestedFloor3("Miller") > suggestedFloor3("Cooper2"),
(suggestedFloor4: Map[String, Int]) => abs(suggestedFloor4("Smith") - suggestedFloor4("Fletcher4")) != 1,
(suggestedFloor5: Map[String, Int]) => abs(suggestedFloor5("Fletcher4") - suggestedFloor5("Cooper2")) != 1)
tenants.permutations.map(_ zip (groundFloor to topFloor)).
filter(p => exclusions.forall(_(p.toMap))).toList match {
case Nil => println("No solution")
case xss => {
println(s"Solutions: ${xss.size}")
xss.foreach { l =>
println("possible solution:")
l.foreach(p => println(f"${p._1}%11s lives on floor number ${p._2}"))
}
}
}
} |
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
| #Logo | Logo | to dotprod :a :b
output apply "sum (map "product :a :b)
end
show dotprod [1 3 -5] [4 -2 -1] ; 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.