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/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".
#Pop11
Pop11
uses objectclass; define :class Delegator; slot delegate = false; enddefine;   define :class Delegate; enddefine;   define :method thing(x : Delegate); 'delegate implementation' enddefine;   define :method operation(x : Delegator); if delegate(x) and fail_safe(delegate(x), thing) then  ;;; Return value is on the stack else 'default implementation' endif; enddefine;   ;;; Default, without a delegate lvars a = newDelegator(); operation(a) =>   ;;; a delegating to itself (works because Delegator does not ;;; implement thing) a -> delegate(a); operation(a) =>   ;;; delegating to a freshly created Delegate newDelegate() -> delegate(a); operation(a) =>
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".
#Python
Python
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation'   class Delegate: def thing(self): return 'delegate implementation'   if __name__ == '__main__':   # No delegate a = Delegator() assert a.operation() == 'default implementation'   # With a delegate that does not implement "thing" a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation'   # With delegate that implements "thing" a.delegate = Delegate() assert a.operation() == '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".
#Racket
Racket
#lang racket ;; Delegates. Tim Brown 2014-10-16   (define delegator% (class object% (init-field [delegate #f]) (define/public (operation) (cond [(and (object? delegate) (object-method-arity-includes? delegate 'thing 0)) (send delegate thing)] [else "default implementation"])) (super-new)))   (define non-thinging-delegate% (class object% (super-new)))   (define thinging-delegate% (class object% (define/public (thing) "delegate implementation") (super-new)))   (module+ test (require tests/eli-tester) (define delegator-1 (new delegator%)) (define delegator-2 (new delegator%)) (define non-thinging-delegate (new non-thinging-delegate%)) (define thinging-delegate (new thinging-delegate%))   (test (send delegator-1 operation) => "default implementation" (send delegator-2 operation) => "default implementation" (set-field! delegate delegator-1 non-thinging-delegate) => (void) (set-field! delegate delegator-2 thinging-delegate) => (void) (send delegator-1 operation) => "default implementation" (send delegator-2 operation) => "delegate implementation" (send (new delegator% [delegate thinging-delegate]) operation) => "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)
#Racket
Racket
#lang racket   ;; A triangle is a list of three pairs of points: '((x . y) (x . y) (x . y)) (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)))   (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))]))   (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")]))   (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? ; Points on the boundary are considered as colliding (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ))))   (define (inr t1 t2) (for*/and ((i (in-range 3)))  ;; Check all points of trangle 2 lay on the external side  ;; of the edge E. If they do, the triangles do not collide. (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j))))))   (let (;; Trangles must be expressed anti-clockwise (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1))))   ;; --------------------------------------------------------------------------------------------------- (module+ test (require rackunit)   (define triangleses ; pairs of triangles (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b)))   (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f)))   (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))  
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.
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");   fso.DeleteFile('input.txt'); fso.DeleteFile('c:/input.txt');   fso.DeleteFolder('docs'); fso.DeleteFolder('c:/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.
#Julia
Julia
  # Delete a file rm("input.txt")   # Delete a directory rm("docs", recursive = true)  
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
#REXX
REXX
/* REXX *************************************************************** * Test the two functions determinant and permanent * using the matrix specifications shown for other languages * 21.05.2013 Walter Pachl **********************************************************************/ Call test ' 1 2', ' 3 4',2   Call test ' 1 2 3 4', ' 4 5 6 7', ' 7 8 9 10', '10 11 12 13',4   Call test ' 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',5   Exit   test: /********************************************************************** * Show the given matrix and compute and show determinant and permanent **********************************************************************/ Parse Arg as,n asc=as Do i=1 To n ol='' Do j=1 To n Parse Var asc a.i.j asc ol=ol right(a.i.j,3) End Say ol End Say 'determinant='right(determinant(as),7) Say ' permanent='right(permanent(as),7) Say copies('-',50) Return
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
#Ruby
Ruby
require 'matrix'   class Matrix # Add "permanent" method to Matrix class def permanent r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example) r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end   m1 = Matrix[[1,2],[3,4]] # testcases from Python version   m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]]   m3 = Matrix[[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]]   [m1, m2, m3].each do |m| puts "determinant:\t #{m.determinant}", "permanent:\t #{m.permanent}" puts 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.
#Lua
Lua
local function div(a,b) if b == 0 then error() end return a/b 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.
#M2000_Interpreter
M2000 Interpreter
  Print function("{Read x : =x**2}", 2)=4  
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.
#M4
M4
ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')
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
#Haxe
Haxe
  static function isNumeric(n:String):Bool { if (Std.parseInt(n) != null) //Std.parseInt converts a string to an int { return true; //as long as it results in an integer, the function will return true } else { return false; } }  
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
#HicEst
HicEst
! = bin + 2*int + 4*flt + 8*oct +16*hex + 32*sci isNumeric("1001") ! 27 = 1 1 0 1 1 0 isNumeric("123") ! 26 = 0 1 0 1 1 0 isNumeric("1E78") ! 48 = 0 0 0 0 1 1 isNumeric("-0.123") ! 4 = 0 0 1 0 0 1 isNumeric("-123.456e-78") ! 32 = 0 0 0 0 0 1 isNumeric(" 123") ! 0: leading blank isNumeric("-123.456f-78") ! 0: illegal character f     FUNCTION isNumeric(string) ! true ( > 0 ), no leading/trailing blanks CHARACTER string b = INDEX(string, "[01]+", 128, Lbin) ! Lbin returns length found i = INDEX(string, "-?\d+", 128, Lint) ! regular expression: 128 f = INDEX(string, "-?\d+\.\d*", 128, Lflt) o = INDEX(string, "[0-7]+", 128, Loct) h = INDEX(string, "[0-9A-F]+", 128, Lhex) ! case sensitive: 1+128 s = INDEX(string, "-?\d+\.*\d*E[+-]*\d*", 128, Lsci) IF(anywhere) THEN ! 0 (false) by default isNumeric = ( b > 0 ) + 2*( i > 0 ) + 4*( f > 0 ) + 8*( o > 0 ) + 16*( h > 0 ) + 32*( s > 0 ) ELSEIF(boolean) THEN ! 0 (false) by default isNumeric = ( b + i + f + o + h + s ) > 0 ! this would return 0 or 1 ELSE L = LEN(string) isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L) ENDIF END
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
'''Determine if a string has all unique characters'''   from itertools import groupby     # duplicatedCharIndices :: String -> Maybe (Char, [Int]) def duplicatedCharIndices(s): '''Just the first duplicated character, and the indices of its occurrence, or Nothing if there are no duplications. ''' def go(xs): if 1 < len(xs): duplicates = list(filter(lambda kv: 1 < len(kv[1]), [ (k, list(v)) for k, v in groupby( sorted(xs, key=swap), key=snd ) ])) return Just(second(fmap(fst))( sorted( duplicates, key=lambda kv: kv[1][0] )[0] )) if duplicates else Nothing() else: return Nothing() return go(list(enumerate(s)))     # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test over various strings.'''   def showSample(s): return repr(s) + ' (' + str(len(s)) + ')'   def showDuplicate(cix): c, ix = cix return repr(c) + ( ' (' + hex(ord(c)) + ') at ' + repr(ix) )   print( fTable('First duplicated character, if any:')( showSample )(maybe('None')(showDuplicate))(duplicatedCharIndices)([ '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' ]) )     # FORMATTING ----------------------------------------------   # fTable :: String -> (a -> String) -> # (b -> String) -> (a -> b) -> [a] -> String def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs )     # GENERIC -------------------------------------------------   # Just :: a -> Maybe a def Just(x): '''Constructor for an inhabited Maybe (option type) value. Wrapper containing the result of a computation. ''' return {'type': 'Maybe', 'Nothing': False, 'Just': x}     # Nothing :: Maybe a def Nothing(): '''Constructor for an empty Maybe (option type) value. Empty wrapper returned where a computation is not possible. ''' return {'type': 'Maybe', 'Nothing': True}     # fmap :: (a -> b) -> [a] -> [b] def fmap(f): '''fmap over a list. f lifted to a function over a list. ''' return lambda xs: [f(x) for x in xs]     # fst :: (a, b) -> a def fst(tpl): '''First member of a pair.''' return tpl[0]     # head :: [a] -> a def head(xs): '''The first element of a non-empty list.''' return xs[0] if isinstance(xs, list) else next(xs)     # maybe :: b -> (a -> b) -> Maybe a -> b def maybe(v): '''Either the default value v, if m is Nothing, or the application of f to x, where m is Just(x). ''' return lambda f: lambda m: v if ( None is m or m.get('Nothing') ) else f(m.get('Just'))     # second :: (a -> b) -> ((c, a) -> (c, b)) def second(f): '''A simple function lifted to a function over a tuple, with f applied only to the second of two values. ''' return lambda xy: (xy[0], f(xy[1]))     # snd :: (a, b) -> b def snd(tpl): '''Second member of a pair.''' return tpl[1]     # swap :: (a, b) -> (b, a) def swap(tpl): '''The swapped components of a pair.''' return (tpl[1], tpl[0])     # MAIN --- if __name__ == '__main__': main()
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
#XPL0
XPL0
string 0; char C, I, J, Last;   proc Collapse(S); \Eliminate immediately repeated characters from string char S; [I:= 0; J:= 0; Last:= -1; loop [if S(I) # Last then [C(J):= S(I); if S(I) = 0 then quit; J:= J+1; ]; Last:= S(I); I:= I+1; ]; ];   int String, K; [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 "]; C:= Reserve(79+1); \space for collapsed string for K:= 0 to 4 do [Collapse(String(K)); Text(0, "<<<"); Text(0, String(K)); Text(0, ">>> "); IntOut(0, I); CrLf(0); Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0); ]; ]
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
#zkl
zkl
fcn collapsible(str){ // no Unicode sink:=Sink(String); str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0 cstr:=sink.close(); return(str.len()!=cstr.len(), cstr); }
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
#Racket
Racket
#lang racket   (define (first-non-matching-index l =) (and (not (null? l)) (index-where l (curry (negate =) (car l)))))   (define (report-string-sameness s) (printf "~s (length: ~a): ~a~%" s (string-length s) (cond [(first-non-matching-index (string->list s) char=?) => (λ (i) (let ((c (string-ref s i))) (format "first different character ~s(~a) at position: ~a" c (char->integer c) (add1 i))))] [else "all characters are the same"])))   (module+ test (for-each report-string-sameness '("" " " "2" "333" ".55" "tttTTT" "4444 444k")))
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
-> $str { my $i = 0; print "\n{$str.raku} (length: {$str.chars}), has "; my %m; %m{$_}.push: ++$i for $str.comb;   if %m > 1 { say "different characters:"; say "'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: "0x%X"})" ~ " in positions: {.value.join: ', '}" for %m.sort( *.value[0] ); } else { say "the same character in all positions." } } for '', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🇬🇧🇬🇧🇬🇧🇬🇧', "\c[LATIN CAPITAL LETTER A]\c[COMBINING DIAERESIS]\c[COMBINING MACRON]" ~ "\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\c[COMBINING MACRON]" ~ "\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]", 'AАΑꓮ𐌀𐊠Ꭺ'
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.
#Smalltalk
Smalltalk
'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 13 October 2011 at 2:44:42 pm'! Object subclass: #Philosopher instanceVariableNames: 'table random name seat forks running' classVariableNames: '' poolDictionaries: '' category: 'rosettacode'!   !Philosopher methodsFor: 'private'! createfork ^ Semaphore forMutualExclusion! !   !Philosopher methodsFor: 'private'! displayState: aStateName Transcript show: name , ' is ' , aStateName; cr! !   !Philosopher methodsFor: 'private'! pickUpForkAt: relativePosition | fork pos | pos := self tableIndex: seat + relativePosition. (fork := table at: pos) ifNotNil: [fork critical: [(table at: pos) notNil ifTrue: [table at: pos put: nil] ifFalse: [fork := nil]]]. ^ (forks at: relativePosition put: fork) notNil! !   !Philosopher methodsFor: 'private'! putBackForkAt: aRelativePosition | fork | fork := forks at: aRelativePosition. fork ifNotNil: [table at: (self tableIndex: seat + aRelativePosition) put: fork. forks at: aRelativePosition put: nil]! !   !Philosopher methodsFor: 'private'! tableIndex: aNum ^ aNum - 1 \\ table size + 1! !   !Philosopher methodsFor: 'private'! waitRandomTime (Delay forMilliseconds: (random next * 4000) rounded) wait! !     !Philosopher methodsFor: 'dining'! eat self displayState: 'eating'; waitRandomTime; putBackForkAt: -1; putBackForkAt: 1! !   !Philosopher methodsFor: 'dining'! pickUpForks self displayState: 'trying to pick up forks'. [(self pickUpForkAt: -1) ifTrue: [(self pickUpForkAt: 1) ifFalse: [self putBackForkAt: -1]]. (forks at: 1) notNil] whileFalse: [(Delay forMilliseconds: 10) wait]! !   !Philosopher methodsFor: 'dining'! think self displayState: 'thinking'; waitRandomTime! !     !Philosopher methodsFor: 'initialize-release'! beginDining: aName at: aTable name := aName. table := aTable. forks := Dictionary new at: -1 put: nil; at: 1 put: nil; yourself. random := Random new seed: name hash. seat := table size + 1. table add: self; add: self createfork. running := true. [(Delay forSeconds: 20) wait. running := false] fork. [[running] whileTrue: [self think; pickUpForks; eat]. nil] fork! !   "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!   Philosopher class instanceVariableNames: ''!   !Philosopher class methodsFor: 'examples'! diningPhilosophersTest | diningTable | diningTable := OrderedCollection new. #('Aristotle' 'Kant' 'Buddha' 'Marx' 'Russel' ) do: [:aName | Philosopher new beginDining: aName at: diningTable]! !  
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Rust
Rust
extern crate chrono;   use chrono::NaiveDate; use std::str::FromStr;   fn main() { let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date."); println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee()); }   // The necessary constants for the seasons, weekdays, and holydays. const APOSTLES: [&str; 5] = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"]; const HOLYDAYS: [&str; 5] = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"]; const SEASONS: [&str; 5] = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]; const WEEKDAYS: [&str; 5] = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"];   // The necessary constants for the conversion. const APOSTLE_HOLYDAY: usize = 5; const CURSE_OF_GREYFACE: i32 = 1166; const SEASON_DAYS: usize = 73; const SEASON_HOLYDAY: usize = 50; const ST_TIBS_DAY: usize = 59; const WEEK_DAYS: usize = 5;   // This extends the `Datelike` trait of Rust's Chrono crate with a method that // prints any Datelike type as a String. impl<T: Datelike> DiscordianDate for T {} pub trait DiscordianDate: Datelike { fn to_poee(&self) -> String { let day = self.ordinal0() as usize; let leap = self.year() % 4 == 0 && self.year() % 100 != 0 || self.year() % 400 == 0; let year = self.year() + CURSE_OF_GREYFACE;   if leap && day == ST_TIBS_DAY { return format!("St. Tib's Day, in the YOLD {}", year); }   let day_offset = if leap && day > ST_TIBS_DAY { day - 1 } else { day };   let day_of_season = day_offset % SEASON_DAYS + 1;   let season = SEASONS[day_offset / SEASON_DAYS]; let weekday = WEEKDAYS[day_offset % WEEK_DAYS];   let holiday = if day_of_season == APOSTLE_HOLYDAY { format!("\nCelebrate {}", APOSTLES[day_offset / SEASON_DAYS]) } else if day_of_season == SEASON_HOLYDAY { format!("\nCelebrate {}", HOLYDAYS[day_offset / SEASON_DAYS]) } else { String::with_capacity(0) };   format!("{}, the {} day of {} in the YOLD {}{}", weekday, ordinalize(day_of_season), season, year, holiday) } }   /// A helper function to ordinalize a numeral. fn ordinalize(num: usize) -> String { let s = format!("{}", num);   let suffix = if s.ends_with('1') && !s.ends_with("11") { "st" } else if s.ends_with('2') && !s.ends_with("12") { "nd" } else if s.ends_with('3') && !s.ends_with("13") { "rd" } else { "th" };   format!("{}{}", s, suffix) }  
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)
#Sidef
Sidef
class Graph(*args) {   struct Node { String name, Array edges = [], Number dist = Inf, prev = nil, Bool visited = false, }   struct Edge { Number weight, Node vertex, }   has g = Hash()   method init { args.each { |a| self.add_edge(a...) } }   method get(name) { g{name} }   method add_edge(a, b, weight) { g{a} ||= Node(name: a) g{b} ||= Node(name: b) g{a}.edges << Edge(weight, g{b}) }   method push_priority(a, v) { var i = 0 var j = a.end while (i <= j) { var k = ((i + j) // 2) if (a[k].dist >= v.dist) { j = k-1 } else { i = k+1 } } a.insert(i, v) }   method dijkstra(a, b) { g{a}.dist = 0 var h = [] self.push_priority(h, g{a}) while (!h.is_empty) { var v = h.shift break if (v.name == b) v.visited = true v.edges.each { |e| var u = e.vertex if (!u.visited && (v.dist+e.weight <= u.dist)) { u.prev = v u.dist = (v.dist + e.weight) self.push_priority(h, u) } } } } }   var g = 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], )   g.dijkstra('a', 'e')   var v = g.get('e') var a = [] while (v != nil) { a << v.name v = v.prev }   var path = a.reverse.join say "#{g.get('e').dist} #{path}"
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#PowerShell
PowerShell
function Get-DigitalRoot ($n) { function Get-Digitalsum ($n) { if ($n -lt 10) {$n} else { ($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10))) } }   $ap = 0 do {$n = Get-DigitalSum $n; $ap++} until ($n -lt 10) $DigitalRoot = [pscustomobject]@{ 'Sum' = $n 'Additive Persistence' = $ap } $DigitalRoot }
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?
#UTFool
UTFool
  ··· http://rosettacode.org/wiki/Dinesman's_multiple-dwelling_problem ··· import java.util.HashSet   ■ Dinesman § static   houses⦂ HashSet⟨String⟩°   ▶ main • args⦂ String[] · Baker, Cooper, Fletcher, Miller, and Smith … build *StringBuilder°, *StringBuilder "BCFMS" ∀ house ∈ houses⦂ String if verify house System.out.println house.toString°   ▶ verify⦂ boolean • house⦂ String · Baker does not live on the top floor. return false if house.charAt 4 = 'B' · Fletcher does not live on either the top or the bottom floor. return false if house.charAt 0 = 'F' or house.charAt 4 = 'F' · Cooper does not live on the bottom floor. return false if house.charAt 0 = 'C' · Miller lives on a higher floor than does Cooper. return false if house.indexOf "M" ≤ house.indexOf "C" · Smith does not live on a floor adjacent to Fletcher's. return false if Math.abs (house.indexOf "S") - (house.indexOf "F") = 1 · Fletcher does not live on a floor adjacent to Cooper's. return false if Math.abs (house.indexOf "F") - (house.indexOf "C") = 1 return true   ▶ build • house⦂ StringBuilder • people⦂ StringBuilder if people.length° = 0 houses.add house.toString° else ∀ i ∈ 0…people.length° person⦂ char: people.charAt i house.append person people.deleteCharAt i build house, people people.insert i, person house.setLength house.length° - 1  
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#.D0.9C.D0.9A-61.2F52
МК-61/52
С/П * ИП0 + П0 С/П БП 00
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
#Modula-2
Modula-2
MODULE DotProduct; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Vector = RECORD x,y,z : REAL END;   PROCEDURE DotProduct(u,v : Vector) : REAL; BEGIN RETURN u.x*v.x + u.y*v.y + u.z*v.z END DotProduct;   VAR buf : ARRAY[0..63] OF CHAR; dp : REAL; BEGIN dp := DotProduct(Vector{1.0,3.0,-5.0},Vector{4.0,-2.0,-1.0}); RealToStr(dp, buf); WriteString(buf); WriteLn;   ReadChar END DotProduct.
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
#FOCAL
FOCAL
01.10 F P=2,2,6;F S=1,7;F G=1,7;D 2 01.20 Q   02.10 I (P-S)2.2,2.6,2.2 02.20 I (P-G)2.3,2.6,2.3 02.30 I (S-G)2.4,2.6,2.4 02.40 I (P+S+G-12)2.6,2.5,2.6 02.50 T %1,P,S,G,! 02.60 R
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
#Forth
Forth
\ if department numbers are valid, print them on a single line : fire ( pol san fir -- ) 2dup = if 2drop drop exit then 2 pick over = if 2drop drop exit then rot . swap . . cr ;   \ tries to assign numbers with given policeno and sanitationno \ and fire = 12 - policeno - sanitationno : sanitation ( pol san -- ) 2dup = if 2drop exit then \ no repeated numbers 12 over - 2 pick - \ calculate fireno dup 1 < if 2drop drop exit then \ cannot be less than 1 dup 7 > if 2drop drop exit then \ cannot be more than 7 fire ;   \ tries to assign numbers with given policeno \ and sanitation = 1, 2, 3, ..., or 7 : police ( pol -- ) 8 1 do dup i sanitation loop drop ;   \ tries to assign numbers with police = 2, 4, or 6 : departments cr \ leave input line 8 2 do i police 2 +loop ;
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".
#Raku
Raku
class Non-Delegate { }   class Delegate { method thing { return "delegate implementation" } }   class Delegator { has $.delegate is rw;   method operation { $.delegate.^can( 'thing' ) ?? $.delegate.thing !! "default implementation" } }   my Delegator $d .= new;   say "empty: "~$d.operation;   $d.delegate = Non-Delegate.new;   say "Non-Delegate: "~$d.operation;   $d.delegate = Delegate.new;   say "Delegate: "~$d.operation;
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Ruby
Ruby
class Delegator attr_accessor :delegate def operation if @delegate.respond_to?(:thing) @delegate.thing else 'default implementation' end end end   class Delegate def thing 'delegate implementation' end end   if __FILE__ == $PROGRAM_NAME   # No delegate a = Delegator.new puts a.operation # prints "default implementation"   # With a delegate that does not implement "thing" a.delegate = 'A delegate may be any object' puts a.operation # prints "default implementation"   # With delegate that implements "thing" a.delegate = Delegate.new puts a.operation # prints "delegate implementation" end
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#Raku
Raku
# Reference: # https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle # https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/   sub if-overlap ($triangle-pair) { my (\A,\B) = $triangle-pair; my Bool $result = False;   sub sign (\T) { return (T[0;0] - T[2;0]) × (T[1;1] - T[2;1]) - (T[1;0] - T[2;0]) × (T[0;1] - T[2;1]); }   sub point-in-triangle (\pt, \Y --> Bool) { my $d1 = sign (pt, Y[0], Y[1]); my $d2 = sign (pt, Y[1], Y[2]); my $d3 = sign (pt, Y[2], Y[0]);   my $has_neg = [or] $d1 < 0, $d2 < 0, $d3 < 0; my $has_pos = [or] $d1 > 0, $d2 > 0, $d3 > 0;   return not ($has_neg and $has_pos); }   sub orientation(\P, \Q, \R --> Int) { my \val = (Q[1] - P[1]) × (R[0] - Q[0]) - (Q[0] - P[0]) × (R[1] - Q[1]);   return 0 if val == 0; # colinear return val > 0 ?? 1 !! 2; # clock or counterclock wise }   sub onSegment(\P, \Q, \R --> Bool) { Q[0] ≤ max(P[0], R[0]) and Q[0] ≥ min(P[0], R[0]) and Q[1] ≤ max(P[1], R[1]) and Q[1] ≥ min(P[0], R[1]) ?? True !! False }   sub intersect(\A,\B,\C,\D --> Bool) { my \o1 = orientation A, C, D; my \o2 = orientation B, C, D; my \o3 = orientation A, B, C; my \o4 = orientation A, B, D;   o1 != o2 and o3 != o4 or o1 == 0 and onSegment A, C, D or o2 == 0 and onSegment B, C, D or o3 == 0 and onSegment A, B, C or o4 == 0 and onSegment A, B, D ?? True !! False }   for ^3 { { $result = True; last } if point-in-triangle A.[$^i], B or point-in-triangle B.[$^i], A ; }   unless $result { $result = True if intersect A.[0], A.[1], B.[0], B.[1] or intersect A.[0], A.[1], B.[0], B.[2] }   say "{A.gist} and {B.gist} do{' NOT' unless $result} overlap."; }   my \DATA = [ [ [(0,0),(5,0),(0,5)] , [(0,0),(5,0),(0,6)] ], [ [(0,0),(0,5),(5,0)] , [(0,0),(0,5),(5,0)] ], [ [(0,0),(5,0),(0,5)] , [(-10,0),(-5,0),(-1,6)] ], [ [(0,0),(5,0),(2.5,5)] , [ (0,4),(2.5,-1),(5,4)] ], [ [(0,0),(1,1),(0,2)] , [(2,1),(3,0),(3,2)] ], [ [(0,0),(1,1),(0,2)] , [(2,1),(3,-2),(3,4)] ], [ [(0,0),(1,0),(0,1)] , [(1,0),(2,0),(1,1)] ] ];   if-overlap $_ for DATA ;
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.
#Kotlin
Kotlin
// version 1.0.6   /* testing on Windows 10 which needs administrative privileges to delete files from the root */   import java.io.File   fun main(args: Array<String>) { val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") var f: File for (path in paths) { f = File(path) if (f.delete()) println("$path successfully deleted") else println("$path could not be deleted") } }
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.
#LabVIEW
LabVIEW
// delete file local(f = file('input.txt')) #f->delete   // delete directory // directory must be empty before it can be successfully deleted. A failure is generated if the operation fails. local(d = dir('docs')) #d->delete   // delete file in root file system (requires permissions at user OS level) local(f = file('//input.txt')) #f->delete   // delete directory in root file system (requires permissions at user OS level) // directory must be empty before it can be successfully deleted. A failure is generated if the operation fails. local(d = file('//docs')) #d->delete
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
#Rust
Rust
  fn main() { let mut m1: Vec<Vec<f64>> = vec![vec![1.0,2.0],vec![3.0,4.0]]; let mut r_m1 = &mut m1; let rr_m1 = &mut r_m1; let mut m2: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0, 4.0], vec![4.0, 5.0, 6.0, 7.0], vec![7.0, 8.0, 9.0, 10.0], vec![10.0, 11.0, 12.0, 13.0]]; let mut r_m2 = &mut m2; let rr_m2 = &mut r_m2; let mut m3: Vec<Vec<f64>> = vec![vec![0.0, 1.0, 2.0, 3.0, 4.0], vec![5.0, 6.0, 7.0, 8.0, 9.0], vec![10.0, 11.0, 12.0, 13.0, 14.0], vec![15.0, 16.0, 17.0, 18.0, 19.0], vec![20.0, 21.0, 22.0, 23.0, 24.0]]; let mut r_m3 = &mut m3; let rr_m3 = &mut r_m3;   println!("Determinant of m1: {}", determinant(rr_m1)); println!("Permanent of m1: {}", permanent(rr_m1));   println!("Determinant of m2: {}", determinant(rr_m2)); println!("Permanent of m2: {}", permanent(rr_m2));   println!("Determinant of m3: {}", determinant(rr_m3)); println!("Permanent of m3: {}", permanent(rr_m3));   }   fn minor( a: &mut Vec<Vec<f64>>, x: usize, y: usize) -> Vec<Vec<f64>> { let mut out_vec: Vec<Vec<f64>> = vec![vec![0.0; a.len() - 1]; a.len() -1]; for i in 0..a.len()-1 { for j in 0..a.len()-1 { match () { _ if (i < x && j < y) => { out_vec[i][j] = a[i][j]; }, _ if (i >= x && j < y) => { out_vec[i][j] = a[i + 1][j]; }, _ if (i < x && j >= y) => { out_vec[i][j] = a[i][j + 1]; }, _ => { //i > x && j > y out_vec[i][j] = a[i + 1][j + 1]; }, } } } out_vec }   fn determinant (matrix: &mut Vec<Vec<f64>>) -> f64 { match () { _ if (matrix.len() == 1) => { matrix[0][0] }, _ => { let mut sign = 1.0; let mut sum = 0.0; for i in 0..matrix.len() { sum = sum + sign * matrix[0][i] * determinant(&mut minor(matrix, 0, i)); sign = sign * -1.0; } sum } } }   fn permanent (matrix: &mut Vec<Vec<f64>>) -> f64 { match () { _ if (matrix.len() == 1) => { matrix[0][0] }, _ => { let mut sum = 0.0; for i in 0..matrix.len() { sum = sum + matrix[0][i] * permanent(&mut minor(matrix, 0, i)); } sum } } }    
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
#Scala
Scala
  def permutationsSgn[T]: List[T] => List[(Int,List[T])] = { case Nil => List((1,Nil)) case xs => { for { (x, i) <- xs.zipWithIndex (sgn,ys) <- permutationsSgn(xs.take(i) ++ xs.drop(1 + i)) } yield { val sgni = sgn * (2 * (i%2) - 1) (sgni, (x :: ys)) } } }   def det(m:List[List[Int]]) = { val summands = for { (sgn,sigma) <- permutationsSgn((0 to m.length - 1).toList).toList } yield { val factors = for (i <- 0 to (m.length - 1)) yield m(i)(sigma(i)) factors.toList.foldLeft(sgn)({case (x,y) => x * y}) } summands.toList.foldLeft(0)({case (x,y) => x + y})  
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.
#Maple
Maple
1/0; # Here is the default behavior.
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Check[2/0, Print["division by 0"], Power::infy]
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.
#MATLAB
MATLAB
function [isDividedByZero] = dividebyzero(numerator, denomenator) isDividedByZero = isinf( numerator/denomenator ); % If isDividedByZero equals 1, divide by zero occured.
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
#i
i
concept numeric(n) { number(n) errors { print(n, " is not numeric!") return } print(n, " is numeric :)") }   software { numeric("1200") numeric("3.14") numeric("3/4") numeric("abcdefg") numeric("1234test") }
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
#Icon_and_Unicon
Icon and Unicon
  write(image(x), if numeric(x) then " is numeric." else " is not numeric")  
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
#R
R
isAllUnique <- function(string) { strLength <- nchar(string) if(length(strLength) > 1) { #R has a distinction between the length of a string and that of a character vector. It is a common source #of problems when coming from another language. We will try to avoid the topic here. #For our purposes, let us only say that there is a good reason why we have made #isAllUnique(c("foo", "bar") immediately throw an error. stop("This task is intended for character vectors with lengths of at most 1.") } else if(length(strLength) == 0) { cat("Examining a character vector of length 0.", "It is therefore made entirely of unique characters.\n") TRUE } else if(strLength == 0) { cat("Examining a character vector of length 1, containing an empty string.", "It is therefore made entirely of unique characters.\n") TRUE } else if(strLength == 1) { cat("Examining the string", paste0(sQuote(string), ","), "which is of length", paste0(strLength, "."), "It is therefore made entirely of unique characters.\n") TRUE } else { cat("Examining the string", paste0(sQuote(string), ","), "which is of length", paste0(strLength, ":"), "\n") #strsplit outputs a list. Its first element is the vector of characters that we desire. characters <- strsplit(string, "")[[1]] #Our use of match is using R's vector recycling rules. Element i is being checked #against every other. indexesOfDuplicates <- sapply(seq_len(strLength), function(i) match(TRUE, characters[i] == characters[-i], nomatch = -1)) + 1 firstDuplicateElementIndex <- indexesOfDuplicates[indexesOfDuplicates != 0][1] if(is.na(firstDuplicateElementIndex)) { cat("It has no duplicates. It is therefore made entirely of unique characters.\n") TRUE } else { cat("It has duplicates. ") firstDuplicatedCharacter <- characters[firstDuplicateElementIndex] cat(sQuote(firstDuplicatedCharacter), "is the first duplicated character. It has hex value", sprintf("0x%X", as.integer(charToRaw(firstDuplicatedCharacter))), "and is at index", paste0(firstDuplicateElementIndex, "."), "\nThis is a duplicate of the character at index", paste0(match(firstDuplicateElementIndex, indexesOfDuplicates), "."), "\n") FALSE } } }   #Tests: cat("Test: A string of length 0 (an empty string):\n") cat("Test 1 of 2: An empty character vector:\n") print(isAllUnique(character(0))) cat("Test 2 of 2: A character vector containing the empty string:\n") print(isAllUnique("")) cat("Test: A string of length 1 which contains .:\n") print(isAllUnique(".")) cat("Test: A string of length 6 which contains abcABC:\n") print(isAllUnique("abcABC")) cat("Test: A string of length 7 which contains XYZ ZYX:\n") print(isAllUnique("XYZ ZYX")) cat("Test: A string of length 36 doesn't contain the letter 'oh':\n") print(isAllUnique("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"))
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
#REXX
REXX
/*REXX program verifies that all characters in a string are all the same (character). */ @chr= ' [character' /* define a literal used for SAY.*/ @all= 'all the same character for string (length' /* " " " " " " */ @.= /*define a default for the @. array. */ parse arg x /*obtain optional argument from the CL.*/ if x\='' then @.1= x /*if user specified an arg, use that. */ else do; @.1= /*use this null string if no arg given.*/ @.2= ' ' /* " " " " " " " */ @.3= 2 /* " " " " " " " */ @.4= 333 /* " " " " " " " */ @.5= .55 /* " " " " " " " */ @.6= 'tttTTT' /* " " " " " " " */ @.7= 4444 444k /* " " " " " " " */ end /* [↑] seventh value contains a blank.*/   do j=1; L= length(@.j) /*obtain the length of an array element*/ if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */ r= allSame(@.j) /*R: ≡0, or the location of bad char.*/ if r\==0 then ?= substr(@.j,r,1) /*if not monolithic, obtain the char.*/ if r==0 then say ' ' @all L"):" @.j else say 'not' @all L"):" @.j @chr ? "('"c2x(?)"'x) at position" r"]." end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ allSame: procedure; parse arg y /*get a value from the argument list. */ if y=='' then return 0 /*if Y is null, then return 0 (zero)*/ return verify(y, left(y,1) ) /*All chars the same? Return 0 (zero)*/ /* else return location*/
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.
#Tcl
Tcl
package require Thread   foreach name {Aristotle Kant Spinoza Marx Russel} { lappend forks [thread::mutex create] lappend tasks [set t [thread::create -preserved { # Implement each task as a coroutine internally for simplicity of presentation # This is because we want to remain able to receive messages so we can shut # down neatly at the end of the program. interp alias {} doTask {} coroutine t philosopher proc delay {expression} { yield [after [expr $expression] [info coroutine]] }   # Forks are mutexes... proc pickUpFork fork { thread::mutex lock $fork } proc putDownFork fork { thread::mutex unlock $fork }   # The actual implementation of the task proc philosopher {f1 f2} { global name # Always acquire forks in order; prevents deadlock # Uses the "natural" order of the lexicographical order of the fork names if {$f1 > $f2} { lassign [list $f1 $f2] f2 f1 }   # The classic "philosophers" loop while {true} { puts "$name is thinking" delay {int(200*rand())}   puts "$name is hungry, getting fork in left hand" pickUpFork $f1 delay {int(2000*rand())} ;# Make deadlock likely if it is possible!   puts "$name is hungry, getting fork in right hand" pickUpFork $f2   puts "$name is eating" delay {int(2000*rand())}   puts "$name has finished eating; putting down forks" putDownFork $f2 putDownFork $f1 delay 100 } } thread::wait }]] thread::send $t [list set name $name] }   # Set the tasks going foreach t $tasks {f1 f2} {0 1 1 2 2 3 3 4 4 0} { thread::send -async $t [list \ doTask [lindex $forks $f1] [lindex $forks $f2]] }   # Kill everything off after 30 seconds; that's enough for demonstration! after 30000 puts "Completing..." foreach t $tasks { thread::send -async $t thread::exit }
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Scala
Scala
package rosetta   import java.util.GregorianCalendar import java.util.Calendar   object DDate extends App { private val DISCORDIAN_SEASONS = Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath")   // month from 1-12; day from 1-31 def ddate(year: Int, month: Int, day: Int): String = { val date = new GregorianCalendar(year, month - 1, day) val dyear = year + 1166   val isLeapYear = date.isLeapYear(year) if (isLeapYear && month == 2 && day == 29) // 2 means February "St. Tib's Day " + dyear + " YOLD" else { var dayOfYear = date.get(Calendar.DAY_OF_YEAR) - 1 if (isLeapYear && dayOfYear >= 60) dayOfYear -= 1 // compensate for St. Tib's Day   val dday = dayOfYear % 73 val season = dayOfYear / 73 "%s %d, %d YOLD".format(DISCORDIAN_SEASONS(season), dday + 1, dyear) } } if (args.length == 3) println(ddate(args(2).toInt, args(1).toInt, args(0).toInt)) else if (args.length == 0) { val today = Calendar.getInstance println(ddate(today.get(Calendar.YEAR), today.get(Calendar.MONTH)+1, today.get(Calendar.DAY_OF_MONTH))) } else println("usage: DDate [day month 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)
#Swift
Swift
typealias WeightedEdge = (Int, Int, Int)   struct Grid<T> { var nodes: [Node<T>]   mutating func addNode(data: T) -> Int { nodes.append(Node(data: data, edges: []))   return nodes.count - 1 }   mutating func createEdges(weights: [WeightedEdge]) { for (start, end, weight) in weights { nodes[start].edges.append((end, weight)) nodes[end].edges.append((start, weight)) } }   func findPath(start: Int, end: Int) -> ([Int], Int)? { var dist = Array(repeating: (Int.max, nil as Int?), count: nodes.count) var heap = Heap<State>(sort: { $0.cost < $1.cost })   dist[start] = (0, nil) heap.insert(State(node: start, cost: 0))   while let state = heap.remove(at: 0) { if state.node == end { var path = [end] var currentDist = dist[end]   while let prev = currentDist.1 { path.append(prev) currentDist = dist[prev] }   return (path.reversed(), state.cost) }   guard state.cost <= dist[state.node].0 else { continue }   for edge in nodes[state.node].edges { let next = State(node: edge.0, cost: state.cost + edge.1)   if next.cost < dist[next.node].0 { dist[next.node] = (next.cost, state.node) heap.insert(next) } } }   return nil } }   struct Node<T> { var data: T var edges: [(Int, Int)] }   struct State { var node: Int var cost: Int }   var grid = Grid<String>(nodes: [])   let (a, b, c, d, e, f) = ( grid.addNode(data: "a"), grid.addNode(data: "b"), grid.addNode(data: "c"), grid.addNode(data: "d"), grid.addNode(data: "e"), grid.addNode(data: "f") )   grid.createEdges(weights: [ (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) ])   guard let (path, cost) = grid.findPath(start: a, end: e) else { fatalError("Could not find path") }   print("Cost: \(cost)") print(path.map({ grid.nodes[$0].data }).joined(separator: " -> "))
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
#Prolog
Prolog
digit_sum(N, Base, Sum):- digit_sum(N, Base, Sum, 0).   digit_sum(N, Base, Sum, S1):- N < Base, !, Sum is S1 + N. digit_sum(N, Base, Sum, S1):- divmod(N, Base, M, Digit), S2 is S1 + Digit, digit_sum(M, Base, Sum, S2).   digital_root(N, Base, AP, DR):- digital_root(N, Base, AP, DR, 0).   digital_root(N, Base, AP, N, AP):- N < Base, !. digital_root(N, Base, AP, DR, AP1):- digit_sum(N, Base, Sum), AP2 is AP1 + 1, digital_root(Sum, Base, AP, DR, AP2).   test_digital_root(N, Base):- digital_root(N, Base, AP, DR), writef('%w has additive persistence %w and digital root %w.\n', [N, AP, DR]).   main:- test_digital_root(627615, 10), test_digital_root(39390, 10), test_digital_root(588225, 10), test_digital_root(393900588225, 10), test_digital_root(685943443231217865409, 10).
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?
#Wren
Wren
import "/seq" for Lst   var permute // recursive permute = Fn.new { |input| if (input.count == 1) return [input] var perms = [] var toInsert = input[0] for (perm in permute.call(input.skip(1).toList)) { for (i in 0..perm.count) { var newPerm = perm.toList newPerm.insert(i, toInsert) perms.add(newPerm) } } return perms }   /* looks for for all possible solutions, not just the first */ var dinesman = Fn.new { |occupants, predicates| return permute.call(occupants).where { |perm| predicates.all { |pred| pred.call(perm) } } }   var occupants = ["Baker", "Cooper", "Fletcher", "Miller", "Smith"] var predicates = [ Fn.new { |p| p[-1] != "Baker" }, Fn.new { |p| p[0] != "Cooper" }, Fn.new { |p| p[-1] != "Fletcher" && p[0] != "Fletcher" }, Fn.new { |p| Lst.indexOf(p, "Miller") > Lst.indexOf(p, "Cooper") }, Fn.new { |p| (Lst.indexOf(p, "Smith") - Lst.indexOf(p, "Fletcher")).abs > 1 }, Fn.new { |p| (Lst.indexOf(p, "Fletcher") - Lst.indexOf(p, "Cooper")).abs > 1 } ]   var solutions = dinesman.call(occupants, predicates) var size = solutions.count if (size == 0) { System.print("No solutions found") } else { var plural = (size == 1) ? "" : "s" System.print("%(size) solution%(plural) found, namely:\n") for (solution in solutions) { var i = 0 for (name in solution) { System.print("Floor %(i+1) -> %(name)") i = i + 1 } System.print() } }
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
#MUMPS
MUMPS
DOTPROD(A,B)  ;Returns the dot product of two vectors. Vectors are assumed to be stored as caret-delimited strings of numbers.  ;If the vectors are not of equal length, a null string is returned. QUIT:$LENGTH(A,"^")'=$LENGTH(B,"^") "" NEW I,SUM SET SUM=0 FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(B,"^",I)) KILL I QUIT SUM
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
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections.NCollectionsExtensions;   module DotProduct { DotProduct(x : array[int], y : array[int]) : int { $[(a * b)|(a, b) in ZipLazy(x, y)].FoldLeft(0, _+_); }   Main() : void { def arr1 = array[1, 3, -5]; def arr2 = array[4, -2, -1]; WriteLine(DotProduct(arr1, arr2)); } }
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
#Fortran
Fortran
INTEGER P,S,F !Department codes for Police, Sanitation, and Fire. Values 1 to 7 only. 1 PP:DO P = 2,7,2 !The police demand an even number. They're special and use violence. 2 SS:DO S = 1,7 !The sanitation department accepts any value. 3 IF (P.EQ.S) CYCLE SS !But it must differ from the others. 4 F = 12 - (P + S) !The fire department accepts any number, but the sum must be twelve. 5 IF (F.LE.0 .OR. F.GT.7) CYCLE SS !Ensure that the only option is within range. 6 IF ((F - S)*(F - P)) 7,8,7 !And F is to differ from S and from P 7 WRITE (6,"(3I2)") P,S,F !If we get here, we have a possible set. 8 END DO SS !Next S 9 END DO PP !Next P. END !Well, that was straightforward.
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".
#Rust
Rust
trait Thingable { fn thing(&self) -> &str; }   struct Delegator<T>(Option<T>);   struct Delegate {}   impl Thingable for Delegate { fn thing(&self) -> &'static str { "Delegate implementation" } }   impl<T: Thingable> Thingable for Delegator<T> { fn thing(&self) -> &str { self.0.as_ref().map(|d| d.thing()).unwrap_or("Default implmementation") } }   fn main() { let d: Delegator<Delegate> = Delegator(None); println!("{}", d.thing());   let d: Delegator<Delegate> = Delegator(Some(Delegate {})); println!("{}", d.thing()); }
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".
#Scala
Scala
trait Thingable { def thing: String }   class Delegator { var delegate: Thingable = _   def operation: String = if (delegate == null) "default implementation" else delegate.thing }   class Delegate extends Thingable { override def thing = "delegate implementation" }   // Example usage // Memory management ignored for simplification object DelegateExample extends App {   val a = new Delegator assert(a.operation == "default implementation") // With a delegate: val d = new Delegate a.delegate = d assert(a.operation == "delegate implementation") // Same as the above, but with an anonymous class: a.delegate = new Thingable() { override def thing = "anonymous delegate implementation" } assert(a.operation == "anonymous delegate implementation")   }
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#REXX
REXX
/* REXX */ Signal On Halt Signal On Novalue Signal On Syntax   fid='trio.in' oid='trio.txt'; 'erase' oid     Call trio_test '0 0 5 0 0 5 0 0 5 0 0 6' Call trio_test '0 0 0 5 5 0 0 0 0 5 5 0' Call trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6' Call trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4' Call trio_test '0 0 1 1 0 2 2 1 3 0 3 2' Call trio_test '0 0 1 1 0 2 2 1 3 -2 3 4' Call trio_test '0 0 1 0 0 1 1 0 2 0 1 1'   Call trio_test '1 0 3 0 2 2 1 3 3 3 2 5' Call trio_test '1 0 3 0 2 2 1 3 3 3 2 2' Call trio_test '0 0 2 0 2 2 3 3 5 3 5 5' Call trio_test '2 0 2 6 1 8 0 1 0 5 8 3' Call trio_test '0 0 4 0 0 4 0 2 2 0 2 2' Call trio_test '0 0 4 0 0 4 1 1 2 1 1 2' Exit   trio_test: parse Arg tlist tlist=space(tlist) Parse Arg ax ay bx by cx cy dx dy ex ey fx fy   Say 'ABC:' show_p(ax ay) show_p(bx by) show_p(cx cy) Say 'DEF:' show_p(dx dy) show_p(ex ey) show_p(fx fy)   bordl=bord(tlist) /* corners that are on the other triangle's edges */ If bordl<>'' Then Say 'Corners on the other triangle''s edges:' bordl wb=words(bordl) /* how many of them? */ Select When wb=3 Then Do /* all three match */ If ident(ax ay,bx by,cx cy,dx dy,ex ey,fx fy) Then Say 'Triangles are identical' Else Say 'Triangles overlap' Say '' Return End When wb=2 Then Do /* two of them match */ Say 'Triangles overlap' Say ' they have a common edge 'bordl Say '' Return End When wb=1 Then Do /* one of them match */ Say 'Triangles touch on' bordl /* other parts may overlap */ Say ' we analyze further' End Otherwise /* we know nothing yet */ Nop End   trio_result=trio(tlist) /* any other overlap? */   Select When trio_result=0 Then Do /* none whatsoever */ If wb=1 Then Say 'Triangles touch (border case) at' show_p(bordl) Else Say 'Triangles don''t overlap' End When trio_result>0 Then /* plain overlapping case */ Say 'Triangles overlap' End Say '' Return   trio: /*--------------------------------------------------------------------- * Determine if two triangles overlap *--------------------------------------------------------------------*/ parse Arg tlist Parse Arg pax pay pbx pby pcx pcy pdx pdy pex pey pfx pfy   abc=subword(tlist,1,6) def=subword(tlist,7,6)   Do i=1 To 3 s.i=subword(abc abc,i*2-1,4) t.i=subword(def def,i*2-1,4) End   abc_='' def_=''   Do i=1 To 3 abc.i=subword(abc,i*2-1,2) /* corners of ABC */ def.i=subword(def,i*2-1,2) /* corners of DEF */ Parse Var abc.i x y; abc_=abc_ '('||x','y')' Parse Var def.i x y; def_=def_ '('||x','y')' End Call o 'abc_='abc_ Call o 'def_='def_   over=0 Do i=1 To 3 Until over Do j=1 To 3 Until over If ssx(s.i t.j) Then Do /* intersection of two edges */ over=1 Leave End End End   If over=0 Then Do /* no edge intersection found */ Do ii=1 To 3 Until over /* look for first possibility */ Call o ' ' 'abc.'ii'='abc.ii 'def='def Call o 'ii='ii 'def.'ii'='def.ii 'abc='abc If in_tri(abc.ii,def) Then Do /* a corner of ABC is in DEF */ Say abc.ii 'is within' def over=1 End Else If in_tri(def.ii,abc) Then Do /* a corner of DEF is in ABC */ Say def.ii 'is within' abc over=1 End End End   If over=0 Then rw='don''t ' Else rw=''   Call o 'Triangles' show_p(pax pay) show_p(pbx pby) show_p(pcx pcy), 'and' show_p(pdx pdy) show_p(pex pey) show_p(pfx pfy), rw'overlap' Call o '' Return over   ssx: Procedure Expose oid bordl /*--------------------------------------------------------------------- * Intersection of 2 line segments A-B and C-D *--------------------------------------------------------------------*/ Parse Arg xa ya xb yb xc yc xd yd   d=ggx(xa ya xb yb xc yc xd yd)   Call o 'ssx:' arg(1) d res=0 Select When d='-' Then res=0 When d='I' Then Do If xa<>xb Then Do xab_min=min(xa,xb) xcd_min=min(xc,xd) xab_max=max(xa,xb) xcd_max=max(xc,xd) If xab_min>xcd_max |, xcd_min>xab_max Then res=0 Else Do res=1 Select When xa=xc & isb(xc,xb,xd)=0 Then Do; x=xa; y=ya; End When xb=xc & isb(xc,xa,xd)=0 Then Do; x=xb; y=yb; End When xa=xd & isb(xc,xb,xd)=0 Then Do; x=xa; y=ya; End When xb=xd & isb(xc,xa,xd)=0 Then Do; x=xb; y=yb; End Otherwise Do x='*' y=ya End End Call o 'ssx:' x y End End Else Do yab_min=min(ya,yb) ycd_min=min(yc,yd) yab_max=max(ya,yb) ycd_max=max(yc,yd) If yab_min>ycd_max |, ycd_min>yab_max Then res=0 Else Do res=1 x=xa y='*' Parse Var bordl x_bord '/' y_bord If x=x_bord Then Do Call o xa'/* IGNORED' res=0 End End End End Otherwise Do Parse Var d x y If is_between(xa,x,xb) &, is_between(xc,x,xd) &, is_between(ya,y,yb) &, is_between(yc,y,yd) Then Do If x'/'y<>bordl Then res=1 End End End If res=1 Then Do Say 'Intersection of line segments: ('||x'/'y')' Parse Var bordl x_bord '/' y_bord If x=x_bord Then Do res=0 Call o x'/'y 'IGNORED' End End Else Call o 'ssx: -' Return res   ggx: Procedure Expose oid bordl /*--------------------------------------------------------------------- * Intersection of 2 (straight) lines *--------------------------------------------------------------------*/ Parse Arg xa ya xb yb xc yc xd yd res='' If xa=xb Then Do k1='*' x1=xa If ya=yb Then Do res='Points A and B are identical' rs='*' End End Else Do k1=(yb-ya)/(xb-xa) d1=ya-k1*xa End If xc=xd Then Do k2='*' x2=xc If yc=yd Then Do res='Points C and D are identical' rs='*' End End Else Do k2=(yd-yc)/(xd-xc) d2=yc-k2*xc End   If res='' Then Do If k1='*' Then Do If k2='*' Then Do If x1=x2 Then Do res='Lines AB and CD are identical' rs='I' End Else Do res='Lines AB and CD are parallel' rs='-' End End Else Do x=x1 y=k2*x+d2 End End Else Do If k2='*' Then Do x=x2 y=k1*x+d1 End Else Do If k1=k2 Then Do If d1=d2 Then Do res='Lines AB and CD are identical' rs='I' End Else Do res='Lines AB and CD are parallel' rs='-' End End Else Do x=(d2-d1)/(k1-k2) y=k1*x+d1 End End End End If res='' Then Do res='Intersection is ('||x'/'y')' rs=x y Call o 'line intersection' x y End Call o 'A=('xa'/'ya') B=('||xb'/'yb') C=('||xc'/'yc') D=('||xd'/'yd')' '-->' res Return rs   isb: Procedure Parse Arg a,b,c Return sign(b-a)<>sign(b-c)   is_between: Procedure Expose oid Parse Arg a,b,c Return diff_sign(b-a,b-c)   diff_sign: Procedure Parse Arg diff1,diff2 Return (sign(diff1)<>sign(diff2))|(sign(diff1)=0)   o: /*y 'sigl='sigl */ Return lineout(oid,arg(1))   in_tri: Procedure Expose oid bordl /*--------------------------------------------------------------------- * Determine if the point (px/py) is within the given triangle *--------------------------------------------------------------------*/ Parse Arg px py,ax ay bx by cx cy abc=ax ay bx by cx cy res=0 maxx=max(ax,bx,cx) minx=min(ax,bx,cx) maxy=max(ay,by,cy) miny=min(ay,by,cy)   If px>maxx|px<minx|py>maxy|py<miny Then Return 0   Parse Value mk_g(ax ay,bx by) With k.1 d.1 x.1 Parse Value mk_g(bx by,cx cy) With k.2 d.2 x.2 Parse Value mk_g(cx cy,ax ay) With k.3 d.3 x.3 /* say 'g1:' show_g(k.1,d.1,x.1) say 'g2:' show_g(k.2,d.2,x.2) say 'g3:' show_g(k.3,d.3,x.3) Say px py '-' ax ay bx by cx cy */ Do i=1 To 3 Select When k.i='*' Then Call o 'g.'i':' 'x='||x.i When k.i=0 Then Call o 'g.'i':' 'y='d.i Otherwise Call o 'g.'i':' 'y=' k.i'*x'dd(d.i) End End   If k.1='*' Then Do y2=k.2*px+d.2 y3=k.3*px+d.3 If is_between(y2,py,y3) Then res=1 End Else Do kp1=k.1 dp1=py-kp1*px If k.2='*' Then x12=x.2 Else x12=(d.2-dp1)/(kp1-k.2) If k.3='*' Then x13=x.3 Else x13=(d.3-dp1)/(kp1-k.3) If is_between(x12,px,x13) Then res=1 End   If res=1 Then rr=' ' Else rr=' not ' If pos(px'/'py,bordl)>0 Then Do ignored=' but is IGNORED' res=0 End Else ignored='' Say 'P ('px','py') is'rr'in' abc ignored Return res   bord: /*--------------------------------------------------------------------- * Look for corners of triangles that are situated * on the edges of the other triangle *--------------------------------------------------------------------*/ parse Arg tlist Parse Arg pax pay pbx pby pcx pcy pdx pdy pex pey pfx pfy bordl='' abc=subword(tlist,1,6) def=subword(tlist,7,6)   Do i=1 To 3 s.i=subword(abc abc,i*2-1,4) t.i=subword(def def,i*2-1,4) End   abc_='' def_='' Do i=1 To 3 abc.i=subword(abc,i*2-1,2) def.i=subword(def,i*2-1,2) Parse Var abc.i x y; abc_=abc_ '('||x','y')' Parse Var def.i x y; def_=def_ '('||x','y')' End   Do i=1 To 3 i1=i+1 If i1=4 Then i1=1 Parse Value mk_g(abc.i,abc.i1) With k.1.i d.1.i x.1.i Parse Value mk_g(def.i,def.i1) With k.2.i d.2.i x.2.i End Do i=1 To 3 Call o show_g(k.1.i,d.1.i,x.1.i) End Do i=1 To 3 Call o show_g(k.2.i,d.2.i,x.2.i) End   pl='' Do i=1 To 3 p=def.i Do j=1 To 3 j1=j+1 If j1=4 Then j1=1 g='1.'j If in_segment(p,abc.j,abc.j1) Then Do pp=Translate(p,'/',' ') If wordpos(pp,bordl)=0 Then bordl=bordl pp End Call o show_p(p) show_g(k.g,d.g,x.g) '->' bordl End End Call o 'Points on abc:' pl   pl='' Do i=1 To 3 p=abc.i Do j=1 To 3 j1=j+1 If j1=4 Then j1=1 g='2.'j If in_segment(p,def.j,def.j1)Then Do pp=Translate(p,'/',' ') If wordpos(pp,bordl)=0 Then bordl=bordl pp End Call o show_p(p) show_g(k.g,d.g,x.g) '->' bordl End End Call o 'Points on def:' pl   Return bordl   in_segment: Procedure Expose g. sigl /*--------------------------------------------------------------------- * Determine if point x/y is on the line segment ax/ay bx/by *--------------------------------------------------------------------*/ Parse Arg x y,ax ay,bx by Call show_p(x y) show_p(ax ay) show_p(bx by) Parse Value mk_g(ax ay,bx by) With gk gd gx Select When gx<>'' Then res=(x=gx & is_between(ay,y,by)) When gk='*' Then res=(y=gd & is_between(ax,x,bx)) Otherwise Do yy=gk*x+gd res=(y=yy & is_between(ax,x,bx)) End End Return res   mk_g: Procedure Expose g. /*--------------------------------------------------------------------- * given two points (a and b) * compute y=k*x+d or, if a vertical line, k='*'; x=c *--------------------------------------------------------------------*/ Parse Arg a,b /* 2 points */ Parse Var a ax ay Parse Var b bx by If ax=bx Then Do /* vertical line */ gk='*' /* special slope */ gx=ax /* x=ax is the equation */ gd='*' /* not required */ End Else Do gk=(by-ay)/(bx-ax) /* compute slope */ gd=ay-gk*ax /* compute y-distance */ gx='' /* not required */ End Return gk gd gx   is_between: Procedure Parse Arg a,b,c Return diff_sign(b-a,b-c)   diff_sign: Procedure Parse Arg diff1,diff2 Return (sign(diff1)<>sign(diff2))|(sign(diff1)=0)   show_p: Procedure Call trace 'O' Parse Arg x y If pos('/',x)>0 Then Parse Var x x '/' y Return space('('||x'/'y')',0)   isb: Procedure Expose oid Parse Arg a,b,c Return sign(b-a)<>sign(b-c)   o: Call o arg(1) Return   show_g: Procedure /*--------------------------------------------------------------------- * given slope, y-distance, and (special) x-value * compute y=k*x+d or, if a vertical line, k='*'; x=c *--------------------------------------------------------------------*/ Parse Arg k,d,x Select When k='*' Then res='x='||x /* vertical line */ When k=0 Then res='y='d /* horizontal line */ Otherwise Do /* ordinary line */ Select When k=1 Then res='y=x'dd(d) When k=-1 Then res='y=-x'dd(d) Otherwise res='y='k'*x'dd(d) End End End Return res   dd: Procedure /*--------------------------------------------------------------------- * prepare y-distance for display *--------------------------------------------------------------------*/ Parse Arg dd Select When dd=0 Then dd='' /* omit dd if it's zero */ When dd<0 Then dd=dd /* use dd as is (-value) */ Otherwise dd='+'dd /* prepend '+' to positive dd */ End Return dd   ident: Procedure /*--------------------------------------------------------------------- * Determine if the corners ABC match those of DEF (in any order) *--------------------------------------------------------------------*/ cnt.=0 Do i=1 To 6 Parse Value Arg(i) With x y cnt.x.y=cnt.x.y+1 End Do i=1 To 3 Parse Value Arg(i) With x y If cnt.x.y<>2 Then Return 0 End Return 1   Novalue: Say 'Novalue raised in line' sigl Say sourceline(sigl) Say 'Variable' condition('D') Signal lookaround   Syntax: Say 'Syntax raised in line' sigl Say sourceline(sigl) Say 'rc='rc '('errortext(rc)')'   halt: lookaround: If fore() Then Do Say 'You can look around now.' Trace ?R Nop End Exit 12
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.
#Lasso
Lasso
// delete file local(f = file('input.txt')) #f->delete   // delete directory // directory must be empty before it can be successfully deleted. A failure is generated if the operation fails. local(d = dir('docs')) #d->delete   // delete file in root file system (requires permissions at user OS level) local(f = file('//input.txt')) #f->delete   // delete directory in root file system (requires permissions at user OS level) // directory must be empty before it can be successfully deleted. A failure is generated if the operation fails. local(d = file('//docs')) #d->delete
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.
#Liberty_BASIC
Liberty BASIC
' show where we are print DefaultDir$   ' in here kill "input.txt" result=rmdir("Docs")   ' from root kill "\input.txt" result=rmdir("\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
#Sidef
Sidef
class Array { method permanent { var r = @^self.len   var sum = 0 r.permutations { |*a| var prod = 1 [a,r].zip {|row,col| prod *= self[row][col] } sum += prod }   return sum } }   var m1 = [[1,2],[3,4]]   var m2 = [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]]   var m3 = [[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]]   [m1, m2, m3].each { |m| say "determinant:\t #{m.determinant}\npermanent:\t #{m.permanent}\n" }
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Maxima
Maxima
f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]);   f(5, 6); 5 / 6   f(5, 0;) 'error
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.
#MAXScript
MAXScript
if not bit.isFinite (<i>expression</i>) then...
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#min
min
(/ inf ==) :div-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
#IDL
IDL
function isnumeric,input on_ioerror, false test = double(input) return, 1 false: return, 0 end
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#J
J
isNumeric=: _ ~: _ ". ] isNumericScalar=: 1 -: isNumeric TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents' sayIsNumericScalar=: , TXT {::~ isNumericScalar
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
#Racket
Racket
#lang racket   (define (first-non-unique-element.index seq) (let/ec ret (for/fold ((es (hash))) ((e seq) (i (in-naturals))) (if (hash-has-key? es e) (ret (list e (hash-ref es e) i)) (hash-set es e i))) #f))   (define (report-if-a-string-has-all-unique-characters str) (printf "~s (length ~a): ~a~%" str (string-length str) (match (first-non-unique-element.index str) [#f "contains all unique characters"] [(list e i i′) (format "has character '~a' (0x~a) at index ~a (first seen at ~a)" e (number->string (char->integer e) 16) i′ i)])))   (module+ main (for-each report-if-a-string-has-all-unique-characters (list "" "." "abcABC" "XYZ ZYX" "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")))  
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
-> $str { my $i = 0; print "\n{$str.raku} (length: {$str.chars}), has "; my %m; %m{$_}.push: ++$i for $str.comb; if any(%m.values) > 1 { say "duplicated characters:"; say "'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: "0x%X"})" ~ " in positions: {.value.join: ', '}" for %m.grep( *.value > 1 ).sort( *.value[0] ); } else { say "no duplicated characters." } } for '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ', '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X', '🦋🙂👨‍👩‍👧‍👦🙄ΔΔ̂ 🦋Δ👍👨‍👩‍👧‍👦'
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
#Ring
Ring
  nputStr = [""," ","2","333",".55","tttTTT","4444 444k"]   for word in inputStr for x = 1 to len(word) for y = x + 1 to len(word) if word[x] != word[y] char = word[y]  ? "Input = " + "'" + word + "'" + ", length = " + len(word)  ? " First difference at position " + y + ", character = " + "'" + char + "'" loop 3 ok next next    ? "Input = " + "'" + word + "'" + ", length = " + len(word)  ? " All characters are the same." next  
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
#Ruby
Ruby
strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]   strings.each do |str| pos = str.empty? ? nil : str =~ /[^#{str[0]}]/ print "#{str.inspect} (size #{str.size}): " puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." : "all the same." end  
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#VBA
VBA
'The combination of holding to the second fork '(HOLDON=True) and all philosophers start 'with same hand (DIJKSTRASOLUTION=False) leads 'to a deadlock. To prevent deadlock 'set HOLDON=False, and DIJKSTRASOLUTION=True. Public Const HOLDON = False Public Const DIJKSTRASOLUTION = True Public Const X = 10 'chance to continue eating/thinking Public Const GETS = 0 Public Const PUTS = 1 Public Const EATS = 2 Public Const THKS = 5 Public Const FRSTFORK = 0 Public Const SCNDFORK = 1 Public Const SPAGHETI = 0 Public Const UNIVERSE = 1 Public Const MAXCOUNT = 100000 Public Const PHILOSOPHERS = 5 Public semaphore(PHILOSOPHERS - 1) As Integer Public positi0n(1, PHILOSOPHERS - 1) As Integer Public programcounter(PHILOSOPHERS - 1) As Long Public statistics(PHILOSOPHERS - 1, 5, 1) As Long Public names As Variant Private Sub init() names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}] For j = 0 To PHILOSOPHERS - 2 positi0n(0, j) = j + 1 'first fork in right hand positi0n(1, j) = j 'second fork in left hand Next j If DIJKSTRASOLUTION Then positi0n(0, PHILOSOPHERS - 1) = j ' first fork in left hand positi0n(1, PHILOSOPHERS - 1) = 0 'second fork in right hand Else positi0n(0, PHILOSOPHERS - 1) = 0 'first fork in right hand positi0n(1, PHILOSOPHERS - 1) = j 'second fork in left hand End If End Sub Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer) statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1 If verb < 2 Then If semaphore(positi0n(objekt, subject)) <> verb Then If Not HOLDON Then 'can't get a fork, release first fork if subject has it, and 'this won't toggle the semaphore if subject hasn't firt fork semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt 'next round back to try to get first fork programcounter(subject) = 0 End If Else 'just toggle semaphore and move on semaphore(positi0n(objekt, subject)) = 1 - verb programcounter(subject) = (programcounter(subject) + 1) Mod 6 End If Else 'when eating or thinking, (100*(X-1)/X)% continue eating or thinking '(100/X)% advance program counter programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6 End If End Sub Private Sub dine() Dim ph As Integer Do While TC < MAXCOUNT For ph = 0 To PHILOSOPHERS - 1 Select Case programcounter(ph) Case 0: philosopher ph, GETS, FRSTFORK Case 1: philosopher ph, GETS, SCNDFORK Case 2: philosopher ph, EATS, SPAGHETI Case 3: philosopher ph, PUTS, FRSTFORK Case 4: philosopher ph, PUTS, SCNDFORK Case 5: philosopher ph, THKS, UNIVERSE End Select TC = TC + 1 Next ph Loop End Sub Private Sub show() Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks" Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About" Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe" For subject = 0 To PHILOSOPHERS - 1 Debug.Print names(subject + 1), For objekt = 0 To 1 Debug.Print statistics(subject, GETS, objekt), Next objekt Debug.Print statistics(subject, EATS, SPAGHETI), For objekt = 0 To 1 Debug.Print statistics(subject, PUTS, objekt), Next objekt Debug.Print statistics(subject, THKS, UNIVERSE) Next subject End Sub Public Sub main() init dine show End Sub
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i";   const array string: seasons is [0] ("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"); const array string: weekday is [0] ("Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"); const array string: apostle is [0] ("Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"); const array string: holiday is [0] ("Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux");   const func string: discordianDate (in time: date) is func result var string: discordianDate is ""; local var integer: dyear is 0; var integer: doy is 0; var integer: dsday is 0; begin dyear := date.year + 1166; if isLeapYear(date.year) and date.month = 2 and date.day = 29 then discordianDate := "St. Tib's Day, in the YOLD " <& dyear; else doy := dayOfYear(date); if isLeapYear(date.year) and doy >= 60 then decr(doy); end if; dsday := doy rem 73; # season day if dsday = 5 then discordianDate := apostle[doy div 73] <& ", in the YOLD " <& dyear; elsif dsday = 50 then discordianDate := holiday[doy div 73] <& ", in the YOLD " <& dyear; else discordianDate := weekday[pred(doy) rem 5] <& ", day " <& dsday <& " of " <& seasons[doy div 73] <& " in the YOLD " <& dyear; end if; end if; end func;   const proc: main is func local var time: today is time.value; begin today := time(NOW); writeln(strDate(today) <& " as Discordian date: " <& discordianDate(today)); if discordianDate(date(2010, 7, 22)) = "Pungenday, day 57 of Confusion in the YOLD 3176" and discordianDate(date(2012, 2, 28)) = "Prickle-Prickle, day 59 of Chaos in the YOLD 3178" and discordianDate(date(2012, 2, 29)) = "St. Tib's Day, in the YOLD 3178" and discordianDate(date(2012, 3, 1)) = "Setting Orange, day 60 of Chaos in the YOLD 3178" and discordianDate(date(2010, 1, 5)) = "Mungday, in the YOLD 3176" and discordianDate(date(2011, 5, 3)) = "Discoflux, in the YOLD 3177" then writeln("Discordian date computation works."); end if; end func;
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)
#Tailspin
Tailspin
  data vertex <'a'..'f'>, to <vertex>   templates shortestPaths&{graph:} @: []; [ {to: $, distance: 0"1", path:[]} ] -> # when <[](0)> do $@ ! otherwise def closest: $ ... -> ..=Min&{by: :(distance:), select: :()}; $closest -> ..|@: $; def path: [ $closest.path..., $closest.to ]; [ $... -> \(<?($.to <~=$closest.to>)> $!\), $graph... -> \(<?($.edge(1) <=$closest.to>) ?($@shortestPaths <~[<{to: <=$.edge(2)>}>]>)> $!\) -> { to: $.edge(2), distance: $.cost + $closest.distance, path: $path} ] -> # end shortestPaths   def edges: [ { edge: [vertex´'a', vertex´'b'], cost: 7"1" }, { edge: [vertex´'a', vertex´'c'], cost: 9"1" }, { edge: [vertex´'a', vertex´'f'], cost: 14"1" }, { edge: [vertex´'b', vertex´'c'], cost: 10"1" }, { edge: [vertex´'b', vertex´'d'], cost: 15"1" }, { edge: [vertex´'c', vertex´'d'], cost: 11"1" }, { edge: [vertex´'c', vertex´'f'], cost: 2"1" }, { edge: [vertex´'d', vertex´'e'], cost: 6"1" }, { edge: [vertex´'e', vertex´'f'], cost: 9"1" }];   def fromA: vertex´'a' -> shortestPaths&{graph: $edges};   $fromA... -> \(<{to:<=vertex´'e'>}> $!\) -> 'Shortest path from $.path(1); to $.to; is distance $.distance; via $.path(2..last); ' -> !OUT::write   $fromA... -> \(<{to:<=vertex´'f'>}> $!\) -> 'Shortest path from $.path(1); to $.to; is distance $.distance; via $.path(2..last); ' -> !OUT::write  
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
#PureBasic
PureBasic
; if you just want the DigitalRoot ; Procedure.q DigitalRoot(N.q) apparently will do ; i must have missed something because it seems too simple ; http://en.wikipedia.org/wiki/Digital_root#Congruence_formula   Procedure.q DigitalRoot(N.q) Protected M.q=N%9 if M=0:ProcedureReturn 9 Else  :ProcedureReturn M:EndIf EndProcedure   ; there appears to be a proof guarantying that Len(N$)<=1 for some X ; http://en.wikipedia.org/wiki/Digital_root#Proof_that_a_constant_value_exists   Procedure.s DigitalRootandPersistance(N.q) Protected r.s,t.s,X.q,M.q,persistance,N$=Str(N) M=DigitalRoot(N.q) ; just a test to see if we get the same DigitalRoot via the Congruence_formula   Repeat X=0:Persistance+1   For i=1 to Len(N$) ; finding X as the sum of the digits of N X+Val(Mid(N$,i,1)) Next   N$=Str(X) If Len(N$)<=1:Break:EndIf ; If Len(N$)<=1:Break:EndIf Forever   If Not (X-M)=0:t.s=" Error in my logic":else:t.s=" ok":EndIf   r.s=RSet(Str(N),15)+" has additive persistance "+Str(Persistance) r.s+" and digital root of X(slow) ="+Str(X)+" M(fast) ="+Str(M)+t.s ProcedureReturn r.s EndProcedure   NewList Nlist.q() AddElement(Nlist()) : Nlist()=627615 AddElement(Nlist()) : Nlist()=39390 AddElement(Nlist()) : Nlist()=588225 AddElement(Nlist()) : Nlist()=393900588225   FirstElement(Nlist())   ForEach Nlist() N.q=Nlist() ; cw(DigitalRootandPersistance(N)) Debug DigitalRootandPersistance(N) Next
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?
#XPL0
XPL0
include c:\cxpl\codes; int B, C, F, M, S; for B:= 1 to 4 do \Baker does not live on top (5th) floor for C:= 2 to 5 do \Cooper does not live on bottom floor if C#B then \Cooper & Baker live on different floors for F:= 2 to 4 do \Fletcher doesn't live on top or bottom if F#B & F#C & F#C-1 & F#C+1 then \ and she's not adjacent to Cooper for M:= 1 to 5 do if M#F & M#B & M>C then \Miller lives above Cooper for S:= 1 to 5 do \Smith is not adjacent to Fletcher if S#M & S#F & S#C & S#B & S#F-1 & S#F+1 then \show [Text(0, "Baker "); IntOut(0, B); CrLf(0); \all Text(0, "Cooper "); IntOut(0, C); CrLf(0); \possible Text(0, "Fletcher "); IntOut(0, F); CrLf(0); \solutions Text(0, "Miller "); IntOut(0, M); CrLf(0); Text(0, "Smith "); IntOut(0, S); CrLf(0); ]
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   whatsTheVectorVictor = [[double 1.0, 3.0, -5.0], [double 4.0, -2.0, -1.0]] dotProduct = Rexx dotProduct(whatsTheVectorVictor) say dotProduct.format(null, 2)   return   method dotProduct(vec1 = double[], vec2 = double[]) public constant returns double signals IllegalArgumentException if vec1.length \= vec2.length then signal IllegalArgumentException('Vectors must be the same length')   scalarProduct = double 0.0 loop e_ = 0 to vec1.length - 1 scalarProduct = vec1[e_] * vec2[e_] + scalarProduct end e_   return scalarProduct   method dotProduct(vecs = double[,]) public constant returns double signals IllegalArgumentException return dotProduct(vecs[0], vecs[1])
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
#FreeBASIC
FreeBASIC
' version 15-08-2017 ' compile with: fbc -s console   Dim As Integer fire, police, sanitation   Print "police fire sanitation" Print "----------------------"   For police = 2 To 7 Step 2 For fire = 1 To 7 If fire = police Then Continue For sanitation = 12 - police - fire If sanitation = fire Or sanitation = police Then Continue For If sanitation >= 1 And sanitation <= 7 Then Print Using " # # # "; police; fire; sanitation End If Next Next   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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".
#Sidef
Sidef
class NonDelegate { }   class Delegate { method thing { return "delegate implementation" } }   class Delegator (delegate = null) { method operation {   if (delegate.respond_to(:thing)) { return delegate.thing }   return "default implementation" } }   var d = Delegator() say "empty: #{d.operation}" d.delegate = NonDelegate() say "NonDelegate: #{d.operation}" d.delegate = Delegate() say "Delegate: #{d.operation}"
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Smalltalk
Smalltalk
Object subclass:#Thingy instanceVariableNames:''   thing ^ 'thingy 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".
#Swift
Swift
import Foundation   protocol Thingable { // prior to Swift 1.2, needs to be declared @objc func thing() -> String }   class Delegator { weak var delegate: AnyObject? func operation() -> String { if let f = self.delegate?.thing { return f() } else { return "default implementation" } } }   class Delegate { dynamic func thing() -> String { return "delegate implementation" } }   // Without a delegate: let a = Delegator() println(a.operation()) // prints "default implementation"   // With a delegate that does not implement thing: a.delegate = "A delegate may be any object" println(a.operation()) // prints "default implementation"   // With a delegate that implements "thing": let d = Delegate() a.delegate = d println(a.operation()) // prints "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)
#Ruby
Ruby
require "matrix"   def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end   def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end   def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end   def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end   def triTri2D(t1, t2, eps, allowReversed, onBoundary) # Triangles must be expressed anti-clockwise checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed)   if onBoundary then # Points on the boundary are considered as colliding chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else # Points on the boundary are not considered as colliding chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end   # For edge E of triangle 1 for i in 0..2 do j = (i + 1) % 3   # Check all points of trangle 2 lay on the external side of the edge E. If # they do, the triangles do not collide. if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end   # For edge E of triangle 2 for i in 0..2 do j = (i + 1) % 3   # Check all points of trangle 1 lay on the external side of the edge E. If # they do, the triangles do not collide. if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end   # The triangles collide return true end   def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)]   t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   # Barely touching t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)]   # Barely touching t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end   main()
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.
#Lingo
Lingo
-- note: fileIO xtra is shipped with Director, i.e. an "internal" fp = xtra("fileIO").new() fp.openFile("input.txt", 0) fp.delete()
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.
#Locomotive_Basic
Locomotive Basic
|era,"input.txt"
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
#Simula
Simula
! MATRIX ARITHMETIC ; BEGIN   INTEGER PROCEDURE LENGTH(A); ARRAY A; LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1;    ! Set MAT to the first minor of A dropping row X and column Y ; PROCEDURE MINOR(A, X, Y, MAT); ARRAY A, MAT; INTEGER X, Y; BEGIN INTEGER I, J, rowA, M; M := LENGTH(A) - 1; ! not a constant; FOR I := 1 STEP 1 UNTIL M DO BEGIN rowA := IF I < X THEN I ELSE I + 1; FOR J := 1 STEP 1 UNTIL M DO MAT(I, J) := A(rowA, IF J < Y THEN J else J + 1); END END MINOR;   REAL PROCEDURE DET(A); REAL ARRAY A; BEGIN INTEGER N; N := LENGTH(A); IF N = 1 THEN DET := A(1, 1) ELSE BEGIN INTEGER I, SIGN; REAL SUM; SIGN := 1; FOR I := 1 STEP 1 UNTIL N DO BEGIN REAL ARRAY MAT(1:N-1, 1:N-1); MINOR(A, 1, I, MAT); SUM := SUM + SIGN * A(1, I) * DET(MAT); SIGN := SIGN * -1 END; DET := SUM END END DET;   REAL PROCEDURE PERM(A); REAL ARRAY A; BEGIN INTEGER N; N := LENGTH(A); IF N = 1 THEN PERM := A(1, 1) ELSE BEGIN REAL SUM; INTEGER I;   FOR I := 1 STEP 1 UNTIL N DO BEGIN REAL ARRAY MAT(1:N-1, 1:N-1); MINOR(A, 1, I, MAT); SUM := SUM + A(1, I) * PERM(MAT) END; PERM := SUM END END PERM;   INTEGER SIZE; SIZE := ININT; BEGIN REAL ARRAY A(1:SIZE, 1:SIZE); INTEGER I, J;   FOR I := 1 STEP 1 UNTIL SIZE DO BEGIN  ! may be need here: INIMAGE; FOR J := 1 STEP 1 UNTIL SIZE DO A(I, J) := INREAL END; OUTTEXT("DETERMINANT ... : "); OUTREAL(DET (A), 10, 20); OUTIMAGE; OUTTEXT("PERMANENT ..... : "); OUTREAL(PERM(A), 10, 20); OUTIMAGE; END   COMMENT THE FIRST INPUT IS THE SIZE OF THE MATRIX, FOR EXAMPLE:    ! 2  ! 1 2  ! 3 4  ! DETERMINANT: -2.0  ! PERMANENT: 10.0 ;   COMMENT  ! 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  ! DETERMINANT: 0.0  ! PERMANENT: 6778800.0 ;   END
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by perm ⁡ ( A ) = ∑ σ ∏ i = 1 n M i , σ i {\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}} In both cases the sum is over the permutations σ {\displaystyle \sigma } of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known. Related task Permutations by swapping
#SPAD
SPAD
(1) -> M:=matrix [[2, 9, 4], [7, 5, 3], [6, 1, 8]]   +2 9 4+ | | (1) |7 5 3| | | +6 1 8+ Type: Matrix(Integer) (2) -> determinant M   (2) - 360 Type: Integer (3) -> permanent M   (3) 900 Type: PositiveInteger
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.
#mIRC_Scripting_Language
mIRC Scripting Language
var %n = $rand(0,1) if ($calc(1/ %n) == $calc((1/ %n)+1)) { echo -ag Divides By Zero } else { echo -ag Does Not Divide By Zero }
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#MUMPS
MUMPS
DIV(A,B) ;Divide A by B, and watch for division by zero  ;The ANSI error code for division by zero is "M9".  ;$ECODE errors are surrounded by commas when set. NEW $ETRAP SET $ETRAP="GOTO DIVFIX^ROSETTA" SET D=(A/B) SET $ETRAP="" QUIT D DIVFIX IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT "" QUIT "" ; Fall through for other errors
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
#Java
Java
public boolean isNumeric(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { // s is not numeric return false; } }
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
#JavaScript
JavaScript
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } var value = "123.45e7"; // Assign string literal to value if (isNumeric(value)) { // value is a number } //Or, in web browser in address field: // javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}  
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
#REXX
REXX
/*REXX pgm determines if a string is comprised of all unique characters (no duplicates).*/ @.= /*assign a default for the @. array. */ parse arg @.1 /*obtain optional argument from the CL.*/ if @.1='' then do; @.1= /*Not specified? Then assume defaults.*/ @.2= . @.3= 'abcABC' @.4= 'XYZ ZYX' @.5= '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' end   do j=1; if j\==1 & @.j=='' then leave /*String is null & not j=1? We're done*/ say copies('─', 79) /*display a separator line (a fence). */ say 'Testing for the string (length' length(@.j)"): " @.j say dup= isUnique(@.j) say 'The characters in the string' word("are aren't", 1 + (dup>0) ) 'all unique.' if dup==0 then iterate  ?= substr(@.j, dup, 1) say 'The character '  ? " ('"c2x(?)"'x) at position " dup , ' is repeated at position ' pos(?, @.j, dup+1) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isUnique: procedure; parse arg x /*obtain the character string.*/ do k=1 to length(x) - 1 /*examine all but the last. */ p= pos( substr(x, k, 1), x, k + 1) /*see if the Kth char is a dup*/ if p\==0 then return k /*Find a dup? Return location.*/ end /*k*/ return 0 /*indicate all chars unique. */
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
#Rust
Rust
fn test_string(input: &str) { println!("Checking string {:?} of length {}:", input, input.chars().count());   let mut chars = input.chars();   match chars.next() { Some(first) => { if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() { println!("\tNot all characters are the same."); println!("\t{:?} (0x{:X}) at position {} differs.", character, character as u32, pos);   return; } }, None => {} }   println!("\tAll characters in the string are the same"); }   fn main() { let tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"];   for string in &tests { test_string(string); } }
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
#Scala
Scala
import scala.collection.immutable.ListMap   object StringAllSameCharacters {   /**Transform an input String into an HashMap of its characters and its first occurrence index*/ def countChar( s : String) : Map[Char, Int] = { val mapChar = s.toSeq.groupBy(identity).map{ case (a,b) => a->s.indexOf(a) } val orderedMapChar = ListMap(mapChar.toSeq.sortWith(_._2 < _._2):_*) orderedMapChar }   /**Check if all the characters of a String are the same given an input Hashmap of it */ def areAllCharEquals ( mapChar : Map[Char, Int] ) : Boolean = { return mapChar.size <= 1 }   /**Retrieve the first "breaking" different character of a String*/ def findFirstDifferentChar ( mapChar : Map[Char, Int] ) : Char = { if(areAllCharEquals(mapChar) == false) mapChar.keys.toList(1) else 0.toChar }   /**Convert char to hexadecimal values as "0xHEXVALUE" */ def charToHexString ( c : Char) : String = "0x" + c.toHexString   /**Display results as asked in the ask*/ def reportResults( s : String) : String = { val mapChar = countChar(s) if (areAllCharEquals(mapChar)) s + " -- length " + s.size + " -- contains all the same character." else { val diffChar = findFirstDifferentChar(mapChar) s + " -- length " + s.size + " -- contains a different character at index " + (s.indexOf(diffChar).toInt+1).toString + " : " + charToHexString(diffChar) } }   def main(args: Array[String]): Unit = { println(reportResults("")) println(reportResults(" ")) println(reportResults("2")) println(reportResults("333")) println(reportResults(".55")) println(reportResults("tttTTT")) println(reportResults("4444 444k")) }     }    
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Threading Module Module1 Public rnd As New Random   Sub Main() 'Aristotle, Kant, Spinoza, Marx, and Russel Dim f1 As New Fork(1) Dim f2 As New Fork(2) Dim f3 As New Fork(3) Dim f4 As New Fork(4) Dim f5 As New Fork(5)   Console.WriteLine("1: Deadlock") Console.WriteLine("2: Live lock") Console.WriteLine("3: Working") Select Console.ReadLine Case "1" Using _ Aristotle As New SelfishPhilosopher("Aristotle", f1, f2), _ Kant As New SelfishPhilosopher("Kant", f2, f3), _ Spinoza As New SelfishPhilosopher("Spinoza", f3, f4), _ Marx As New SelfishPhilosopher("Marx", f4, f5), _ Russel As New SelfishPhilosopher("Russel", f5, f1)   Console.ReadLine() End Using Case "2" Using _ Aristotle As New SelflessPhilosopher("Aristotle", f1, f2), _ Kant As New SelflessPhilosopher("Kant", f2, f3), _ Spinoza As New SelflessPhilosopher("Spinoza", f3, f4), _ Marx As New SelflessPhilosopher("Marx", f4, f5), _ Russel As New SelflessPhilosopher("Russel", f5, f1)   Console.ReadLine() End Using Case "3" Using _ Aristotle As New WisePhilosopher("Aristotle", f1, f2), _ Kant As New WisePhilosopher("Kant", f2, f3), _ Spinoza As New WisePhilosopher("Spinoza", f3, f4), _ Marx As New WisePhilosopher("Marx", f4, f5), _ Russel As New WisePhilosopher("Russel", f5, f1)   Console.ReadLine() End Using End Select End Sub   End Module
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Sidef
Sidef
require('Time::Piece');   var seasons = %w(Chaos Discord Confusion Bureaucracy The\ Aftermath); var week_days = %w(Sweetmorn Boomtime Pungenday Prickle-Prickle Setting\ Orange);   func ordinal (n) { "#{n}" + (n % 100 ~~ [11,12,13] ? 'th'  : <th st nd rd th th th th th th>[n % 10]) }   func ddate(ymd) { var d = %s'Time::Piece'.strptime(ymd, '%Y-%m-%d'); var yold = "in the YOLD #{d.year + 1166}";   var day_of_year0 = d.day_of_year;   if (d.is_leap_year) { return "St. Tib's Day, #{yold}" if ([d.mon, d.mday] == [2, 29]); day_of_year0-- if (day_of_year0 >= 60); # Compensate for St. Tib's Day }   var weekday = week_days[day_of_year0 % week_days.len]; var season = seasons[day_of_year0 / 73]; var season_day = ordinal(day_of_year0 % 73 + 1);   return "#{weekday}, the #{season_day} day of #{season} #{yold}"; }   %w(2010-07-22 2012-02-28 2012-02-29 2012-03-01).each { |ymd| say "#{ymd} is #{ddate(ymd)}" }
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)
#Tcl
Tcl
proc dijkstra {graph origin} { # Initialize dict for {vertex distmap} $graph { dict set dist $vertex Inf dict set path $vertex {} } dict set dist $origin 0 dict set path $origin [list $origin]   while {[dict size $graph]} { # Find unhandled node with least weight set d Inf dict for {uu -} $graph { if {$d > [set dd [dict get $dist $uu]]} { set u $uu set d $dd } }   # No such node; graph must be disconnected if {$d == Inf} break   # Update the weights for nodes lead to by the node we've picked dict for {v dd} [dict get $graph $u] { if {[dict exists $graph $v]} { set alt [expr {$d + $dd}] if {$alt < [dict get $dist $v]} { dict set dist $v $alt dict set path $v [list {*}[dict get $path $u] $v] } } }   # Remove chosen node from graph still to be handled dict unset graph $u } return [list $dist $path] }
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Python
Python
def digital_root (n): ap = 0 n = abs(int(n)) while n >= 10: n = sum(int(digit) for digit in str(n)) ap += 1 return ap, n   if __name__ == '__main__': for n in [627615, 39390, 588225, 393900588225, 55]: persistance, root = digital_root(n) print("%12i has additive persistance %2i and digital root %i."  % (n, persistance, root))
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?
#zkl
zkl
var Baker, Cooper, Fletcher, Miller, Smith; // value == floor const bottom=1,top=5; // floors: 1..5 // All live on different floors, enforced by using permutations of floors //fcn c0{ (Baker!=Cooper!=Fletcher) and (Fletcher!=Miller!=Smith) } fcn c1{ Baker!=top } fcn c2{ Cooper!=bottom } fcn c3{ bottom!=Fletcher!=top } fcn c4{ Miller>Cooper } fcn c5{ (Fletcher - Smith).abs() !=1 } fcn c6{ (Fletcher - Cooper).abs()!=1 }   filters:=T(c1,c2,c3,c4,c5,c6); dudes:=T("Baker","Cooper","Fletcher","Miller","Smith"); // for reflection foreach combo in (Utils.Helpers.permuteW([bottom..top].walk())){ // lazy dudes.zip(combo).apply2(fcn(nameValue){ setVar(nameValue.xplode()) }); if(not filters.runNFilter(False)){ // all constraints are True vars.println(); // use reflection to print solution 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
#newLISP
newLISP
(define (dot-product x y) (apply + (map * x y)))   (println (dot-product '(1 3 -5) '(4 -2 -1)))
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
#Gambas
Gambas
Public Sub Main() Dim siC0, siC1, siC2 As Short Dim sOut As New String[] Dim sTemp As String   For siC0 = 2 To 6 Step 2 For siC1 = 1 To 7 For siC2 = 1 To 7 If sic0 + siC1 + siC2 = 12 Then If siC0 <> siC1 And siC1 <> siC2 And siC0 <> siC2 Then sOut.Add(Str(siC0) & Str(siC1) & Str(siC2)) End If Next Next Next   Print "\tPolice\tFire\tSanitation" siC0 = 0   For Each sTemp In sOut Inc sic0 Print "[" & Format(Str(siC0), "00") & "]\t" & Left(sTemp, 1) & "\t" & Mid(sTemp, 2, 1) & "\t" & Right(sTemp, 1) Next   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".
#Tcl
Tcl
package require TclOO   oo::class create Delegate { method thing {} { return "delegate impl." } export thing }   oo::class create Delegator { variable delegate constructor args { my delegate {*}$args }   method delegate args { if {[llength $args] == 0} { if {[info exists delegate]} { return $delegate } } elseif {[llength $args] == 1} { set delegate [lindex $args 0] } else { return -code error "wrong # args: should be \"[self] delegate ?target?\"" } }   method operation {} { try { set result [$delegate thing] } on error e { set result "default implementation" } return $result } }   # to instantiate a named object, use: class create objname; objname aMethod # to have the class name the object: set obj [class new]; $obj aMethod   Delegator create a set b [Delegator new "not a delegate object"] set c [Delegator new [Delegate new]]   assert {[a operation] eq "default implementation"} ;# a "named" object, hence "a ..." assert {[$b operation] eq "default implementation"} ;# an "anonymous" object, hence "$b ..." assert {[$c operation] ne "default implementation"}   # now, set a delegate for object a a delegate [$c delegate] assert {[a operation] ne "default implementation"}   puts "all assertions passed"
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)
#Scala
Scala
object Overlap { type Point = (Double, Double)   class Triangle(var p1: Point, var p2: Point, var p3: Point) { override def toString: String = s"Triangle: $p1, $p2, $p3" }   def det2D(t: Triangle): Double = { val (p1, p2, p3) = (t.p1, t.p2, t.p3) p1._1 * (p2._2 - p3._2) + p2._1 * (p3._2 - p1._2) + p3._1 * (p1._2 - p2._2) }   def checkTriWinding(t: Triangle, allowReversed: Boolean): Unit = { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw new RuntimeException("Triangle has wrong winding direction") } }   def boundaryCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) < eps   def boundaryDoesntCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) <= eps   def triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean = { //triangles must be expressed anti-clockwise checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) // 'onBoundary' determines whether points on boundary are considered as colliding or not val chkEdge = if (onBoundary) Overlap.boundaryCollideChk _ else Overlap.boundaryDoesntCollideChk _ val lp1 = Array(t1.p1, t1.p2, t1.p3) val lp2 = Array(t2.p1, t2.p2, t2.p3)   // for each edge E of t1 for (i <- 0 until 3) { val 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(new Triangle(lp1(i), lp1(j), lp2(0)), eps) && chkEdge(new Triangle(lp1(i), lp1(j), lp2(1)), eps) && chkEdge(new Triangle(lp1(i), lp1(j), lp2(2)), eps)) return false }   // for each edge E of t2 for (i <- 0 until 3) { val 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(new Triangle(lp2(i), lp2(j), lp1(0)), eps) && chkEdge(new Triangle(lp2(i), lp2(j), lp1(1)), eps) && chkEdge(new Triangle(lp2(i), lp2(j), lp1(2)), eps)) return false }   // The triangles overlap true }   def main(args: Array[String]): Unit = { var t1 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0)) var t2 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 6.0)) println(s"$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   // need to allow reversed for this pair to avoid exception t1 = new Triangle((0.0, 0.0), (0.0, 5.0), (5.0, 0.0)) t2 = t1 println(s"\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, allowReversed = true)) "overlap (reversed)" else "do not overlap")   t1 = new Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0)) t2 = new Triangle((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)) println(s"\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   t1.p3 = (2.5, 5.0) t2 = new Triangle((0.0, 4.0), (2.5, -1.0), (5.0, 4.0)) println(s"\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   t1 = new Triangle((0.0, 0.0), (1.0, 1.0), (0.0, 2.0)) t2 = new Triangle((2.0, 1.0), (3.0, 0.0), (3.0, 2.0)) println(s"\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   t2 = new Triangle((2.0, 1.0), (3.0, -2.0), (3.0, 4.0)) println(s"\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   t1 = new Triangle((0.0, 0.0), (1.0, 0.0), (0.0, 1.0)) t2 = new Triangle((1.0, 0.0), (2.0, 0.0), (1.0, 1.1)) println(s"\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")   println(s"\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, onBoundary = false)) "overlap" else "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.
#Logo
Logo
erasefile "input.txt erasefile "/input.txt
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.
#Lua
Lua
os.remove("input.txt") os.remove("/input.txt") os.remove("docs") os.remove("/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
#Stata
Stata
real vector range1(real scalar n, real scalar i) { if (i < 1 | i > n) { return(1::n) } else if (i == 1) { return(2::n) } else if (i == n) { return(1::n-1) } else { return(1::i-1\i+1::n) } }   real matrix submat(real matrix a, real scalar i, real scalar j) { return(a[range1(rows(a), i), range1(cols(a), j)]) }   real scalar sumrec(real matrix a, real scalar x) { real scalar n, s, p n = rows(a) if (n==1) return(a[1,1]) s = 0 p = 1 for (i=1; i<=n; i++) { s = s+p*a[i,1]*sumrec(submat(a, i, 1), x) p = p*x } return(s) }
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
#Tcl
Tcl
package require math::linearalgebra package require struct::list   proc permanent {matrix} { for {set plist {};set i 0} {$i<[llength $matrix]} {incr i} { lappend plist $i } foreach p [::struct::list permutations $plist] { foreach i $plist j $p { lappend prod [lindex $matrix $i $j] } lappend sum [::tcl::mathop::* {*}$prod[set prod {}]] } return [::tcl::mathop::+ {*}$sum] }
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.
#Nanoquery
Nanoquery
def div_check(x, y) try (x / y) return false catch return true end end