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
#FreeBASIC
FreeBASIC
sub make_S( M() as double, S() as double, i as uinteger, j as uinteger ) 'removes row j, column i from the matrix, stores result in S() dim as uinteger ii, jj, size=ubound(M), ix, jx for ii = 1 to size-1 if ii<i then ix = ii else ix = ii + 1 for jj = 1 to size-1 if jj<j then jx = jj else jx = jj + 1 S(ii, jj) = M(ix, jx) next jj next ii end sub   function deperminant( M() as double, det as boolean ) as double 'calculates the determinant or the permanent of a square matrix M 'det = true for determinant, false for permanent 'assumes a square matrix dim as uinteger size = ubound(M,1), i dim as integer sign dim as double S(1 to size-1, 1 to size-1) dim as double ret = 0.0, inc if size = 1 then return M(1,1) 'matrices of size < 3 are easy to calculate if size = 2 and det then return M(1,1)*M(2,2) - M(1,2)*M(2,1) if size = 2 then return M(1,1)*M(2,2) + M(1,2)*M(2,1) for i = 1 to size if det then sign = (-1)^(i+1) else sign = 1 'this bit is what distinguishes a determinant from a permanent make_S( M(), S(), i, 1 ) inc = sign*M(i,1)*deperminant( S(), det ) 'recursively call on submatrices ret += inc next i return ret end function   dim as double A(1 to 2, 1 to 2) = {{1,2},{3,4}}   dim as double B(1 to 4, 1 to 4) = {_ {1,2,3,4}, {4,5,6,7}, {7,8,9,10}, {10,11,12,13} }   dim as double C(1 to 5, 1 to 5) = {_ { 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 } }   print deperminant( A(), true ), deperminant( A(), false ) print deperminant( B(), true ), deperminant( B(), false ) print deperminant( C(), true ), deperminant( C(), false )
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.
#CLU
CLU
% This will catch a divide-by-zero exception and % return a oneof instead, with either the result or div_by_zero. % Overflow and underflow are resignaled. check_div = proc [T: type] (a, b: T) returns (otype) signals (overflow, underflow) where T has div: proctype (T,T) returns (T) signals (zero_divide, overflow, underflow) otype = oneof[div_by_zero: null, result: T]   return(otype$make_result(a/b)) except when zero_divide: return(otype$make_div_by_zero(nil)) end resignal overflow, underflow end check_div   % Try it start_up = proc () pair = struct[n, d: int] pairs: sequence[pair] := sequence[pair]$[ pair${n: 10, d: 2},  % OK pair${n: 10, d: 0},  % divide by zero pair${n: 20, d: 2}  % another OK one to show the program doesn't stop ]   po: stream := stream$primary_output() for p: pair in sequence[pair]$elements(pairs) do stream$puts(po, int$unparse(p.n) || "/" || int$unparse(p.d) || " = ") tagcase check_div[int](p.n, p.d) tag div_by_zero: stream$putl(po, "divide by zero") tag result (r: int): stream$putl(po, int$unparse(r)) end end end start_up
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.
#COBOL
COBOL
DIVIDE foo BY bar GIVING foobar ON SIZE ERROR DISPLAY "Division by zero detected!" END-DIVIDE
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
#Befunge
Befunge
~:0\`#v_:"+"-!#v_:"-"-!#v_::"E"-\"e"-*#v_ v v _v# < < 0< >~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_ v ^ $< > > $ v >~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_> v> ^ $< >$~:0\`#v_:"+"-#v_v v $_v# < <  :#< >~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!v 0 > v ^ $< v < << ^_^#-"-"< > "ciremuN">:#,_@ >>#$_"ciremun toN">:#,_@^ <
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
#Bracmat
Bracmat
43257349578692:/ F   260780243875083/35587980:/ S   247/30:~/# F   80000000000:~/# S
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
#D
D
import std.stdio;   void uniqueCharacters(string str) { writefln("input: `%s`, length: %d", str, str.length); foreach (i; 0 .. str.length) { foreach (j; i + 1 .. str.length) { if (str[i] == str[j]) { writeln("String contains a repeated character."); writefln("Character '%c' (hex %x) occurs at positions %d and %d.", str[i], str[i], i + 1, j + 1); writeln; return; } } } writeln("String contains no repeated characters."); writeln; }   void main() { 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
#Haskell
Haskell
import Text.Printf (printf) import Data.Maybe (catMaybes) import Control.Monad (guard)   input :: [String] input = [ "" , "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" , "headmistressship" , "\"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 " , "😍😀🙌💃😍😍😍🙌" ]   collapse :: Eq a => [a] -> [a] collapse = catMaybes . (\xs -> zipWith (\a b -> guard (a /= b) >> a) (Nothing : xs) (xs <> [Nothing])) . map Just   main :: IO () main = mapM_ (\(a, b) -> printf "old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" (length a) a (length b) b) $ ((,) <*> collapse) <$> input
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
#J
J
STRINGS =: <;._2]0 :0 "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 ) collapse =: (#~ (1 , 2 ~:/\ ])) ::(''"_) NB. copy dissimilar neighbors assert 1 2 3 2 3 1 2 1 -: collapse 1 2 3 2 2 2 2 3 1 1 2 2 1 NB. test task =: ,&(<@:(;~ (_6 + #)))&('<<<' , '>>>' ,~ ]) collapse NB. assemble the output task&> STRINGS NB. operate on the data +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+ |+-+------+ |+-+------+ | ||0|<<<>>>| ||0|<<<>>>| | |+-+------+ |+-+------+ | +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+ |+--+------------------------------------------------------------------------------+|+--+----------------------------------------------------------------------------+| ||72|<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>|||70|<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>|| |+--+------------------------------------------------------------------------------+|+--+----------------------------------------------------------------------------+| +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+ |+--+------------------------------------------------------------------------------+|+-+----------+ | ||72|<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>|||4|<<<.178>>>| | |+--+------------------------------------------------------------------------------+|+-+----------+ | +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+ |+--+------------------------------------------------------------------------------+|+--+---------------------------------------------------------------------------+ | ||72|<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>|||69|<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>| | |+--+------------------------------------------------------------------------------+|+--+---------------------------------------------------------------------------+ | +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+ |+--+------------------------------------------------------------------------------+|+--+-----------------------+ | ||72|<<< --- Harry S Truman >>>|||17|<<< - Hary S Truman >>>| | |+--+------------------------------------------------------------------------------+|+--+-----------------------+ | +-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+
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
#Fortran
Fortran
  program demo_verify implicit none call homogeneous('') call homogeneous('2') call homogeneous('333') call homogeneous('.55') call homogeneous('tttTTT') call homogeneous('4444 444k') contains   subroutine homogeneous(str) character(len=*),intent(in)  :: str character(len=:),allocatable :: ch character(len=*),parameter  :: g='(*(g0))' integer :: where if(len(str)>0)then;ch=str(1:1);else;ch='';endif where=verify(str,ch) if(where.eq.0)then write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"' else write(*,g)'STR: "',str,'" LEN: ',len(str), & & '. Multiple chars found. First difference at position ',where, & & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.' write(*,g)repeat(' ',where+5),'^' endif end subroutine homogeneous   function hex(ch) result(hexstr) character(len=1),intent(in) :: ch character(len=:),allocatable :: hexstr hexstr=repeat(' ',100) write(hexstr,'(Z0)')ch hexstr=trim(hexstr) end function hex   end program demo_verify  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
names = <|1 -> "Aristotle", 2 -> "Kant", 3 -> "Spinoza", 4 -> "Marx", 5 -> "Russell"|>; n = Length[names]; rp := Pause[RandomReal[4]]; PrintTemporary[Dynamic[Array[forks, n]]]; Clear[forks]; forks[_] := Null; With[{nf = n}, ParallelDo[ With[{i1 = i, i2 = Mod[i + 1, nf, 1]}, Do[Print[names[i], " thinking"]; rp; Print[names[i], " hungry"]; CriticalSection[{forks[i1], forks[i2]}, Print[names[i], " eating"]; rp], {2}]], {i, nf}]];
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#MAD
MAD
R DISCORDIAN DATE CALCULATION R R PUNCH CARD SHOULD CONTAIN - R MM/DD/YYYY R IN GREGORIAN CALENDAR   NORMAL MODE IS INTEGER   VECTOR VALUES MLENGT = 0 0,0,31,59,90,120,151,181,212,243,273,304,334 VECTOR VALUES TIBS = 0 $31HSAINT TIBS DAY IN THE Y.O.L.D. ,I4*$ VECTOR VALUES DISDAT = 0 $C,6H, DAY ,I2,S1,3HOF ,C,S1,16HIN THE Y.O.L.D. ,I4*$   VECTOR VALUES DISDAY = $SWEETMORN$, $BOOMTIME$, 0 $PUNGENDAY$, $PRICKLE-PRICKLE$, $SETTING ORANGE$ VECTOR VALUES DISSSN = $CHAOS$, $DISCORD$, 0 $CONFUSION$, $BUREAUCRACY$, $THE AFTERMATH$   VECTOR VALUES CLDAY = $10HCELEBRATE ,C,3HDAY*$ VECTOR VALUES CLFLUX = $10HCELEBRATE ,C,4HFLUX*$ VECTOR VALUES HOLY5 = $MUNG$,$MOJO$,$SYA$,$ZARA$,$MALA$ VECTOR VALUES HOLY50 = $CHAO$,$DISCO$,$CONFU$,$BURE$,$AF$   READ FORMAT GREG,GMONTH,GDAY,GYEAR VECTOR VALUES GREG = $2(I2,1H/),I4*$   WHENEVER GMONTH.E.2 .AND. GDAY.E.29 PRINT FORMAT TIBS, GYEAR + 1166 OTHERWISE YRDAY = MLENGT(GMONTH)+GDAY SEASON = YRDAY/73 DAY = YRDAY-SEASON*73 WKDAY = (YRDAY-1)-(YRDAY-1)/5*5 PRINT FORMAT DISDAT, DISDAY(WKDAY), DAY, 0 DISSSN(SEASON), GYEAR + 1166 WHENEVER DAY.E.5 PRINT FORMAT CLDAY, HOLY5(SEASON) OR WHENEVER DAY.E.50 PRINT FORMAT CLFLUX, HOLY50(SEASON) END OF CONDITIONAL END OF CONDITIONAL END OF PROGRAM
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)
#Maxima
Maxima
load(graphs)$ g: create_graph([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"], [6, "f"]], [[[1, 2], 7], [[1, 3], 9], [[1, 6], 14], [[2, 3], 10], [[2, 4], 15], [[3, 4], 11], [[3, 6], 2], [[4, 5], 6], [[5, 6], 9]], directed)$   shortest_weighted_path(1, 5, g); /* [26, [1, 3, 4, 5]] */
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
#Groovy
Groovy
class DigitalRoot { static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base) int additivePersistence = 0 if (bi.signum() < 0) { bi = bi.negate() } BigInteger biBase = BigInteger.valueOf(base) while (bi >= biBase) { number = bi.toString(base) bi = BigInteger.ZERO for (int i = 0; i < number.length(); i++) { bi = bi.add(new BigInteger(number.substring(i, i + 1), base)) } additivePersistence++ } return [additivePersistence, bi.intValue()] }   static void main(String[] args) { for (String arg : [627615, 39390, 588225, 393900588225]) { int[] results = calcDigitalRoot(arg, 10) println("$arg has additive persistence ${results[0]} and digital root of ${results[1]}") } } }
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Ring
Ring
  # Project : Digital root/Multiplicative digital root   load "stdlib.ring" root = newlist(10, 5) for r = 1 to 10 for x = 1 to 5 root[r][x] = 0 next next root2 = list(10) for y = 1 to 10 root2[y] = 0 next see "Number MDR MP" + nl num = [123321, 7739, 893, 899998] digroot(num) see nl num = 0:12000 digroot(num) see "First five numbers with MDR in first column:" + nl for n1 = 1 to 10 see "" + (n1-1) + " => " for n2 = 1 to 5 see "" + root[n1][n2] + " " next see nl next   func digroot(num) for n = 1 to len(num) sum = 0 numold = num[n] while true pro = 1 strnum = string(numold) for nr = 1 to len(strnum) pro = pro * number(strnum[nr]) next sum = sum + 1 numold = pro numn = string(num[n]) sp = 6 - len(string(num[n])) if sp > 0 for p = 1 to sp + 2 numn = " " + numn next ok if len(string(numold)) = 1 and len(num) < 5 see "" + numn + " " + numold + " " + sum + nl exit ok if len(string(numold)) = 1 and len(num) > 4 root2[numold+1] = root2[numold+1] + 1 if root2[numold+1] < 6 root[numold+1][root2[numold+1]] = num[n] ok exit ok end next  
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Ruby
Ruby
def mdroot(n) mdr, persist = n, 0 until mdr < 10 do mdr = mdr.digits.inject(:*) persist += 1 end [mdr, persist] end   puts "Number: MDR MP", "====== === ==" [123321, 7739, 893, 899998].each{|n| puts "%6d:  %d  %2d" % [n, *mdroot(n)]}   counter = Hash.new{|h,k| h[k]=[]} 0.step do |i| counter[mdroot(i).first] << i break if counter.values.all?{|v| v.size >= 5 } end puts "", "MDR: [n0..n4]", "=== ========" 10.times{|i| puts "%3d: %p" % [i, counter[i].first(5)]}
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?
#Nim
Nim
import algorithm   type   Person {.pure.} = enum Baker, Cooper, Fletcher, Miller, Smith Floor = range[1..5]   var floors: array[Person, Floor] = [Floor 1, 2, 3, 4, 5]   while true: if floors[Baker] != 5 and floors[Cooper] != 1 and floors[Fletcher] notin [1, 5] and floors[Miller] > floors[Cooper] and abs(floors[Smith] - floors[Fletcher]) != 1 and abs(floors[Fletcher] - floors[Cooper]) != 1: for person, floor in floors: echo person, " lives on floor ", floor break if not floors.nextPermutation(): echo "No solution found." break
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
#Groovy
Groovy
def dotProduct = { x, y -> assert x && y && x.size() == y.size() [x, y].transpose().collect{ xx, yy -> xx * yy }.sum() }
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
#J
J
  dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)  
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified character that is   immediately   followed by an identical character (or characters).   Another word choice could've been   duplicated character,   but that might have ruled out   (to some readers)   triplicated characters   ···   or more. {This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   PL/I   BIF:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   the   original string and its length   the resultant string and its length   the above strings should be "bracketed" with   <<<   and   >>>   (to delineate blanks)   «««Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here»»» Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except the 1st string: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Java
Java
    // Title: Determine if a string is squeezable   public class StringSqueezable {   public static void main(String[] args) { String[] testStrings = new String[] { "", "\"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 ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"};   String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold:  %2d <<<%s>>>%nnew:  %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } }   private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); }   }  
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.
#Java
Java
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction;   public class DemingsFunnel {   public static void main(String[] args) { double[] 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};   double[] 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};   experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0); experiment("Rule 2:", dxs, dys, (z, dz) -> -dz); experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz)); experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz); }   static void experiment(String label, double[] dxs, double[] dys, BiFunction<Double, Double, Double> rule) {   double[] resx = funnel(dxs, rule); double[] resy = funnel(dys, rule); System.out.println(label); System.out.printf("Mean x, y:  %.4f, %.4f%n", mean(resx), mean(resy)); System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy)); System.out.println(); }   static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) { double x = 0; double[] result = new double[input.length];   for (int i = 0; i < input.length; i++) { double rx = x + input[i]; x = rule.apply(x, input[i]); result[i] = rx; } return result; }   static double mean(double[] xs) { return Arrays.stream(xs).sum() / xs.length; }   static double stdDev(double[] xs) { double m = mean(xs); return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length); } }
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
#ALGOL_68
ALGOL 68
BEGIN # show possible department number allocations for police, sanitation and fire departments # # the police department number must be even, all department numbers in the range 1 .. 7 # # the sum of the department numbers must be 12 # INT max department number = 7; INT department sum = 12; print( ( "police sanitation fire", newline ) ); FOR police FROM 2 BY 2 TO max department number DO FOR sanitation TO max department number DO IF sanitation /= police THEN INT fire = ( department sum - police ) - sanitation; IF fire > 0 AND fire <= max department number AND fire /= sanitation AND fire /= police THEN print( ( whole( police, -6 ) , whole( sanitation, -11 ) , whole( fire, -5 ) , newline ) ) FI FI OD OD END
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".
#C.2B.2B
C++
  #include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional>   using namespace std; using namespace std::tr1; using std::tr1::function;   // interface for all delegates class IDelegate { public: virtual ~IDelegate() {} };   //interface for delegates supporting thing class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; };   // Does not handle Thing class DelegateA : virtual public IDelegate { };   // Handles Thing class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } };   class Delegator { public: std::string Operation() { if(Delegate) //have delegate if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) //delegate provides IThing interface return pThing->Thing();   return "default implementation"; }   shared_ptr<IDelegate> Delegate; };   int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator;   // No delegate std::cout << delegator.Operation() << std::endl;   // Delegate doesn't handle "Thing" delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl;   // Delegate handles "Thing" delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl;   /* Prints:   default implementation default implementation 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)
#Go
Go
package main   import "fmt"   type point struct { x, y float64 }   func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) }   type triangle struct { p1, p2, p3 point }   func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) }   func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) }   func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } }   func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps }   func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps }   func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) 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. var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3}   // for each edge E of t1 for i := 0; i < 3; i++ { j := (i + 1) % 3 // Check all points of t2 lay on the external side of edge E. // If they do, the triangles do not overlap. tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } }   // for each edge E of t2 for i := 0; i < 3; i++ { j := (i + 1) % 3 // Check all points of t1 lay on the external side of edge E. // If they do, the triangles do not overlap. tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } }   // The triangles overlap. return true }   func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 }   func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   // Need to allow reversed for this pair to avoid panic. t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap"))   t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap"))   fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
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.
#AWK
AWK
system("rm input.txt") system("rm /input.txt") system("rm -rf docs") system("rm -rf /docs")
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.
#Axe
Axe
DelVar "appvINPUT"
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
#FunL
FunL
def sgn( p ) = product( (if s(0) < s(1) xor i(0) < i(1) then -1 else 1) | (s, i) <- p.combinations(2).zip( (0:p.length()).combinations(2) ) )   def perm( m ) = sum( product(m(i, sigma(i)) | i <- 0:m.length()) | sigma <- (0:m.length()).permutations() )   def det( m ) = sum( sgn(sigma)*product(m(i, sigma(i)) | i <- 0:m.length()) | sigma <- (0:m.length()).permutations() )
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
#GLSL
GLSL
  mat4 m1 = mat3(1, 2, 3, 4, 5, 6, 7, 8 9,10,11,12, 13,14,15,16);   float d = det(m1);  
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.
#Common_Lisp
Common Lisp
(handler-case (/ x y) (division-by-zero () (format t "division by zero caught!~%")))
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.
#D
D
import std.stdio, std.string, std.math, std.traits;   string divCheck(T)(in T numer, in T denom) if (isIntegral!T || isFloatingPoint!T) { Unqual!(typeof(numer / denom)) result; string msg;   static if (isIntegral!T) { try { result = numer / denom; } catch(Error e) { msg = "| " ~ e.msg ~ " (by Error)"; result = T.max; } } else { // Floating Point Type. result = numer / denom; if (numer.isNormal && result.isInfinity) { msg = "| Division by Zero"; } else if (result != 0 && !result.isNormal) { if (numer.isNaN) msg = "| NaN numerator"; else if (denom.isNaN) msg = "| NaN denominator"; else if (numer.isInfinity) msg = "| Inf numerator"; else msg = "| NaN (Zero Division by Zero)"; } }   return format("%5s %s", format("%1.1g", real(result)), msg); }   void main() { writeln("Division with check:"); writefln("int 1/ 0:  %s", divCheck(1, 0)); writefln("ubyte 1/ 0:  %s", divCheck(ubyte(1), ubyte(0))); writefln("real 1/ 0:  %s", divCheck(1.0L, 0.0L)); writefln("real -1/ 0:  %s", divCheck(-1.0L, 0.0L)); writefln("real 0/ 0:  %s", divCheck(0.0L, 0.0L)); writeln; writefln("real -4/-2:  %s", divCheck(-4.0L,-2.0L)); writefln("real 2/-inf: %s", divCheck(2.0L, -real.infinity)); writeln; writefln("real -inf/-2:  %s", divCheck(-real.infinity, -2.0L)); writefln("real +inf/-2:  %s", divCheck(real.infinity, -2.0L)); writefln("real nan/-2:  %s", divCheck(real.nan, -2.0L)); writefln("real -2/ nan: %s", divCheck(-2.0L, real.nan)); writefln("real nan/ 0:  %s", divCheck(real.nan, 0.0L)); writefln("real inf/ inf: %s", divCheck(real.infinity, real.infinity)); writefln("real nan/ nan: %s", divCheck(real.nan, real.nan)); }
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
#Burlesque
Burlesque
  ps^^-]to{"Int""Double"}\/~[\/L[1==?*  
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
#C
C
#include <ctype.h> #include <stdlib.h> int isNumeric (const char * s) { if (s == NULL || *s == '\0' || isspace(*s)) return 0; char * p; strtod (s, &p); return *p == '\0'; }
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
#Delphi
Delphi
  program Determine_if_a_string_has_all_unique_characters;   {$APPTYPE CONSOLE}   uses System.SysUtils;   procedure string_has_repeated_character(str: string); var len, i, j: Integer; begin len := length(str); Writeln('input: \', str, '\, length: ', len); for i := 1 to len - 1 do begin for j := i + 1 to len do begin if str[i] = str[j] then begin Writeln('String contains a repeated character.'); Writeln('Character "', str[i], '" (hex ', ord(str[i]).ToHexString, ') occurs at positions ', i + 1, ' and ', j + 1, '.'#10); Exit; end; end; end; Writeln('String contains no repeated characters.' + sLineBreak); end;   begin string_has_repeated_character(''); string_has_repeated_character('.'); string_has_repeated_character('abcABC'); string_has_repeated_character('XYZ ZYX'); string_has_repeated_character('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'); readln; 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
#Java
Java
  // Title: Determine if a string is collapsible   public class StringCollapsible {   public static void main(String[] args) { for ( String s : new String[] { "", "\"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 ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}) { String result = collapse(s); System.out.printf("old:  %2d <<<%s>>>%nnew:  %2d <<<%s>>>%n%n", s.length(), s, result.length(), result); } }   private static String collapse(String in) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) ) { sb.append(in.charAt(i)); } } return sb.toString(); }   }  
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
#FreeBASIC
FreeBASIC
dim as string s, nxt   input "Enter string: ", s   if len(s)<2 then 'A string with one or zero characters passes by default print "All characters are the same." end end if   dim as ubyte i   for i = 1 to len(s)-1 nxt = mid(s, i+1, 1) if mid(s, i, 1)<>nxt then 'if any character differs from the previous one print "First non-matching char is "+nxt print "It occurs at position "+str(i+1) print "Its hex value is "+hex(asc(nxt)) end end if next i   'otherwise, success! print "All characters are the same."
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
#Go
Go
package main   import "fmt"   func analyze(s string) { chars := []rune(s) le := len(chars) fmt.Printf("Analyzing %q which has a length of %d:\n", s, le) if le > 1 { for i := 1; i < le; i++ { if chars[i] != chars[i-1] { fmt.Println(" Not all characters in the string are the same.") fmt.Printf("  %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1) return } } } fmt.Println(" All characters in the string are the same.\n") }   func main() { strings := []string{ "", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄", } for _, s := range strings { analyze(s) } }
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.
#Modula-3
Modula-3
MODULE DiningPhilosophers EXPORTS Main;   IMPORT IO, Random, Thread;   CONST   PartySize = 5; (* modify for more/fewer philosophers *)   TYPE   Closure = Thread.Closure OBJECT (* thread information *) which: [1..PartySize]; (* identifies the thread *) OVERRIDES apply := Live; (* procedure to execute *) END;   VAR   (* how long to eat/think *) random: Random.T;   (* controls access to resources *) test := NEW(MUTEX); forks := NEW(Thread.Condition); (* condition variable, used for signaling *) forkAvailable := ARRAY[1..PartySize] OF BOOLEAN { TRUE, TRUE, TRUE, TRUE, TRUE }; (* the philosophers/tasks *) thread: ARRAY[1..PartySize] OF Thread.T; name := ARRAY[1..PartySize] OF TEXT { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" };   PROCEDURE PlaceAvailable(): CARDINAL = (* Determines whether a place is available at the table. If so, returns the place number. Otherwise, returns 0. We consider a place available if and only if *both* forks are free. *) BEGIN FOR i := 1 TO PartySize DO IF forkAvailable[i] AND forkAvailable[((i+1) MOD PartySize) + 1] THEN RETURN i; END; END; RETURN 0; END PlaceAvailable;   PROCEDURE Live(philosopher: Closure): REFANY = (* philosophers eat, sleep, ... and that's about it *) VAR place: CARDINAL; BEGIN WITH which = philosopher.which DO WHILE TRUE DO (* first make sure a place is available: both forks must be free! *) LOCK test DO place := PlaceAvailable(); (* if not, release mutex and use condition variable to wait for one *) WHILE place = 0 DO IO.Put(name[which]); IO.Put(" starving!\n"); Thread.Wait(test, forks); (* in Modula-3 we arrive here only if we have the lock again *) place := PlaceAvailable(); END; (* a place has come available! seize the forks while mutex is locked *) forkAvailable[place] := FALSE; forkAvailable[(place MOD PartySize) + 1] := FALSE; IO.Put(name[which]); IO.Put(" eating at place "); IO.PutInt(place); IO.PutChar('\n'); END; Thread.Pause(FLOAT(random.integer(1,3), LONGREAL)); (* put down the forks *) forkAvailable[place] := TRUE; forkAvailable[(place MOD PartySize) + 1] := TRUE; Thread.Signal(forks); (* signal the condition variable *) LOCK test DO IO.Put(name[which]); IO.Put(" thinking\n"); END; Thread.Pause(FLOAT(random.integer(1,3), LONGREAL)); END; (* WHILE *) END; (* WITH *) RETURN NIL; END Live;   BEGIN random := NEW(Random.Default).init(); (* bring philosophers to life *) FOR i := 1 TO PartySize DO thread[i] := Thread.Fork(NEW(Closure, apply := Live, which := i)); END; (* We need to wait, otherwise the program will terminate, and the philosophers with it. Technically we could wait for just one philosopher, but in the interest of symmetry... *) FOR i := 1 TO PartySize DO EVAL Thread.Join(thread[i]); END; END DiningPhilosophers.
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Maple
Maple
convertDiscordian := proc(year, month, day) local days31, days30, daysThisYear, i, dYear, dMonth, dDay, seasons, week, dayOfWeek; days31 := [1, 3, 5, 7, 8, 10, 12]; days30 := [4, 6, 9, 11]; if month < 1 or month >12 then error "Invalid month: %1", month; end if; if (member(month, days31) and day > 31) or (member(month, days30) and day > 30) or (month = 2 and day > 29) or day < 1 then error "Invalid date: %1", day; end if; dYear := year + 1166; if month = 2 and day = 29 then printf("The date is St. Tib's Day, YOLD %a.\n", dYear); else seasons := ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]; week := ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]; daysThisYear := 0; for i to month-1 do if member(i, days31) then daysThisYear := daysThisYear + 31; elif member(i, days30) then daysThisYear := daysThisYear + 30; else daysThisYear := daysThisYear + 28; end if; end do; daysThisYear := daysThisYear + day -1; dMonth := seasons[trunc((daysThisYear) / 73)+1]; dDay := daysThisYear mod 73 +1; dayOfWeek := week[daysThisYear mod 5 +1]; printf("The date is %s %s %s, YOLD %a.\n", dayOfWeek, dMonth, convert(dDay, ordinal), dYear); end if; end proc:   convertDiscordian (2016, 1, 1); convertDiscordian (2016, 2, 29); convertDiscordian (2016, 12, 31);
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)
#Nim
Nim
  # Dijkstra algorithm.   from algorithm import reverse import sets import strformat import tables   type Edge = tuple[src, dst: string; cost: int] Graph = object vertices: HashSet[string] neighbours: Table[string, seq[tuple[dst: string, cost: float]]]   #---------------------------------------------------------------------------------------------------   proc initGraph(edges: openArray[Edge]): Graph = ## Initialize a graph from an edge list. ## Use floats for costs in order to compare to Inf value.   for (src, dst, cost) in edges: result.vertices.incl(src) result.vertices.incl(dst) result.neighbours.mgetOrPut(src, @[]).add((dst, cost.toFloat))   #---------------------------------------------------------------------------------------------------   proc dijkstraPath(graph: Graph; first, last: string): seq[string] = ## Find the path from "first" to "last" which minimizes the cost.   var dist = initTable[string, float]() var previous = initTable[string, string]() var notSeen = graph.vertices for vertex in graph.vertices: dist[vertex] = Inf dist[first] = 0   while notSeen.card > 0: # Search vertex with minimal distance. var vertex1: string var mindist = Inf for vertex in notSeen: if dist[vertex] < mindist: vertex1 = vertex mindist = dist[vertex] if vertex1 == last: break notSeen.excl(vertex1) # Find shortest paths to neighbours. for (vertex2, cost) in graph.neighbours.getOrDefault(vertex1): if vertex2 in notSeen: let altdist = dist[vertex1] + cost if altdist < dist[vertex2]: # Found a shorter path to go to vertex2. dist[vertex2] = altdist previous[vertex2] = vertex1 # To go to vertex2, go through vertex1.   # Build the path. var vertex = last while vertex.len > 0: result.add(vertex) vertex = previous.getOrDefault(vertex) result.reverse()   #---------------------------------------------------------------------------------------------------   proc printPath(path: seq[string]) = ## Print a path. stdout.write(fmt"Shortest path from '{path[0]}' to '{path[^1]}': {path[0]}") for i in 1..path.high: stdout.write(fmt" → {path[i]}") stdout.write('\n')   #---------------------------------------------------------------------------------------------------   let graph = initGraph([("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)]) printPath(graph.dijkstraPath("a", "e")) printPath(graph.dijkstraPath("a", "f"))  
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
#Haskell
Haskell
import Data.Bifunctor (bimap) import Data.List (unfoldr) import Data.Tuple (swap)   digSum :: Int -> Int -> Int digSum base = sum . unfoldr f where f 0 = Nothing f n = Just (swap (quotRem n base))   digRoot :: Int -> Int -> (Int, Int) digRoot base = head . dropWhile ((>= base) . snd) . iterate (bimap succ (digSum base)) . (,) 0   main :: IO () main = do putStrLn "in base 10:" mapM_ (print . ((,) <*> digRoot 10)) [627615, 39390, 588225, 393900588225]
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Scala
Scala
import Stream._   object MDR extends App {   def mdr(x: BigInt, base: Int = 10): (BigInt, Long) = { def multiplyDigits(x: BigInt): BigInt = ((x.toString(base) map (_.asDigit)) :\ BigInt(1))(_*_) def loop(p: BigInt, c: Long): (BigInt, Long) = if (p < base) (p, c) else loop(multiplyDigits(p), c+1) loop(multiplyDigits(x), 1) }   printf("%15s\t%10s\t%s\n","Number","MDR","MP") printf("%15s\t%10s\t%s\n","======","===","==") Seq[BigInt](123321, 7739, 893, 899998, BigInt("393900588225"), BigInt("999999999999")) foreach {x => val (s, c) = mdr(x) printf("%15s\t%10s\t%2s\n",x,s,c) } println   val mdrs: Stream[Int] => Stream[(Int, BigInt)] = i => i map (x => (x, mdr(x)._1))   println("MDR: [n0..n4]") println("==== ========") ((for {i <- 0 to 9} yield (mdrs(from(0)) take 11112 toList) filter {_._2 == i}) .map {_ take 5} map {xs => xs map {_._1}}).zipWithIndex .foreach{p => printf("%3s: [%s]\n",p._2,p._1.mkString(", "))}   }
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?
#Perl
Perl
use strict; use warnings; use feature <state say>; use List::Util 1.33 qw(pairmap); use Algorithm::Permute qw(permute);   our %predicates = ( # | object | sprintf format for Perl expression | # --------------------+-----------+------------------------------------+ 'on bottom' => [ '' , '$f[%s] == 1' ], 'on top' => [ '' , '$f[%s] == @f' ], 'lower than' => [ 'person' , '$f[%s] < $f[%s]' ], 'higher than' => [ 'person' , '$f[%s] > $f[%s]' ], 'directly below' => [ 'person' , '$f[%s] == $f[%s] - 1' ], 'directly above' => [ 'person' , '$f[%s] == $f[%s] + 1' ], 'adjacent to' => [ 'person' , 'abs($f[%s] - $f[%s]) == 1' ], 'on' => [ 'ordinal' , '$f[%s] == \'%s\'' ], );   our %nouns = ( 'person' => qr/[a-z]+/i, 'ordinal' => qr/1st | 2nd | 3rd | \d+th/x, );   sub parse_and_solve { my @facts = @_;   state $parser = qr/^(?<subj>$nouns{person}) (?<not>not )?(?|@{[ join '|', pairmap { "(?<pred>$a)" . ($b->[0] ? " (?<obj>$nouns{$b->[0]})" : '') } %predicates ]})$/;   my (@expressions, %ids, $i); my $id = sub { defined $_[0] ? $ids{$_[0]} //= $i++ : () };   foreach (@facts) { /$parser/ or die "Cannot parse '$_'\n";   my $pred = $predicates{$+{pred}}; { no warnings; my $expr = '(' . sprintf($pred->[1], $id->($+{subj}), $pred->[0] eq 'person' ? $id->($+{obj}) : $+{obj}). ')'; $expr = '!' . $expr if $+{not}; push @expressions, $expr; } }   my @f = 1..$i; eval ' permute { say join(", ", pairmap { "$f[$b] $a" } %ids) if ('.join(' && ', @expressions).'); } @f;'; }
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
#Haskell
Haskell
dotp :: Num a => [a] -> [a] -> a dotp a b | length a == length b = sum (zipWith (*) a b) | otherwise = error "Vector sizes must match"   main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 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
#jq
jq
# Assume $c is specified as a single character correctly def squeeze($c): gsub("[\($c)]+"; $c);   def Guillemets: "«««\(.)»»»";   def Squeeze(s; $c): "Squeeze character: \($c)", (s | "Original: \(Guillemets) has length \(length)", (squeeze($c) | "result is \(Guillemets) with length \(length)")), "";
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
#J_2
J
NB. Note |.!.1 here instead of the APL version's 1 , }. to more elegantly handle the null case in J sq =: ] #~ ~: +. _1 |.!.1 ] ~: 1 |. ]
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.
#Julia
Julia
# Run from Julia REPL to see the plots. using Statistics, Distributions, Plots   const racket_xdata = [-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]   const racket_ydata = [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]   const rules = [(x, y, dx, dy) -> [0, 0], (x, y, dx, dy) -> [-dx, -dy], (x, y, dx, dy) -> [-x - dx, -y - dy], (x, y, dx, dy) -> [x + dx, y + dy]] const plots, colors = plot(layout=(1,2)), [:red, :green, :blue, :yellow]   function makedata() radius_angles = zip(rand(Normal(), 100), rand(Uniform(-π, π), 100)) zip([z[1] * cos(z[2]) for z in radius_angles], [z[1] * sin(z[2]) for z in radius_angles]) end   function testfunnel(useracket=true) for (i, rule) in enumerate(rules) origin = [0.0, 0.0] xvec, yvec = Float64[], Float64[] for point in (useracket ? zip(racket_xdata, racket_ydata) : makedata()) push!(xvec, origin[1] + point[1]) push!(yvec, origin[2] + point[2]) origin .= rule(origin[1], origin[2], point[1], point[2]) end println("Rule $i results:") println("mean x: ", round(mean(xvec), digits=4), " std x: ", round(std(xvec, corrected=false), digits=4), " mean y: ", round(mean(yvec), digits=4), " std y: ", round(std(yvec, corrected=false), digits=4)) scatter!(xvec, yvec, color=colors[i], subplot=(useracket ? 1 : 2), title= useracket ? "Racket Data" : "Random Data", label="Rule $i") end end   println("\nUsing Racket data.") testfunnel() println("\nUsing new data.") testfunnel(false) display(plots)  
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.
#Kotlin
Kotlin
// version 1.1.3   typealias Rule = (Double, Double) -> Double   val dxs = doubleArrayOf( -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 )   val dys = doubleArrayOf( 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 )   fun funnel(da: DoubleArray, rule: Rule): DoubleArray { var x = 0.0 val result = DoubleArray(da.size) for ((i, d) in da.withIndex()) { result[i] = x + d x = rule(x, d) } return result }   fun mean(da: DoubleArray) = da.average()   fun stdDev(da: DoubleArray): Double { val m = mean(da) return Math.sqrt(da.map { (it - m) * (it - m) }.average()) }   fun experiment(label: String, rule: Rule) { val rxs = funnel(dxs, rule) val rys = funnel(dys, rule) println("$label  : x y") println("Mean  : ${"%7.4f, %7.4f".format(mean(rxs), mean(rys))}") println("Std Dev : ${"%7.4f, %7.4f".format(stdDev(rxs), stdDev(rys))}") println() }   fun main(args: Array<String>) { experiment("Rule 1") { _, _ -> 0.0 } experiment("Rule 2") { _, dz -> -dz } experiment("Rule 3") { z, dz -> -(z + dz) } experiment("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
#ALGOL_W
ALGOL W
begin  % show possible department number allocations for police, sanitation and fire departments %  % the police department number must be even, all department numbers in the range 1 .. 7  %  % the sum of the department numbers must be 12  % integer MAX_DEPARTMENT_NUMBER, DEPARTMENT_SUM; MAX_DEPARTMENT_NUMBER := 7; DEPARTMENT_SUM  := 12; write( "police sanitation fire" ); for police := 2 step 2 until MAX_DEPARTMENT_NUMBER do begin for sanitation := 1 until MAX_DEPARTMENT_NUMBER do begin IF sanitation not = police then begin integer fire; fire := ( DEPARTMENT_SUM - police ) - sanitation; if fire > 0 and fire <= MAX_DEPARTMENT_NUMBER and fire not = sanitation and fire not = police then begin write( s_w := 0, i_w := 6, police, i_w := 11, sanitation, i_w := 5, fire ) end if_valid_combination end if_sanitation_ne_police end for_sanitation end for_police end.
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
#APL
APL
'PSF'⍪(⊢(⌿⍨)((∪≡⊢)¨↓∧(0=2|1⌷[2]⊢)∧12=+/))↑,⍳3/7
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".
#Clojure
Clojure
(defprotocol Thing (thing [_]))   (defprotocol Operation (operation [_]))   (defrecord Delegator [delegate] Operation (operation [_] (try (thing delegate) (catch IllegalArgumentException e "default implementation"))))   (defrecord Delegate [] Thing (thing [_] "delegate implementation"))
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".
#CoffeeScript
CoffeeScript
  class Delegator operation: -> if @delegate and typeof (@delegate.thing) is "function" return @delegate.thing() "default implementation"   class Delegate thing: -> "Delegate Implementation"   testDelegator = -> # Delegator with no delegate. a = new Delegator() console.log a.operation()   # Delegator with delegate not implementing "thing" a.delegate = "A delegate may be any object" console.log a.operation()   # Delegator with delegate that does implement "thing" a.delegate = new Delegate() console.log a.operation()   testDelegator()  
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)
#Groovy
Groovy
import java.util.function.BiFunction   class TriangleOverlap { private static class Pair { double first double second   Pair(double first, double second) { this.first = first this.second = second }   @Override String toString() { return String.format("(%s, %s)", first, second) } }   private static class Triangle { Pair p1, p2, p3   Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1 this.p2 = p2 this.p3 = p3 }   @Override String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3) } }   private static double det2D(Triangle t) { Pair p1 = t.p1 Pair p2 = t.p2 Pair p3 = t.p3 return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) }   private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3 t.p3 = t.p2 t.p2 = a } else throw new RuntimeException("Triangle has wrong winding direction") } }   private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps }   private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps }   private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true) }   private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true) }   private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { // Triangles must be expressed anti-clockwise checkTriWinding(t1, allowedReversed) checkTriWinding(t2, allowedReversed) // 'onBoundary' determines whether points on boundary are considered as colliding or not BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap.&boundaryCollideChk : TriangleOverlap.&boundaryDoesntCollideChk Pair[] lp1 = [t1.p1, t1.p2, t1.p3] Pair[] lp2 = [t2.p1, t2.p2, t2.p3]   // for each edge E of t1 for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3 // Check all points of t2 lay on the external side of edge E. // If they do, the triangles do not overlap. if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false }   // for each edge E of t2 for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3 // Check all points of t1 lay on the external side of edge E. // If they do, the triangles do not overlap. if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false }   // The triangles overlap return true }   static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)) Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)) printf("%s and\n%s\n", t1, t2) if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   // need to allow reversed for this pair to avoid exception t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)) t2 = t1 printf("\n%s and\n%s\n", t1, t2) if (triTri2D(t1, t2, 0.0, true)) { println("overlap (reversed)") } else { println("do not overlap") }   t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)) t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)) printf("\n%s and\n%s\n", t1, t2) if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   t1.p3 = new Pair(2.5, 5.0) t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)) printf("\n%s and\n%s\n", t1, t2) if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)) t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)) printf("\n%s and\n%s\n", t1, t2) if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)) printf("\n%s and\n%s\n", t1, t2) if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)) t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)) printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") if (triTri2D(t1, t2)) { println("overlap") } else { println("do not overlap") }   printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points do not collide") if (triTri2D(t1, t2, 0.0, false, false)) { println("overlap") } else { println("do not overlap") } } }
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.
#BASIC
BASIC
  KILL "INPUT.TXT" KILL "C:\INPUT.TXT" SHELL "RMDIR /S /Q DIR" SHELL "RMDIR /S /Q C:\DIR"  
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.
#Batch_File
Batch File
del input.txt rd /s /q docs   del \input.txt rd /s /q \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
#Go
Go
package main   import ( "fmt" "permute" )   func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return }   func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return }   var m2 = [][]float64{ {1, 2}, {3, 4}}   var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}}   func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
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.
#Delphi
Delphi
program DivideByZero;   {$APPTYPE CONSOLE}   uses SysUtils;   var a, b: Integer; begin a := 1; b := 0; try WriteLn(a / b); except on e: EZeroDivide do Writeln(e.Message); end; end.
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
divcheck x y: true try: drop / x y catch value-error: not   if divcheck 1 0:  !print "Okay" else:  !print "Division by zero"
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
#C.23
C#
public static bool IsNumeric(string s) { double Result; return double.TryParse(s, out Result); // TryParse routines were added in Framework version 2.0. }   string value = "123"; if (IsNumeric(value)) { // do something }
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
#C.2B.2B
C++
#include <sstream> // for istringstream   using namespace std;   bool isNumeric( const char* pszInput, int nNumberBase ) { istringstream iss( pszInput );   if ( nNumberBase == 10 ) { double dTestSink; iss >> dTestSink; } else if ( nNumberBase == 8 || nNumberBase == 16 ) { int nTestSink; iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink; } else return false;   // was any input successfully consumed/converted? if ( ! iss ) return false;   // was all the input successfully consumed/converted? return ( iss.rdbuf()->in_avail() == 0 ); }  
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
#Erlang
Erlang
  -module(string_examples). -export([all_unique/1, all_unique_examples/0]).   all_unique(String) -> CharPosPairs = lists:zip(String, lists:seq(1, length(String))), Duplicates = [{Char1, Pos1, Pos2} || {Char1, Pos1} <- CharPosPairs, {Char2, Pos2} <- CharPosPairs, Char1 =:= Char2, Pos2 > Pos1], case Duplicates of [] -> all_unique; [{Char, P1, P2}|_] -> {not_all_unique, Char, P1, P2} end.   all_unique_examples() -> lists:foreach(fun (Str) -> io:format("String \"~ts\" (length ~p): ", [Str, length(Str)]), case all_unique(Str) of all_unique -> io:format("All characters unique.~n"); {not_all_unique, Char, P1, P2} -> io:format("First duplicate is '~tc' (0x~.16b)" " at positions ~p and ~p.~n", [Char, Char, P1, P2]) end end, ["", ".", "abcABC", "XYZ ZYX", "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
#JavaScript
JavaScript
  String.prototype.collapse = function() { let str = this; for (let i = 0; i < str.length; i++) { while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1); } return str; }   // testing let 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 ' ]; for (let i = 0; i < strings.length; i++) { let str = strings[i], col = str.collapse(); console.log(`«««${str}»»» (${str.length})`); console.log(`«««${col}»»» (${col.length})`); }  
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
#jq
jq
# Input: an array # Output: a stream def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);   def collapse: explode | [uniq] | implode;
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
#Groovy
Groovy
class Main { static void main(String[] args) { String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"] for (String s : tests) { analyze(s) } }   static void analyze(String s) { println("Examining [$s] which has a length of ${s.length()}") if (s.length() > 1) { char firstChar = s.charAt(0) int lastIndex = s.lastIndexOf(firstChar as String) if (lastIndex != 0) { println("\tNot all characters in the string are the same.") println("\t'$firstChar' (0x${Integer.toHexString(firstChar as Integer)}) is different at position $lastIndex") return } } println("\tAll characters in the string are the same.") } }
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.
#Nim
Nim
import threadpool, locks, math, os, random # to call randomize() as a seed, need to import random module randomize()   type Philosopher = ref object name: string food: string forkLeft, forkRight: int   const n = 5 names = ["Aristotle", "Kant", "Spinoza", "Marx", "Russell"] foods = [" rat poison", " cockroaches", " dog food", " lemon-curd toast", " baked worms"]   var forks: array[n, Lock] phils: array[n, Philosopher] threads: array[n, Thread[Philosopher]]   proc run(p: Philosopher) {.thread.} = # random deprecated, use rand(x .. y) sleep rand(1..10) * 500 echo p.name, " is hungry."   acquire forks[min(p.forkLeft, p.forkRight)] sleep rand(1..5) * 500 acquire forks[max(p.forkLeft, p.forkRight)]   echo p.name, " starts eating", p.food, "." sleep rand(1..10) * 500   echo p.name, " finishes eating", p.food, " and leaves to think."   release forks[p.forkLeft] release forks[p.forkRight]   for i in 0..<n: initLock forks[i] phils[i] = Philosopher( name: names[i], food: foods[rand(0 .. n) mod n], forkLeft: i, forkRight: (i + 1) mod n ) createThread(threads[i], run, phils[i])   joinThreads(threads)
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
DiscordianDate[y_, m_, d_] := Module[{year = ToString[y + 1166], month = m, day = d},   DMONTHS = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}; DDAYS = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"}; DayOfYear = DateDifference[{y} ,{y, m, d}] + 1; LeapYearQ = (Mod[#, 4]== 0 && (Mod[#, 100] != 0 || Mod[#, 400] == 0))&@ y;   If [ LeapYearQ && month == 2 && day == 29, Print["Today is St. Tib's Day, YOLD ", ] , If [ LeapYearQ && DayOfYear >= 60, DayOfYear -= 1 ]; {season, dday} = {Quotient[DayOfYear, 73], Mod[DayOfYear, 73]}; Print["Today is ", DDAYS[[Mod[dday,4] + 1]],", ",DMONTHS[[season+1]]," ",dday,", YOLD ",year] ]; ]
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)
#OCaml
OCaml
let list_vertices graph = List.fold_left (fun acc ((a, b), _) -> let acc = if List.mem b acc then acc else b::acc in let acc = if List.mem a acc then acc else a::acc in acc ) [] graph   let neighbors v = List.fold_left (fun acc ((a, b), d) -> if a = v then (b, d)::acc else acc ) []   let remove_from v lst = let rec aux acc = function [] -> failwith "remove_from" | x::xs -> if x = v then List.rev_append acc xs else aux (x::acc) xs in aux [] lst   let with_smallest_distance q dist = match q with | [] -> assert false | x::xs -> let rec aux distance v = function | x::xs -> let d = Hashtbl.find dist x in if d < distance then aux d x xs else aux distance v xs | [] -> (v, distance) in aux (Hashtbl.find dist x) x xs   let dijkstra max_val zero add graph source target = let vertices = list_vertices graph in let dist_between u v = try List.assoc (u, v) graph with _ -> zero in let dist = Hashtbl.create 1 in let previous = Hashtbl.create 1 in List.iter (fun v -> (* initializations *) Hashtbl.add dist v max_val (* unknown distance function from source to v *) ) vertices; Hashtbl.replace dist source zero; (* distance from source to source *) let rec loop = function [] -> () | q -> let u, dist_u = with_smallest_distance q dist in (* vertex in q with smallest distance in dist *) if dist_u = max_val then failwith "vertices inaccessible"; (* all remaining vertices are inaccessible from source *) if u = target then () else begin let q = remove_from u q in List.iter (fun (v, d) -> if List.mem v q then begin let alt = add dist_u (dist_between u v) in let dist_v = Hashtbl.find dist v in if alt < dist_v then begin (* relax (u,v,a) *) Hashtbl.replace dist v alt; Hashtbl.replace previous v u; (* previous node in optimal path from source *) end end ) (neighbors u graph); loop q end in loop vertices; let s = ref [] in let u = ref target in while Hashtbl.mem previous !u do s := !u :: !s; u := Hashtbl.find previous !u done; (source :: !s)   let () = let 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; ] in let p = dijkstra max_int 0 (+) graph "a" "e" in print_endline (String.concat " -> " p)
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
#Huginn
Huginn
main( argv_ ) { if ( size( argv_ ) < 2 ) { throw Exception( "usage: digital-root {NUM}" ); } n = argv_[1]; if ( ( size( n ) == 0 ) || ( n.find_other_than( "0123456789" ) >= 0 ) ) { throw Exception( "{} is not a number".format( n ) ); } shift = integer( '0' ) + 1; acc = 0; for ( d : n ) { acc = 1 + ( acc + integer( d ) - shift ) % 9; } print( "{}\n".format( acc ) ); return ( 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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every m := n := integer(!A) do { ap := 0 while (*n > 1) do (ap +:= 1, n := sumdigits(n)) write(m," has additive persistence of ",ap," and digital root of ",n) } end   procedure sumdigits(n) s := 0 n ? while s +:= move(1) return s end
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Scheme
Scheme
; Convert an integer into a list of its digits.   (define integer->list (lambda (integer) (let loop ((list '()) (int integer)) (if (< int 10) (cons int list) (loop (cons (remainder int 10) list) (quotient int 10))))))   ; Return the product of the digits of an integer.   (define integer-product-digits (lambda (integer) (fold-left * 1 (integer->list integer))))   ; Compute the multiplicative digital root and multiplicative persistence of an integer. ; Return as a cons of (mdr . mp).   (define mdr-mp (lambda (integer) (let loop ((int integer) (cnt 0)) (if (< int 10) (cons int cnt) (loop (integer-product-digits int) (1+ cnt))))))   ; Emit a table of integer, multiplicative digital root, and multiplicative persistence ; for the example integers given. Example list ends with sequence A003001 from OEIS.   (printf "~16@a ~6@a ~6@a~%" "Integer" "Root" "Pers.") (printf "~16@a ~6@a ~6@a~%" "===============" "======" "======") (let rowloop ((intlist '(123321 7739 893 899998 0 10 25 39 77 679 6788 68889 2677889 26888999 3778888999 277777788888899))) (when (pair? intlist) (let* ((int (car intlist)) (mm (mdr-mp int))) (printf "~16@a ~6@a ~6@a~%" int (car mm) (cdr mm)) (rowloop (cdr intlist)))))   ; Emit a table of multiplicative digital root versus the first five integers having that MDR.   (newline) (printf "~5@a ~a~%" "Root" "First five integers with that root") (printf "~5@a ~a~%" "====" "==================================") (let ((mdrslsts (make-vector 10 '()))) (do ((integer 0 (1+ integer))) ((>= (fold-left min 5 (vector->list (vector-map length mdrslsts))) 5)) (let ((mdr (car (mdr-mp integer)))) (when (< (length (vector-ref mdrslsts mdr)) 5) (vector-set! mdrslsts mdr (append (vector-ref mdrslsts mdr) (list integer)))))) (do ((mdr 0 (1+ mdr))) ((>= mdr 10)) (printf "~5@a" mdr) (for-each (lambda (int) (printf "~7@a" int)) (vector-ref mdrslsts mdr)) (newline)))
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?
#Phix
Phix
with javascript_semantics enum Baker, Cooper, Fletcher, Miller, Smith constant names={"Baker","Cooper","Fletcher","Miller","Smith"} procedure test(sequence flats) if flats[Baker]!=5 and flats[Cooper]!=1 and not find(flats[Fletcher],{1,5}) and flats[Miller]>flats[Cooper] and abs(flats[Smith]-flats[Fletcher])!=1 and abs(flats[Fletcher]-flats[Cooper])!=1 then for i=1 to 5 do ?{names[i],flats[i]} end for end if end procedure for i=1 to factorial(5) do test(permute(i,tagset(5))) end for
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
#Hoon
Hoon
|= [a=(list @sd) b=(list @sd)] =| sum=@sd |-  ?: |(?=(~ a) ?=(~ b)) sum $(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.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
#Hy
Hy
(defn dotp [a b] (assert (= (len a) (len b))) (sum (genexpr (* aterm bterm) [(, aterm bterm) (zip a b)])))   (assert (= 3 (dotp [1 3 -5] [4 -2 -1])))
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified character that is   immediately   followed by an identical character (or characters).   Another word choice could've been   duplicated character,   but that might have ruled out   (to some readers)   triplicated characters   ···   or more. {This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   PL/I   BIF:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   the   original string and its length   the resultant string and its length   the above strings should be "bracketed" with   <<<   and   >>>   (to delineate blanks)   «««Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here»»» Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except the 1st string: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
const teststringpairs = [ ("", ' '), (""""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 ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')]   function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end   for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") 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
#Kotlin
Kotlin
fun main() { val testStrings = arrayOf( "", "\"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 ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship") val testChar = arrayOf( " ", "-", "7", ".", " -r", "5", "e", "s") for (testNum in testStrings.indices) { val s = testStrings[testNum] for (c in testChar[testNum].toCharArray()) { val result = squeeze(s, c) System.out.printf("use: '%c'%nold:  %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%nnew:  %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%n%n", c, s.length, s, result.length, result) } } }   private fun squeeze(input: String, include: Char): String { val sb = StringBuilder() for (i in input.indices) { if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) { sb.append(input[i]) } } return sb.toString() }
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
dxs = {-0.533, 0.27, 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.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -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.17, 0.054, -0.553, -0.024, -0.181, -0.7, -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.31, 0.171, 0., 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.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0., 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 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.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -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.65, -1.103, 0.154, -1.72, 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};   (*Mathematica's StandardDeviation function computes the unbiased standard deviation. The solutions seem to be using the biased standard deviation, so I'll create a custom function for that.*) BiasedStandardDeviation[data_] := With[ {mean = Mean@data}, Sqrt[Total[(# - mean)^2 & /@ data]/Length[data]] ]   (*Mathematica's FoldPair functionality will work well with this if we provide a properly defined function to fold with.*) DemingRule[1][funnelPosition_, diff_] := {funnelPosition + diff, 0}; DemingRule[2][funnelPosition_, diff_] := {funnelPosition + diff, -diff}; DemingRule[3][funnelPosition_, diff_] := {funnelPosition + diff, -funnelPosition - diff}; DemingRule[4][funnelPosition_, diff_] := {funnelPosition + diff, funnelPosition + diff};   (*The core implementation.*) MarblePositions[rule_][diffs_] := FoldPairList[DemingRule[rule], 0, diffs];   (*This is to help format the output.*) Results[rule_, diffData_] := With[ {positions = MarblePositions[rule][diffData]}, StringForm["Rule `1`\nmean: `2`\nstd dev: `3`", rule, Mean[positions], BiasedStandardDeviation[positions]] ];   TableForm[Results[#, Transpose[{dxs, dys}]] & /@ Range[4], TableSpacing -> 5]
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.
#Stretch_1
Stretch 1
  RadiusDistribution = NormalDistribution[0, 1]; AngleDistribution = UniformDistribution[{0, Pi}];   (*Mathematica has built in transformation functions, but this seems clearer given the way the instructions were written.*) ToCartesian[{r_, a_}] := ToCartesian[{Abs@r, a - Pi}] /; Negative[r]; ToCartesian[{r_, a_}] := FromPolarCoordinates[{r, a}];   newData = ToCartesian /@ Transpose[{RandomVariate[RadiusDistribution, 100], RandomVariate[AngleDistribution, 100]}];   TableForm[Results[#, newData] & /@ Range[4], TableSpacing -> 5]  
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
#AppleScript
AppleScript
on run script on |λ|(x) script on |λ|(y) script on |λ|(z) if y ≠ z and 1 ≤ z and z ≤ 7 then {{x, y, z} as string} else {} end if end |λ| end script   concatMap(result, {12 - (x + y)}) --Z end |λ| end script   concatMap(result, {1, 2, 3, 4, 5, 6, 7}) --Y end |λ| end script   unlines(concatMap(result, {2, 4, 6})) --X end run     -- GENERIC FUNCTIONS ----------------------------------------------------------   -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) set lst to {} set lng to length of xs tell mReturn(f) repeat with i from 1 to lng set lst to (lst & |λ|(contents of item i of xs, i, xs)) end repeat end tell return lst end concatMap   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- unlines :: [String] -> String on unlines(xs) intercalate(linefeed, xs) end unlines
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".
#Common_Lisp
Common Lisp
(defgeneric thing (object) (:documentation "Thing the object."))   (defmethod thing (object) "default implementation")   (defclass delegator () ((delegate :initarg :delegate :reader delegator-delegate)))   (defmethod thing ((delegator delegator)) "If delegator has a delegate, invoke thing on the delegate, otherwise return \"no delegate\"." (if (slot-boundp delegator 'delegate) (thing (delegator-delegate delegator)) "no delegate"))   (defclass delegate () ())   (defmethod thing ((delegate delegate)) "delegate implementation")   (let ((d1 (make-instance 'delegator)) (d2 (make-instance 'delegator :delegate nil)) (d3 (make-instance 'delegator :delegate (make-instance 'delegate)))) (assert (string= "no delegate" (thing d1))) (assert (string= "default implementation" (thing d2))) (assert (string= "delegate implementation" (thing d3))))
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".
#D
D
class Delegator { string delegate() hasDelegate;   string operation() { if (hasDelegate is null) return "Default implementation"; return hasDelegate(); }   typeof(this) setDg(string delegate() dg) { hasDelegate = dg; return this; } }   void main() { import std.stdio; auto dr = new Delegator; string delegate() thing = () => "Delegate implementation";   writeln(dr.operation()); writeln(dr.operation()); writeln(dr.setDg(thing).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)
#Haskell
Haskell
isOverlapping :: Triangle Double -> Triangle Double -> Bool isOverlapping t1 t2 = vertexInside || midLineInside where vertexInside = any (isInside t1) (vertices t2) || any (isInside t2) (vertices t1)   isInside t = (Outside /=) . overlapping t   midLineInside = any (\p -> isInside t1 p && isInside t2 p) midPoints   midPoints = [ intersections l1 l2 | l1 <- midLines t1 , l2 <- midLines t2 ]   intersections (a1,b1,c1) (a2,b2,c2) = ( -(-b2*c1+b1*c2)/(a2*b1-a1*b2) , -(a2*c1-a1*c2)/(a2*b1-a1*b2) )   midLines (Triangle a b c) = [line a b c, line b c a, line c a b]   line (x,y) (ax, ay) (bx, by) = (ay+by-2*y, -ax-bx+2*x, -ay*x-by*x+ax*y+bx*y)   test = map (uncurry isOverlapping) [ (Triangle (0,0) (5,0) (0,5), Triangle (0,0) (5,0) (0,6)) , (Triangle (0,0) (0,5) (5,0), Triangle (0,0) (0,5) (5,0)) , (Triangle (0,0) (5,0) (0,5), Triangle (-10,0) (-5,0) (-1,6)) , (Triangle (0,0) (5,0) (2.5,5), Triangle (0,4) (2.5,-1) (5,4)) , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,0) (3,2)) , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,-2) (3,4)) , (Triangle (0,0) (1,0) (0,1), Triangle (1,0) (2,0) (1,1))]
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.
#C
C
#include <stdio.h>   int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
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.
#C.23
C#
using System; using System.IO;   namespace RosettaCode { class Program { static void Main() { try { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete(@"\input.txt"); Directory.Delete(@"\docs"); } catch (Exception exception) { Console.WriteLine(exception.Message); } } } }
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
#Haskell
Haskell
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]] where aux items x = do (f, item) <- zip (cycle [reverse, id]) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys)   elemPos :: [[a]] -> Int -> Int -> a elemPos ms i j = (ms !! i) !! j   prod :: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [Int] -> a prod f ms = product . zipWith (f ms) [0 ..]   sDeterminant :: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [([Int], Int)] -> a sDeterminant f ms = sum . fmap (\(is, s) -> fromIntegral s * prod f ms is)   determinant :: Num a => [[a]] -> a determinant ms = sDeterminant elemPos ms . sPermutations $ [0 .. pred . length $ ms]   permanent :: Num a => [[a]] -> a permanent ms = sum . fmap (prod elemPos ms . fst) . sPermutations $ [0 .. pred . length $ ms]   -- TEST ----------------------------------------------------------------------- result :: (Num a, Show a) => [[a]] -> String result ms = unlines [ "Matrix:" , unlines (show <$> ms) , "Determinant:" , show (determinant ms) , "Permanent:" , show (permanent ms) ]   main :: IO () main = mapM_ (putStrLn . result) [ [[5]] , [[1, 0, 0], [0, 1, 0], [0, 0, 1]] , [[0, 0, 1], [0, 1, 0], [1, 0, 0]] , [[4, 3], [2, 5]] , [[2, 5], [4, 3]] , [[4, 4], [2, 2]] ]
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.
#E
E
def divide(numerator, denominator) { def floatQuotient := numerator / denominator if (floatQuotient.isNaN() || floatQuotient.isInfinite()) { return ["zero denominator"] } else { return ["ok", floatQuotient] } }
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.
#ECL
ECL
  DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;   #option ('divideByZero', 'zero'); DBZ(10,0); //returns 0.0  
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#CFScript
CFScript
isNumeric(42)
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
#Clojure
Clojure
(defn numeric? [s] (if-let [s (seq s)] (let [s (if (= (first s) \-) (next s) s) s (drop-while #(Character/isDigit %) s) s (if (= (first s) \.) (next s) s) s (drop-while #(Character/isDigit %) s)] (empty? s))))
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
#F.23
F#
  // Determine if a string has all unique characters. Nigel Galloway: June 9th., 2020 let fN (n:string)=n.ToCharArray()|>Array.mapi(fun n g->(n,g))|>Array.groupBy(fun (_,n)->n)|>Array.filter(fun(_,n)->n.Length>1)   let allUnique n=match fN n with g when g.Length=0->printfn "All charcters in <<<%s>>> (length %d) are unique" n n.Length |g->Array.iter(fun(n,g)->printf "%A is repeated at positions" n; Array.iter(fun(n,_)->printf " %d" n)g;printf " ")g printfn "in <<<%s>>> (length %d)" n n.Length   allUnique "" allUnique "." allUnique "abcABC" allUnique "XYZ ZYX" allUnique "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
#Julia
Julia
const teststrings = [ "", """"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 "]   function collapse(s) len = length(s) if len < 2 return s, len, s, len end result = last = s[1] for c in s[2:end] if c != last last = c result *= c end end return s, len, result, length(result) end   function testcollapse(arr) for s in arr (s1, len1, s2, len2) = collapse(s) println("«««$s1»»» (length $len1)\n collapses to:\n«««$s2»»» (length $len2).\n") end end   testcollapse(teststrings)  
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
#Kotlin
Kotlin
fun collapse(s: String): String { val cs = StringBuilder() var last: Char = 0.toChar() for (c in s) { if (c != last) { cs.append(c) last = c } } return cs.toString() }   fun main() { val strings = arrayOf( "", "\"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 (s in strings) { val c = collapse(s) println("original : length = ${s.length}, string = «««$s»»»") println("collapsed : length = ${c.length}, string = «««$c»»»") 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
#Haskell
Haskell
import Numeric (showHex) import Data.List (span) import Data.Char (ord)   inconsistentChar :: Eq a => [a] -> Maybe (Int, a) inconsistentChar [] = Nothing inconsistentChar xs@(x:_) = let (pre, post) = span (x ==) xs in if null post then Nothing else Just (length pre, head post)     ---------------------------TEST---------------------------- samples :: [String] samples = [" ", "2", "333", ".55", "tttTTT", "4444 444"]   main :: IO () main = do let w = succ . maximum $ length <$> samples justifyRight n c = (drop . length) <*> (replicate n c ++) f = (++ "' -> ") . justifyRight w ' ' . ('\'' :) (putStrLn . unlines) $ (\s -> maybe (f s ++ "consistent") (\(n, c) -> f s ++ "inconsistent '" ++ c : "' (0x" ++ showHex (ord c) ")" ++ " at char " ++ show (succ n)) (inconsistentChar s)) <$> samples
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.
#OxygenBasic
OxygenBasic
  '========================= class RoundTableWith5Seats '=========================    % hungry 0  % beingUsed 1  % putDown 0  % empty 0   sys fork[5], plate[5],chair[5],philosopher[5] sys first   method AddPasta() as sys function rand() as sys static seed=0x12345678 mov eax,seed rol eax,7 mul seed xor eax,0x5335ABD9 mov seed,eax return seed end function return 4+(rand() and 15) end method   method dine() first++ 'PRIORITY DINER if first>5 then first-=5 for i=1 to 5 kl=first+i-1 kr=first+i if kl>5 then kl-=5 if kr>5 then kr-=5 if philosopher(kl) = hungry then if not fork(kl) or fork(kr) = beingUsed then plate(kl) = AddPasta() fork(kl)=beingUsed fork(kr)=beingUsed end if end if ' next ' for kl=1 to 5 kr=kl+1 : if kr>5 then kr-=5 if plate(kl) philosopher(kl)+=1 'PHILOSOPHER DINING --plate(kl) if plate(kl)=empty fork(kl)=PutDown fork(kr)=PutDown end if else if philosopher(kl)>0 --philosopher(kl) 'PHILOSOPHER THINKING end if end if next ' end method   method show() as string cr=chr(13)+chr(10) : tab=chr(9) pr="philos" tab "activity" tab "plate" tab "fork L" tab "fork R" cr cr for i=1 to 5 j=i+1 : if j>5 then j-=5 if plate(i)=0 then if philosopher(i)=0 then act="waiting" else act="thinks" end if else act="dining" end if ' pr+=i tab act tab plate(i) tab fork(i) tab fork(j) cr next return pr end method   end class   'TEST '====   RoundTableWith5Seats Sopho for i=1 to 100 Sopho.dine next   print Sopho.show 'putfile "s.txt",Sopho.show   'philos action plate fork L fork R ' '1 waiting 0 0 1 '2 dining 8 1 1 '3 thinks 0 1 1 '4 dining 8 1 1 '5 thinks 0 1 0  
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Nim
Nim
import times, strformat   const   DiscordianOrigin = -1166 SaintTibsDay = "St. Tib’s Day"   type   Season = enum sCha = (1, "Chaos"), sDis = "Discord", sCon = "Confusion", sBur = "Bureaucracy", sAft = "The Aftermath"   ErisianWeekDay = enum eSwe = "Sweetmorn", eBoo = "Boomtime", ePun = "Pungenday", ePri = "Prickle-Prickle", eSet = "Setting Orange"   SeasonDayRange = range[1..73]   # Description of a discordian date. DiscordianDate = object year: int yearday: YeardayRange case isSaintTibsDay: bool of false: seasondayZero: int seasonZero: int weekday: ErisianWeekDay else: nil   #---------------------------------------------------------------------------------------------------   proc toDiscordianDate(gdate: DateTime): DiscordianDate = ## Convert a DateTime to a discordian date. ## All the time fields are ignored.   # Create the object. result = DiscordianDate(isSaintTibsDay: gdate.isLeapDay)   # The yearday field is unchanged. result.yearday = gdate.yearday   # The year is simply translated. result.year = gdate.year - DiscordianOrigin   # For remaining fields, we must take in account leap years. if not result.isSaintTibsDay: var yearday = result.yearday if gdate.year.isLeapYear and result.yearday > 59: dec yearday # Now, we have simply to use division and modulo using the corrected yearday. result.seasonZero = yearday div SeasonDayRange.high result.seasondayZero = yearday mod SeasonDayRange.high result.weekday = ErisianWeekDay(yearday mod 5)   #---------------------------------------------------------------------------------------------------   proc `$`(date: DiscordianDate): string = ## Convert a discordian date to a string. if date.isSaintTibsDay: result = SaintTibsDay else: result = fmt"{date.weekday}, {Season(date.seasonZero + 1)} {date.seasondayZero + 1}" result &= fmt", {date.year} YOLD"   #---------------------------------------------------------------------------------------------------   proc showDiscordianDate(year, month, day: Natural) = ## Show the discordian date corresponding to a gregorian date. let gdate = initDateTime(year = year, month = Month(month), monthday = day, hour = 0, minute = 0, second = 0) echo gdate.format("YYYY-MM-dd"), ": ", $gdate.toDiscordianDate()   #———————————————————————————————————————————————————————————————————————————————————————————————————   showDiscordianDate(2100, 12, 31) showDiscordianDate(2012, 02, 28) showDiscordianDate(2012, 02, 29) showDiscordianDate(2012, 03, 01) showDiscordianDate(2010, 07, 22) showDiscordianDate(2012, 09, 02) showDiscordianDate(2012, 12, 31)
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)
#PARI.2FGP
PARI/GP
shortestPath(G, startAt=1)={ my(n=#G[,1],dist=vector(n,i,9e99),prev=dist,Q=2^n-1); dist[startAt]=0; while(Q, my(t=vecmin(vecextract(dist,Q)),u); if(t==9e99, break); for(i=1,#v,if(dist[i]==t && bittest(Q,i-1), u=i; break)); Q-=1<<(u-1); for(i=1,n, if(!G[u,i],next); my(alt=dist[u]+G[u,i]); if (alt < dist[i], dist[i]=alt; prev[i]=u; ) ) ); dist };
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
#J
J
digrot=: +/@(#.inv~&10)^:_ addper=: _1 + [: # +/@(#.inv~&10)^:a:
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
#Java
Java
import java.math.BigInteger;   class DigitalRoot { public static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base); int additivePersistence = 0; if (bi.signum() < 0) bi = bi.negate(); BigInteger biBase = BigInteger.valueOf(base); while (bi.compareTo(biBase) >= 0) { number = bi.toString(base); bi = BigInteger.ZERO; for (int i = 0; i < number.length(); i++) bi = bi.add(new BigInteger(number.substring(i, i + 1), base)); additivePersistence++; } return new int[] { additivePersistence, bi.intValue() }; }   public static void main(String[] args) { for (String arg : args) { int[] results = calcDigitalRoot(arg, 10); System.out.println(arg + " has additive persistence " + results[0] + " and digital root of " + results[1]); } } }
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Sidef
Sidef
func mdroot(n) { var (mdr, persist) = (n, 0) while (mdr >= 10) { mdr = mdr.digits.prod ++persist } [mdr, persist] }   say "Number: MDR MP\n====== === ==" [123321, 7739, 893, 899998].each{|n| "%6d: %3d %3d\n" \ .printf(n, mdroot(n)...) }   var counter = Hash()   Inf.times { |j| counter{mdroot(j).first} := [] << j break if counter.values.all {|v| v.len >= 5 } }   say "\nMDR: [n0..n4]\n=== ========" 10.times {|i| "%3d: %s\n".printf(i, counter{i}.first(5)) }
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?
#Picat
Picat
import util. import cp.   dinesman_cp => println(dinesman_cp), N = 5, X = [Baker, Cooper, Fletcher, Miller, Smith], X :: 1..N,   all_different(X),    % Baker does not live on the fifth floor. Baker #!= 5,    % Cooper does not live on the first floor. Cooper #!= 1,    % Fletcher does not live on either the fifth or the first floor. Fletcher #!= 5, Fletcher #!= 1,    % Miller lives on a higher floor than does Cooper. Miller #> Cooper,    % Smith does not live on a floor adjacent to Fletcher'. abs(Smith-Fletcher) #> 1,    % Fletcher does not live on a floor adjacent to Cooper's. abs(Fletcher-Cooper) #> 1,   solve(X),   println([baker=Baker, cooper=Cooper, fletcher=Fletcher, miller=Miller, smith=Smith]).
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
#Icon_and_Unicon
Icon and Unicon
procedure main() write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1])) end   procedure dotproduct(a,b) #: return dot product of vectors a & b or error if *a ~= *b & type(a) == type(b) == "list" then runerr(205,a) # invalid value every (dp := 0) +:= a[i := 1 to *a] * b[i] return dp 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
#Lua
Lua
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s))   local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le)   print() end   function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-') squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.')   local s = " --- Harry S Truman " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end   main()
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"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[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]