  [ 0 swap
    dup size 0 = iff
      drop done
    behead swap witheach
      [ over != if
          [ drop i^ 1+
            swap conclude ] ]
    drop ]                    is allsame ( [ --> n )

  ( 0 indicates all items are the same,
    otherwise n is first different item )

  [ say ' String: "' dup echo$
    say '" length ' dup size echo
    dup allsame dup 0 = iff
      [ say ', all characters are the same.'
        2drop ]
    else
      [ say ', first difference is item '
        dup echo
        say ', char "'
        peek dup emit
        say '", hex: '
        16 base put echo base release
        say '.' ]
    cr ]                      is task    ( $ -->   )

  $ ""          task
  $ "   "       task
  $ "2"         task
  $ ".55"       task
  $ "tttTTT"    task
  $ "4444 444k" task


isAllSame <- 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
    #isAllSame(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.\n")
    TRUE
  }
  else if(strLength == 0)
  {
    cat("Examining a character vector of length 1, containing an empty string.\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. Every element is being checked
    #against the first.
    differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0)
    if(differentElementIndex == 0)
    {
      cat("It has no duplicates.\n")
      TRUE
    }
    else
    {
      cat("It has duplicates. ")
      firstDifferentCharacter <- characters[differentElementIndex]
      cat(sQuote(firstDifferentCharacter), "is the first different character. It has hex value",
          sprintf("0x%X", as.integer(charToRaw(firstDifferentCharacter))),
          "and is at index", paste0(differentElementIndex, "."), "\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(isAllSame(character(0)))
cat("Test 2 of 2: A character vector containing the empty string:\n")
print(isAllSame(""))
cat("Test: A string of length 3 which contains three blanks:\n")
print(isAllSame("   "))
cat("Test: A string of length 1 which contains 2:\n")
print(isAllSame("2"))
cat("Test: A string of length 3 which contains 333:\n")
print(isAllSame("333"))
cat("Test: A string of length 3 which contains .55:\n")
print(isAllSame(".55"))
cat("Test: A string of length 6 which contains tttTTT:\n")
print(isAllSame("tttTTT"))
cat("Test: A string of length 9 which contains 4444 444k:\n")
print(isAllSame("4444 444k"))


(defn uniq-char-string [s]
  (let [len (count s)]
    (if (= len (count (set s)))
      (println (format "All %d chars unique in: '%s'" len s))
      (loop [prev-chars #{}
             idx   0
             chars (vec s)]
        (let [c (first chars)]
          (if (contains? prev-chars c)
            (println (format "'%s' (len: %d) has '%c' duplicated at idx: %d"
                             s len c idx))
            (recur (conj prev-chars c)
                   (inc idx)
                   (rest chars))))))))


;; * Loading the iterate library
(eval-when (:compile-toplevel :load-toplevel)
  (ql:quickload '("iterate")))

;; * The package definition
(defpackage :unique-string
  (:use :common-lisp :iterate))
(in-package :unique-string)

;; * The test strings
(defparameter test-strings
  '("" "." "abcABC" "XYZ ZYX" "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"))

;; * The function
(defun unique-string (string)
  "Returns T if STRING has all unique characters."
  (iter
    (with hash = (make-hash-table :test #'equal))
    (with len = (length string))
    (with result = T)
    (for char in-string string)
    (for pos  from 0)
    (initially (format t "String ~a of length ~D~%" string len))
    (if #1=(gethash char hash)
        ;; The character was seen before
        (progn
          (format t
                  " --> Non-unique character ~c #X~X found at position ~D,
                  before ~D ~%" char (char-code char) pos #1#)
          (setf result nil))
        ;; The character was not seen before, saving its position
        (setf #1# pos))
    (finally (when result
               (format t " --> All characters are unique~%"))
             (return result))))

(mapcar #'unique-string test-strings)


#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")))


  -> $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АΑꓮ𐌀𐊠Ꭺ'


/*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*/


import std.stdio;

void uniqueCharacters(string str) {
    writefln("input: `%s`, length: %d", str, str.length);
    foreach (i; 0 .. str.length) {
        foreach (j; i + 1 .. str.length) {
            if (str[i] == str[j]) {
                writeln("String contains a repeated character.");
                writefln("Character '%c' (hex %x) occurs at positions %d and %d.", str[i], str[i], i + 1, j + 1);
                writeln;
                return;
            }
        }
    }
    writeln("String contains no repeated characters.");
    writeln;
}

void main() {
    uniqueCharacters("");
    uniqueCharacters(".");
    uniqueCharacters("abcABC");
    uniqueCharacters("XYZ ZYX");
    uniqueCharacters("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
}


program Determine_if_a_string_has_all_unique_characters;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

procedure string_has_repeated_character(str: string);
var
  len, i, j: Integer;
begin
  len := length(str);
  Writeln('input: \', str, '\, length: ', len);
  for i := 1 to len - 1 do
  begin
    for j := i + 1 to len do
    begin
      if str[i] = str[j] then
      begin
        Writeln('String contains a repeated character.');
        Writeln('Character "', str[i], '" (hex ', ord(str[i]).ToHexString,
          ') occurs at positions ', i + 1, ' and ', j + 1, '.'#10);
        Exit;
      end;
    end;
  end;
  Writeln('String contains no repeated characters.' + sLineBreak);
end;

begin
  string_has_repeated_character('');
  string_has_repeated_character('.');
  string_has_repeated_character('abcABC');
  string_has_repeated_character('XYZ ZYX');
  string_has_repeated_character('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ');
  readln;
end.


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


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


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);
    }
}


-module(string_examples).
-export([all_unique/1, all_unique_examples/0]).

all_unique(String) ->
    CharPosPairs = lists:zip(String, lists:seq(1, length(String))),
    Duplicates = [{Char1, Pos1, Pos2} || {Char1, Pos1} <- CharPosPairs,
                                         {Char2, Pos2} <- CharPosPairs,
                                         Char1 =:= Char2,
                                         Pos2 > Pos1],
    case Duplicates of
        [] ->
            all_unique;
        [{Char, P1, P2}|_] ->
            {not_all_unique, Char, P1, P2}
    end.

all_unique_examples() ->
    lists:foreach(fun (Str) ->
                          io:format("String \"~ts\" (length ~p): ",
                                    [Str, length(Str)]),
                          case all_unique(Str) of
                              all_unique ->
                                  io:format("All characters unique.~n");
                              {not_all_unique, Char, P1, P2} ->
                                  io:format("First duplicate is '~tc' (0x~.16b)"
                                            " at positions ~p and ~p.~n",
                                            [Char, Char, P1, P2])
                          end
                  end,
                  ["", ".", "abcABC", "XYZ ZYX",
                   "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]).


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"))
  }

}


func analyze_string(str) {
    var chars = str.chars
    chars.range.to_a.each_cons(2, {|a,b|
        chars[a] == chars[b] || return b
    })
    return str.len
}

var strings = ["", "   ", "2", "333", ".55", "tttTTT", "4444   444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]

strings.each {|str|
    print "'#{str}' (size #{str.len}): "
    var idx = analyze_string(str)

    if (idx == str.len) {
        say "all the same."
    }
    else {
        say "first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}."
    }
}


// Determine if a string has all unique characters. Nigel Galloway: June 9th., 2020
let fN (n:string)=n.ToCharArray()|>Array.mapi(fun n g->(n,g))|>Array.groupBy(fun (_,n)->n)|>Array.filter(fun(_,n)->n.Length>1)

let allUnique n=match fN n with
                 g when g.Length=0->printfn "All charcters in <<<%s>>> (length %d) are unique" n n.Length
                |g->Array.iter(fun(n,g)->printf "%A is repeated at positions" n; Array.iter(fun(n,_)->printf " %d" n)g;printf " ")g
                    printfn "in <<<%s>>> (length %d)" n n.Length

allUnique ""
allUnique "."
allUnique "abcABC"
allUnique "XYZ ZYX"
allUnique "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"


USING: formatting fry generalizations io kernel math.parser
sequences sets ;

: repeated ( elt seq -- )
    [ dup >hex over ] dip indices first2
    "  '%c' (0x%s) at indices %d and %d.\n" printf ;

: uniqueness-report ( str -- )
    dup dup length "%u — length %d — contains " printf
    [ duplicates ] keep over empty?
    [ 2drop "all unique characters." print ]
    [ "repeated characters:" print '[ _ repeated ] each ] if ;

""
"."
"abcABC"
"XYZ ZYX"
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"
[ uniqueness-report nl ] 5 napply


program demo_verify
implicit none
    call nodup('')
    call nodup('.')
    call nodup('abcABC')
    call nodup('XYZ ZYX')
    call nodup('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')
contains

subroutine nodup(str)
character(len=*),intent(in)  :: str
character(len=*),parameter   :: g='(*(g0))'
character(len=:),allocatable :: ch
integer                      :: where
integer                      :: i
   where=0
   ch=''

   do i=1,len(str)-1
      ch=str(i:i)
      where=index(str(i+1:),ch)
      if(where.ne.0)then
         where=where+i
         exit
      endif
   enddo

   if(where.eq.0)then
     write(*,g)'STR: "',str,'"',new_line('a'),'LEN: ',len(str),'. No duplicate characters found'
   else
     write(*,g)'STR: "',str,'"'
     write(*,'(a,a,t1,a,a)')repeat(' ',where+5),'^',repeat(' ',i+5),'^'
     write(*,g)'LEN: ',len(str), &
     & '. Duplicate chars. First duplicate at positions ',i,' and ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
   endif
   write(*,*)

end subroutine nodup

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex

end program demo_verify


/*
This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c
p_in_str -- input string
*/
WITH
  FUNCTION same_characters_in_string(p_in_str IN varchar2) RETURN varchar2 IS
    v_que varchar2(32767) := p_in_str;
    v_res varchar2(32767);
    v_first varchar2(1);
    v_next  varchar2(1);
BEGIN
  v_first := substr(v_que,1,1);
  IF v_first IS NULL THEN
    v_res := '"" length:0 all characters are the same';
  ELSE
    FOR i IN 2..LENGTH(v_que)
    loop
      v_next := substr(v_que,i,1);
      IF v_first != v_next THEN
        v_res := '"'||v_que||'" length:'||LENGTH(v_que)||', first different character "'||v_next||'"(0x'||rawtohex(utl_raw.cast_to_raw(v_next))||') at position:'|| i;
        exit;
      END IF;
   END loop;
   v_res := nvl(v_res,'"'||v_que||'" length:'||LENGTH(v_que)||' all characters are the same');
  END IF;
  RETURN v_res;
END;

--Test
SELECT same_characters_in_string('') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('   ') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('2') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('333') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('.55') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('tttTTT') AS res FROM dual
UNION ALL
SELECT same_characters_in_string('4444 444k') AS res FROM dual
;


datatype result=allSame | difference of string*char*int ;
val chkstring =  fn input =>
let
val rec chk =  fn ([],n)     => allSame
               |  ([x],n)    => allSame
	       |  (x::y::t,n)=> if x=y then chk (y::t,n+1)
	                                else difference (Int.fmt StringCvt.HEX(Char.ord(y)),y,n)
in
(  input,  String.size input ,   chk ( String.explode  input,2 )  )
end;


Sub CaracteresUnicos (cad As String)
    Dim As Integer lngt = Len(cad)
    Print "Cadena = """; cad; """, longitud = "; lngt
    For i As Integer = 1 To lngt
        For j As Integer = i + 1 To lngt
            If Mid(cad,i,1) = Mid(cad,j,1) Then
                Print " Primer duplicado en las posiciones " & i & _
                " y " & j & ", caracter = '" &  Mid(cad,i,1) & _
                "', valor hex = " & Hex(Asc(Mid(cad,i,1)))
                Print
                Exit Sub
            End If
        Next j
    Next i
    Print " Todos los caracteres son unicos." & Chr(10)
End Sub

CaracteresUnicos ("")
CaracteresUnicos (".")
CaracteresUnicos ("abcABC")
CaracteresUnicos ("XYZ ZYX")
CaracteresUnicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
Sleep


package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 0; i < le-1; i++ {
            for j := i + 1; j < le; j++ {
                if chars[j] == chars[i] {
                    fmt.Println("  Not all characters in the string are unique.")
                    fmt.Printf("  %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)
                    return
                }
            }
        }
    }
    fmt.Println("  All characters in the string are unique.\n")
}

func main() {
    strings := []string{
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    }
    for _, s := range strings {
        analyze(s)
    }
}


package require Tcl 8.6 ; # For binary encode

array set yesno {1 Yes 0 No}

set test {
    {}
    {   }
    {2}
    {333}
    {.55}
    {tttTTT}
    {4444 444k}
    {jjjjjjj}
}

# Loop through test strings
foreach str $test {
    set chars [dict create] ; # init dictionary
    set same 1
    set prev {}
    # Loop through characters in string
    for {set i 0} {$i < [string length $str]} {incr i} {
        set c [string index $str $i] ; # get char at index
        if {$prev == {}} {
            set prev $c ; # initialize prev if it doesn't exist
        }
        if {$c != $prev} {
            set same 0
            break ; # Found a different char, break out of the loop
        }
    }

    # Handle Output
    puts [format "Tested: %12s (len: %2d). All Same? %3s. " \
              "'$str'" [string length $str] $yesno($same)]
    if {! $same} {
        puts [format " --> Different character '%s' (hex: 0x%s) appears at index: %s." \
                  $c [binary encode hex $c] $i]
    }
}


Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
    arr = Array("", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "111111112", " 123")
    For i = LBound(arr) To UBound(arr)
        If SameCharacters(arr(i), respons) Then
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " All characters are the same."
        Else
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " is different at position " & respons & ", character = '" & Mid(arr(i), respons, 1) & "', hexa : (0x" & Hex(Asc(Mid(arr(i), respons, 1))) & ")"
        End If
    Next
End Sub
Function SameCharacters(sTxt, resp As Integer, Optional LowerUpper As Boolean = False) As Boolean
Dim A As String, B As String, i As Integer, temp As Integer
    If Len(sTxt) > 1 Then
        If LowerUpper Then
            SameCharacters = UCase(sTxt) = String$(Len(sTxt), UCase(Left$(sTxt, 1)))
        Else
            SameCharacters = sTxt = String$(Len(sTxt), Left$(sTxt, 1))
        End If
        If Not SameCharacters Then resp = InStr(sTxt, Left$(Replace(sTxt, Left$(sTxt, 1), vbNullString), 1))
    Else
        SameCharacters = True
    End If
End Function


class StringUniqueCharacters {
    static void main(String[] args) {
        printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
        printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
        for (String s : ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]) {
            processString(s)
        }
    }

    private static void processString(String input) {
        Map<Character, Integer> charMap = new HashMap<>()
        char dup = 0
        int index = 0
        int pos1 = -1
        int pos2 = -1
        for (char key : input.toCharArray()) {
            index++
            if (charMap.containsKey(key)) {
                dup = key
                pos1 = charMap.get(key)
                pos2 = index
                break
            }
            charMap.put(key, index)
        }
        String unique = (int) dup == 0 ? "yes" : "no"
        String diff = (int) dup == 0 ? "" : "'" + dup + "'"
        String hex = (int) dup == 0 ? "" : Integer.toHexString((int) dup).toUpperCase()
        String position = (int) dup == 0 ? "" : pos1 + " " + pos2
        printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position)
    }
}


Module Module1

    Sub Analyze(s As String)
        Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length)
        If s.Length > 1 Then
            Dim b = s(0)
            For i = 1 To s.Length
                Dim c = s(i - 1)
                If c <> b Then
                    Console.WriteLine("    Not all characters in the string are the same.")
                    Console.WriteLine("    '{0}' (0x{1:X02}) is different at position {2}", c, AscW(c), i - 1)
                    Return
                End If
            Next
        End If
        Console.WriteLine("    All characters in the string are the same.")
    End Sub

    Sub Main()
        Dim strs() = {"", "   ", "2", "333", ".55", "tttTTT", "4444 444k"}
        For Each s In strs
            Analyze(s)
        Next
    End Sub

End Module


fn analyze(s string) {
    chars := s.runes()
    le := chars.len
    println("Analyzing $s which has a length of $le:")
    if le > 1 {
        for i in 1..le{
            if chars[i] != chars[i-1] {
                println("  Not all characters in the string are the same.")
                println("  '${chars[i]}' (0x${chars[i]:x}) is different at position ${i+1}.\n")
                return
            }
        }
    }
    println("  All characters in the string are the same.\n")
}

fn main() {
    strings := [
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄"
	]
    for s in strings {
        analyze(s)
    }
}


import "/fmt" for Conv, Fmt

var analyze = Fn.new { |s|
    var chars = s.codePoints.toList
    var le = chars.count
    System.print("Analyzing %(Fmt.q(s)) which has a length of %(le):")
    if (le > 1) {
        for (i in 1...le) {
            if (chars[i] != chars[i-1]) {
                System.print("  Not all characters in the string are the same.")
                var c = String.fromCodePoint(chars[i])
                var hex = Conv.hex(chars[i])
                System.print("  '%(c)' (0x%(hex)) is different at position %(i+1).\n")
                return
            }
        }
    }
    System.print("  All characters in the string are the same.\n")
}

var strings = [
    "",
    "   ",
    "2",
    "333",
    ".55",
    "tttTTT",
    "4444 444k",
    "pépé",
    "🐶🐶🐺🐶",
    "🎄🎄🎄🎄"
]
for (s in strings) analyze.call(s)


import Data.List (groupBy, intersperse, sort, transpose)
import Data.Char (ord, toUpper)
import Data.Function(on)
import Numeric (showHex)

hexFromChar :: Char -> String
hexFromChar c = map toUpper $ showHex (ord c) ""

string :: String -> String
string xs = ('\"' : xs) <> "\""

char :: Char -> String
char c = ['\'', c, '\'']

size :: String -> String
size = show . length

positions :: (Int, Int) -> String
positions (a, b) = show a <> " " <> show b

forTable :: String -> [String]
forTable xs = string xs : go (allUnique xs)
  where
    go Nothing = [size xs, "yes", "", "", ""]
    go (Just (u, ij)) = [size xs, "no", char u, hexFromChar u, positions ij]

showTable :: Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents =
  unlines $
  hr :
  (if header
     then z : hr : zs
     else intersperse hr zss) <>
  [hr]
  where
    vss = map (map length) contents
    ms = map maximum (transpose vss) :: [Int]
    hr = concatMap (\n -> sep : replicate n hor) ms <> [sep]
    top = replicate (length hr) hor
    bss = map (map (`replicate` ' ') . zipWith (-) ms) vss
    zss@(z:zs) =
      zipWith
        (\us bs -> concat (zipWith (\x y -> (ver : x) <> y) us bs) <> [ver])
        contents
        bss

table xs =
  showTable
    True
    '|'
    '-'
    '+'
    (["string", "length", "all unique", "1st diff", "hex", "positions"] :
     map forTable xs)

allUnique
  :: (Ord b, Ord a, Num b, Enum b)
  => [a] -> Maybe (a, (b, b))
allUnique xs = go . groupBy (on (==) fst) . sort . zip xs $ [0 ..]
  where
    go [] = Nothing
    go ([_]:us) = go us
    go (((u, i):(_, j):_):_) = Just (u, (i, j))

main :: IO ()
main =
  putStrLn $
  table ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]


include xpllib;                 \contains StrLen function

proc    StrSame(S);             \Show if string has same characters
char    S;
int     L, I, J, K;
[L:= StrLen(S);
IntOut(0, L);  Text(0, ":       ^"");  Text(0, S);  ChOut(0, ^");  CrLf(0);
for I:= 0 to L-1 do
    for J:= I+1 to L-1 do
        [if S(I) # S(J) then
                [ChOut(0, \tab\ 9);
                for K:= 0 to J do ChOut(0, ^ );
                Text(0, "^^ Not same character: ");
                ChOut(0, S(J));
                Text(0, ", hex ");
                SetHexDigits(2);
                HexOut(0, S(J));
                CrLf(0);
                return;
                ];
        ];
Text(0, "       All same character");  CrLf(0);
];

[Text(0, "Length");  CrLf(0);
StrSame("");
StrSame("   ");
StrSame("2");
StrSame("333");
StrSame(".55");
StrSame("tttTTT");
StrSame("4444 444k");
]


fcn stringSameness(str){  // Does not handle Unicode
   sz,unique,uz := str.len(), str.unique(), unique.len();
   println("Length %d: \"%s\"".fmt(sz,str));
   if(sz==uz or uz==1) println("\tSame character in all positions");
   else
      println("\tDifferent: ",
        unique[1,*].pump(List,
	   'wrap(c){ "'%s' (0x%x)[%d]".fmt(c,c.toAsc(), str.find(c)+1) })
        .concat(", "));
}


rc_unique=: monad define
 string=. '"' , y , '"'
 self_classification=. = y  NB. deprecated- consumes space proportional to the squared tally of y  (*: # y)
 is_unique=. self_classification =&# y
 if. is_unique do.
  (# y) ; string ; 'unique'
 else.
  duplicate_masks=. (#~ (1 < +/"1)) self_classification
  duplicate_characters=. ~. y #~ +./ duplicate_masks
  ASCII_values_of_duplicates=. a. i. duplicate_characters
  markers=. duplicate_masks { ' ^'
  A=. (# y) ; string , ' ' ,. markers
  B=. 'duplicate' , ASCII_values_of_duplicates ('<' , (#~ 31&<)~ , '> ASCII ' , ":@:[)"0 duplicate_characters
  A , < B
 end.
)


import java.util.HashMap;
import java.util.Map;

//  Title:  Determine if a string has all unique characters

public class StringUniqueCharacters {

    public static void main(String[] args) {
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions");
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------");
        for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) {
            processString(s);
        }
    }

    private static void processString(String input) {
        Map<Character,Integer> charMap = new HashMap<>();
        char dup = 0;
        int index = 0;
        int pos1 = -1;
        int pos2 = -1;
        for ( char key : input.toCharArray() ) {
            index++;
            if ( charMap.containsKey(key) ) {
                dup = key;
                pos1 = charMap.get(key);
                pos2 = index;
                break;
            }
            charMap.put(key, index);
        }
        String unique = dup == 0 ? "yes" : "no";
        String diff = dup == 0 ? "" : "'" + dup + "'";
        String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase();
        String position = dup == 0 ? "" : pos1 + " " + pos2;
        System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position);
    }

}


(() => {
    'use strict';

    // duplicatedCharIndices :: String -> Maybe (Char, [Int])
    const duplicatedCharIndices = s => {
        const
            duplicates = filter(g => 1 < g.length)(
                groupBy(on(eq)(snd))(
                    sortOn(snd)(
                        zip(enumFrom(0))(chars(s))
                    )
                )
            );
        return 0 < duplicates.length ? Just(
            fanArrow(compose(snd, fst))(map(fst))(
                sortOn(compose(fst, fst))(
                    duplicates
                )[0]
            )
        ) : Nothing();
    };

    // ------------------------TEST------------------------
    const main = () =>
        console.log(
            fTable('First duplicated character, if any:')(
                s => `'${s}' (${s.length})`
            )(maybe('None')(tpl => {
                const [c, ixs] = Array.from(tpl);
                return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`
            }))(duplicatedCharIndices)([
                "", ".", "abcABC", "XYZ ZYX",
                "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"
            ])
        );

    // -----------------GENERIC FUNCTIONS------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // chars :: String -> [Char]
    const chars = s => s.split('');

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        x => fs.reduceRight((a, f) => f(a), x);

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // eq (==) :: Eq a => a -> a -> Bool
    const eq = a => b => a === b;

    // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))
    const fanArrow = f =>
        // Compose a function from a simple value to a tuple of
        // the separate outputs of two different functions.
        g => x => Tuple(f(x))(g(x));

    // filter :: (a -> Bool) -> [a] -> [a]
    const filter = f => xs => xs.filter(f);

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // fTable :: String -> (a -> String) -> (b -> String)
    //                      -> (a -> b) -> [a] -> String
    const fTable = s => xShow => fxShow => f => xs => {
        // Heading -> x display function ->
        //           fx display function ->
        //    f -> values -> tabular string
        const
            ys = xs.map(xShow),
            w = Math.max(...ys.map(length));
        return s + '\n' + zipWith(
            a => b => a.padStart(w, ' ') + ' -> ' + b
        )(ys)(
            xs.map(x => fxShow(f(x)))
        ).join('\n');
    };

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    const groupBy = fEq =>
        // Typical usage: groupBy(on(eq)(f), xs)
        xs => 0 < xs.length ? (() => {
            const
                tpl = xs.slice(1).reduce(
                    (gw, x) => {
                        const
                            gps = gw[0],
                            wkg = gw[1];
                        return fEq(wkg[0])(x) ? (
                            Tuple(gps)(wkg.concat([x]))
                        ) : Tuple(gps.concat([wkg]))([x]);
                    },
                    Tuple([])([xs[0]])
                );
            return tpl[0].concat([tpl[1]])
        })() : [];

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite length.
        // This enables zip and zipWith to choose the shorter
        // argument when one is non-finite, like cycle, repeat etc
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // map :: (a -> b) -> [a] -> [b]
    const map = f => xs =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // maybe :: b -> (a -> b) -> Maybe a -> b
    const maybe = v =>
        // Default value (v) if m is Nothing, or f(m.Just)
        f => m => m.Nothing ? v : f(m.Just);

    // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
    const on = f =>
        g => a => b => f(g(a))(g(b));

    // ord :: Char -> Int
    const ord = c => c.codePointAt(0);

    // showHex :: Int -> String
    const showHex = n =>
        n.toString(16);

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // sortOn :: Ord b => (a -> b) -> [a] -> [a]
    const sortOn = f =>
        // Equivalent to sortBy(comparing(f)), but with f(x)
        // evaluated only once for each x in xs.
        // ('Schwartzian' decorate-sort-undecorate).
        xs => xs.map(
            x => [f(x), x]
        ).sort(
            (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0)
        ).map(x => x[1]);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // uncurry :: (a -> b -> c) -> ((a, b) -> c)
    const uncurry = f =>
        (x, y) => f(x)(y)

    // zip :: [a] -> [b] -> [(a, b)]
    const zip = xs => ys => {
        const
            lng = Math.min(length(xs), length(ys)),
            vs = take(lng)(ys);
        return take(lng)(xs)
            .map((x, i) => Tuple(x)(vs[i]));
    };

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        xs => ys => {
            const
                lng = Math.min(length(xs), length(ys)),
                vs = take(lng)(ys);
            return take(lng)(xs)
                .map((x, i) => f(x)(vs[i]));
        };

    // MAIN ---
    return main();
})();


# Emit null if there is no duplicate, else [c, [ix1, ix2]]
def firstDuplicate:
  label $out
  | foreach explode[] as $i ({ix: -1};
    .ix += 1
    | .ix as $ix
    | .iu = ([$i] | implode)
    | .[.iu] += [ $ix] ;
    if .[.iu]|length == 2 then [.iu, .[.iu]], break $out else empty end )
    // null ;


arr(s) = [c for c in s]
alldup(a) = filter(x -> length(x) > 1, [findall(x -> x == a[i], a) for i in 1:length(a)])
firstduplicate(s) = (a = arr(s); d = alldup(a); isempty(d) ? nothing : first(d))

function testfunction(strings)
    println("String                            | Length | All Unique | First Duplicate | Positions\n" *
            "-------------------------------------------------------------------------------------")
    for s in strings
        n = firstduplicate(s)
        a = arr(s)
        println(rpad(s, 38), rpad(length(s), 11), n == nothing ? "yes" :
                rpad("no               $(a[n[1]])", 26) * rpad(n[1], 4) * "$(n[2])")
    end
end

testfunction([
"",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
 "hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡",
])


import java.util.HashMap

fun main() {
    System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
    System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
    for (s in arrayOf("", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")) {
        processString(s)
    }
}

private fun processString(input: String) {
    val charMap: MutableMap<Char, Int?> = HashMap()
    var dup = 0.toChar()
    var index = 0
    var pos1 = -1
    var pos2 = -1
    for (key in input.toCharArray()) {
        index++
        if (charMap.containsKey(key)) {
            dup = key
            pos1 = charMap[key]!!
            pos2 = index
            break
        }
        charMap[key] = index
    }
    val unique = if (dup.toInt() == 0) "yes" else "no"
    val diff = if (dup.toInt() == 0) "" else "'$dup'"
    val hex = if (dup.toInt() == 0) "" else Integer.toHexString(dup.toInt()).toUpperCase()
    val position = if (dup.toInt() == 0) "" else "$pos1 $pos2"
    System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length, unique, diff, hex, position)
}


local find, format = string.find, string.format
local function printf(fmt, ...) print(format(fmt,...)) end

local pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'

function report_dup_char(subject)
    local pos1, pos2, char = find(subject, pattern)

    local prefix = format('"%s" (%d)', subject, #subject)
    if pos1 then
        local byte = char:byte()
        printf("%s: '%s' (0x%02x) duplicates at %d, %d", prefix, char, byte, pos1, pos2)
    else
        printf("%s: no duplicates", prefix)
    end
end

local show = report_dup_char
show('coccyx')
show('')
show('.')
show('abcABC')
show('XYZ ZYX')
show('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')


CheckUnique:=proc(s)
	local i, index;
	printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
	for i from 1 to StringTools:-Length(s) do
		index := StringTools:-SearchAll(s[i], s);
		if (numelems([index]) > 1) then
			printf("The given string has duplicated characters.\n");
			printf("The first duplicated character is %a (0x%x) which appears at index %a.\n\n",
				  s[i], convert(s[i], 'bytes')[1], {index});
			return;
		end if;
	end do;
	# if no repeated found
	printf("The given string has all unique characters.\n\n");
end proc:

# Test
CheckUnique("");
CheckUnique(".");
CheckUnique("abcABC");
CheckUnique("XYZ ZYX");
CheckUnique("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");


report zdiv_zero
data x type i.
try.
  x = 1 / 0.
catch CX_SY_ZERODIVIDE.
  write 'Divide by zero.'.
endtry.


-- Divide By Zero Detection

with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Divide_By_Zero is
   Fnum : Float := 1.0;
   Fdenom : Float := 0.0;
   Fresult : Float;
   Inum : Integer := 1;
   Idenom : Integer := 0;
   Iresult : Integer;
begin
   begin
      Put("Integer divide by zero: ");
      Iresult := Inum / Idenom;
      Put(Item => Iresult);
   exception
      when Constraint_Error =>
         Put("Division by zero detected.");
   end;
   New_Line;
   Put("Floating point divide by zero: ");
   Fresult := Fnum / Fdenom;
   if Fresult > Float'Last or Fresult < Float'First then
      Put("Division by zero detected (infinite value).");
   else
      Put(Item => Fresult, Aft => 9, Exp => 0);
   end if;
   New_Line;
end Divide_By_Zero;


ClearAll[UniqueCharacters]
UniqueCharacters[s_String] := Module[{c, len, good = True},
  c = Characters[s];
  len = Length[c];
  Print[s, " with length ", len];
  Do[
   If[c[[i]] == c[[j]],
    Print["Character ", c[[i]], " is repeated at positions ", i,
     " and ", j];
    good = False
    ]
   ,
   {i, len - 1},
   {j, i + 1, len}
   ];
  If[good,
   Print["No repeats"];
   True
   ,
   False
   ]
  ]
UniqueCharacters[""]
UniqueCharacters["."]
UniqueCharacters["abcABC"]
UniqueCharacters["XYZ ZYX"]
UniqueCharacters["1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]


def analyze(s)
        s = str(s)
        println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"

        if len(s) < 2
                println "\tAll characters in the string are unique."
                return
        end

        seen = list()
        for i in range(0, len(s) - 2)
                if s[i] in seen
                        println "\tNot all characters in the string are unique."
                        println "\t'" + s[i] + "' " + format("(0x%x)", ord(s[i])) +\
                                " is duplicated at positions " + str(i + 1) + " and " +\
                                str(s.indexOf(s[i]) + 1)
                        return
                end
                seen.append(s[i])
        end

        println "\tAll characters in the string are unique."
end

tests = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}
for s in tests
        analyze(s)
end


import unicode, strformat

proc checkUniqueChars(s: string) =

  echo fmt"Checking string ""{s}"":"
  let runes = s.toRunes
  for i in 0..<runes.high:
    let rune = runes[i]
    for j in (i+1)..runes.high:
      if runes[j] == rune:
        echo "The string contains duplicate characters."
        echo fmt"Character {rune} ({int(rune):x}) is present at positions {i+1} and {j+1}."
        echo ""
        return
  echo "All characters in the string are unique."
  echo ""

const Strings = ["",
                 ".",
                 "abcABC",
                 "XYZ ZYX",
                 "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
                 "hétérogénéité",
                 "🎆🎃🎇🎈",
                 "😍😀🙌💃😍🙌",
                 "🐠🐟🐡🦈🐬🐳🐋🐡"]

for s in Strings:
  s.checkUniqueChars()


use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
use List::AllUtils qw(uniq);
use Unicode::UCD 'charinfo';

for my $str (
    '',
    '.',
    'abcABC',
    'XYZ ZYX',
    '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ',
    '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X',
    'Δ👍👨👍Δ',
    'ΔδΔ̂ΔΛ',
) {
    my @S;
    push @S, $1 while $str =~ /(\X)/g;
    printf qq{\n"$str" (length: %d) has }, scalar @S;
    if (@S != uniq @S ) {
        say "duplicated characters:";
        my %P;
        push @{ $P{$S[$_]} }, 1+$_ for 0..$#S;
        for my $k (sort keys %P) {
            next unless @{$P{$k}} > 1;
            printf "'%s' %s (0x%x) in positions: %s\n", $k, charinfo(ord $k)->{'name'}, ord($k), join ', ', @{$P{$k}};
        }
    } else {
        say "no duplicated characters."
    }
}


integer
divide(integer n, integer d)
{
    return n / d;
}

integer
can_divide(integer n, integer d)
{
    return !trap(divide, n, d);
}

integer
main(void)
{
    if (!can_divide(9, 0)) {
        o_text("Division by zero.\n");
    }

    return 0;
}


PROC raise exception= ([]STRING args)VOID: (
  put(stand error, ("Exception: ",args, newline));
  stop
);

PROC raise zero division error := VOID:
  raise exception("integer division or modulo by zero");

PROC int div  = (INT a,b)REAL: a/b;
PROC int over = (INT a,b)INT:  a%b;
PROC int mod  = (INT a,b)INT: a%*b;

BEGIN
  OP /  = (INT a,b)REAL: ( b = 0 | raise zero division error; SKIP | int div (a,b) );
  OP %  = (INT a,b)INT:  ( b = 0 | raise zero division error; SKIP | int over(a,b) );
  OP %* = (INT a,b)INT:  ( b = 0 | raise zero division error; SKIP | int mod (a,b) );

  PROC a different handler = VOID: (
      put(stand error,("caught division by zero",new line));
      stop
  );

  INT x:=1, y:=0;
  raise zero division error := a different handler;
  print(x/y)
END


procedure all_uniq(sequence s)
    string chars = ""
    sequence posns = {},
             multi = {}
    integer lm = 0
    for i=1 to length(s) do
        integer si = s[i],
                k = find(si,chars)
        if k=0 then
            chars &= si
            posns &= {{i}}
        else
            posns[k] &= i
            if length(posns[k])=2 then
                multi &= k
                lm += 1
            end if
        end if
    end for
    string msg = sprintf("\"%s\" (length %d): ",{s,length(s)}),
           nod = ordinal(lm,true),
           ess = "s"[1..lm>1],
           res = iff(lm=0?"all characters are unique"
                         :sprintf("contains %s duplicate%s:",{nod,ess}))
    printf(1,"%s %s\n",{msg,res})
    res = repeat(' ',length(msg))
    for i=1 to length(multi) do
        integer mi = multi[i],
                ci = chars[mi]
        printf(1,"%s '%c'(#%02x) at %V\n",{res,ci,ci,posns[mi]})
    end for
    printf(1,"\n")
end procedure

constant tests = {"",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
                  "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
                  "   ","2","333","55","tttTTT","tTTTtt","4444 444k"}
papply(tests,all_uniq)


begin
    % integer division procedure                                                 %
    %     sets c to a divided by b, returns true if the division was OK,         %
    %                                      false if there was division by zero   %
    logical procedure divideI ( integer value a, b; integer result c ) ;
    begin
        % set exception handling to allow integer division by zero to occur once %
        INTDIVZERO := EXCEPTION( false, 1, 0, false, "INTDIVZERO" );
        c := a div b;
        not XCPNOTED(INTDIVZERO)
    end divideI ;
    % real division procedure                                                    %
    %     sets c to a divided by b, returns true if the division was OK,         %
    %                                      false if there was division by zero   %
    logical procedure divideR ( long real value a, b; long real result c ) ;
    begin
        % set exception handling to allow realdivision by zero to occur once     %
        DIVZERO := EXCEPTION( false, 1, 0, false, "DIVZERO" );
        c := a / b;
        not XCPNOTED(DIVZERO)
    end divideR ;
    integer c;
    real    d;
    write( divideI( 4, 2, c ) ); % prints false as no exception                  %
    write( divideI( 5, 0, c ) ); % prints true as division by zero was detected  %
    write( divideR( 4, 2, d ) ); % prints false as no exception                  %
    write( divideR( 5, 0, d ) )  % prints true as division by zero was detected  %
end.


try? -> 3/0
else -> print "division by zero"


ZeroDiv(num1, num2) {
  If ((num1/num2) != "")
    MsgBox % num1/num2
  Else
    MsgBox, 48, Warning, The result is not valid (Divide By Zero).
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert


(de burn (Lst)
   (let P 0
      (by
         '((A)
            (set A (inc 'P))
            (put A 'P (char A)) )
         group
         Lst ) ) )
(de first (Lst)
   (mini
      '((L)
         (nand
            (cdr L)
            (apply min (mapcar val L)) ) )
      Lst ) )
(de uniq? (Str)
   (let M (first (burn (chop Str)))
      (ifn M
         (prinl Str " (length " (length Str) "): all characters are unique")
         (prin
            Str " (length " (length Str) "): first duplicate character "
            (car M)
            " at positions " )
         (println (mapcar val M)) ) ) )
(uniq?)
(uniq? ".")
(uniq? "abcABC")
(uniq? "XYZ ZYX")
(uniq? "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")


report_duplicates(S) :-
	duplicates(S, Dups),
	format('For value "~w":~n', S),
	report(Dups),
	nl.

report(Dups) :-
	maplist(only_one_position, Dups),
	format('    All characters are unique~n').

report(Dups) :-
	exclude(only_one_position, Dups, [c(Char,Positions)|_]),
	reverse(Positions, PosInOrder),
	atomic_list_concat(PosInOrder, ', ', PosAsList),
	format('    The character ~w is non unique at ~p~n', [Char, PosAsList]).

only_one_position(c(_,[_])).

duplicates(S, Count) :-
	atom_chars(S, Chars),
	char_count(Chars, 0, [], Count).

char_count([], _, C, C).
char_count([C|T], Index, Counted, Result) :-
	select(c(C,Positions), Counted, MoreCounted),
	succ(Index, Index1),
	char_count(T, Index1, [c(C,[Index|Positions])|MoreCounted], Result).
char_count([C|T], Index, Counted, Result) :-
	\+ member(c(C,_), Counted),
	succ(Index, Index1),
	char_count(T, Index1, [c(C,[Index])|Counted], Result).

test :-	report_duplicates('').
test :-	report_duplicates('.').
test :-	report_duplicates('abcABC').
test :-	report_duplicates('XYZ ZYX').
test :-	report_duplicates('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ').


 100  REM TRY
 110  ONERR  GOTO 200
 120 D =  - 44 / 0
 190  END
 200  REM CATCH
 210 E =  PEEK (222) <  > 133
 220  POKE 216,0: REM ONERR OFF
 230  IF E THEN  RESUME
 240  CALL  - 3288: REM RECOVER
 250  PRINT "DIVISION BY ZERO"


@echo off
set /a dummy=5/0 2>nul

if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0


Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷

•Show 5 Div 0
•Show 5 Div 5
•Show 0 Div 0


#include <limits.h>	/* INT_MIN */
#include <setjmp.h>	/* siglongjmp(), sigsetjmp() */
#include <stdio.h>	/* perror(), printf() */
#include <stdlib.h>	/* exit() */
#include <signal.h>	/* sigaction(), sigemptyset() */

static sigjmp_buf fpe_env;

/*
 * This SIGFPE handler jumps to fpe_env.
 *
 * A SIGFPE handler must not return, because the program might retry
 * the division, which might cause an infinite loop. The only safe
 * options are to _exit() the program or to siglongjmp() out.
 */
static void
fpe_handler(int signal, siginfo_t *w, void *a)
{
	siglongjmp(fpe_env, w->si_code);
	/* NOTREACHED */
}

/*
 * Try to do x / y, but catch attempts to divide by zero.
 */
void
try_division(int x, int y)
{
	struct sigaction act, old;
	int code;
	/*
	 * The result must be volatile, else C compiler might delay
	 * division until after sigaction() restores old handler.
	 */
	volatile int result;

	/*
	 * Save fpe_env so that fpe_handler() can jump back here.
	 * sigsetjmp() returns zero.
	 */
	code = sigsetjmp(fpe_env, 1);
	if (code == 0) {
		/* Install fpe_handler() to trap SIGFPE. */
		act.sa_sigaction = fpe_handler;
		sigemptyset(&act.sa_mask);
		act.sa_flags = SA_SIGINFO;
		if (sigaction(SIGFPE, &act, &old) < 0) {
			perror("sigaction");
			exit(1);
		}

		/* Do division. */
		result = x / y;

		/*
		 * Restore old hander, so that SIGFPE cannot jump out
		 * of a call to printf(), which might cause trouble.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		printf("%d / %d is %d\n", x, y, result);
	} else {
		/*
		 * We caught SIGFPE. Our fpe_handler() jumped to our
		 * sigsetjmp() and passes a nonzero code.
		 *
		 * But first, restore old handler.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		/* FPE_FLTDIV should never happen with integers. */
		switch (code) {
		case FPE_INTDIV: /* integer division by zero */
		case FPE_FLTDIV: /* float division by zero */
			printf("%d / %d: caught division by zero!\n", x, y);
			break;
		default:
			printf("%d / %d: caught mysterious error!\n", x, y);
			break;
		}
	}
}

/* Try some division. */
int
main()
{
	try_division(-44, 0);
	try_division(-44, 5);
	try_division(0, 5);
	try_division(0, 0);
	try_division(INT_MIN, -1);
	return 0;
}


'''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()


using System;

namespace RosettaCode {
    class Program {
        static void Main(string[] args) {
            int x = 1;
            int y = 0;
            try {
               int z = x / y;
            } catch (DivideByZeroException e) {
                Console.WriteLine(e);
            }

        }
    }
}


#include<iostream>
#include<csignal> /* for signal */
#include<cstdlib>

using namespace std;

void fpe_handler(int signal)
{
    cerr << "Floating Point Exception: division by zero" << endl;
    exit(signal);
}

int main()
{
    // Register floating-point exception handler.
    signal(SIGFPE, fpe_handler);

    int a = 1;
    int b = 0;
    cout << a/b << endl;

    return 0;
}


shared void run() {

	//integers divided by zero throw an exception
	try {
		value a = 1 / 0;
	} catch (Exception e) {
		e.printStackTrace();
	}

	//floats divided by zero produce infinity
	print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!");
}


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"))


(defn safe-/ [x y]
  (try (/ x y)
    (catch ArithmeticException _
      (println "Division by zero caught!")
      (cond (> x 0)   Double/POSITIVE_INFINITY
            (zero? x) Double/NaN
            :else     Double/NEGATIVE_INFINITY) )))


% This will catch a divide-by-zero exception and
% return a oneof instead, with either the result or div_by_zero.
% Overflow and underflow are resignaled.
check_div = proc [T: type] (a, b: T) returns (otype)
            signals (overflow, underflow)
            where T has div: proctype (T,T) returns (T)
                             signals (zero_divide, overflow, underflow)
    otype = oneof[div_by_zero: null, result: T]

    return(otype$make_result(a/b))
    except when zero_divide:
        return(otype$make_div_by_zero(nil))
    end resignal overflow, underflow
end check_div

% Try it
start_up = proc ()
    pair = struct[n, d: int]
    pairs: sequence[pair] := sequence[pair]$[
        pair${n: 10, d: 2},   % OK
        pair${n: 10, d: 0},   % divide by zero
        pair${n: 20, d: 2}    % another OK one to show the program doesn't stop
    ]

    po: stream := stream$primary_output()
    for p: pair in sequence[pair]$elements(pairs) do
        stream$puts(po, int$unparse(p.n) || "/" || int$unparse(p.d) || " = ")
        tagcase check_div[int](p.n, p.d)
            tag div_by_zero: stream$putl(po, "divide by zero")
            tag result (r: int): stream$putl(po, int$unparse(r))
        end
    end
end start_up


DIVIDE foo BY bar GIVING foobar
    ON SIZE ERROR
        DISPLAY "Division by zero detected!"
END-DIVIDE


(handler-case (/ x y)
  (division-by-zero () (format t "division by zero caught!~%")))


#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")))


  -> $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',
    '🦋🙂👨👩👧👦🙄ΔΔ̂ 🦋Δ👍👨👩👧👦'


/*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.  */


import std.stdio, std.string, std.math, std.traits;

string divCheck(T)(in T numer, in T denom)
if (isIntegral!T || isFloatingPoint!T) {
    Unqual!(typeof(numer / denom)) result;
    string msg;

    static if (isIntegral!T) {
        try {
            result = numer / denom;
        } catch(Error e) {
            msg = "| " ~ e.msg ~ " (by Error)";
            result = T.max;
        }
    } else { // Floating Point Type.
        result = numer / denom;
        if (numer.isNormal && result.isInfinity) {
            msg = "| Division by Zero";
        } else if (result != 0 && !result.isNormal) {
            if (numer.isNaN)
                msg = "| NaN numerator";
            else if (denom.isNaN)
                msg = "| NaN denominator";
            else if (numer.isInfinity)
                msg = "| Inf numerator";
            else
                msg = "| NaN (Zero Division by Zero)";
        }
    }

    return format("%5s %s", format("%1.1g", real(result)), msg);
}

void main() {
    writeln("Division with check:");
    writefln("int     1/ 0:   %s", divCheck(1, 0));
    writefln("ubyte   1/ 0:   %s", divCheck(ubyte(1), ubyte(0)));
    writefln("real    1/ 0:   %s", divCheck(1.0L, 0.0L));
    writefln("real   -1/ 0:   %s", divCheck(-1.0L, 0.0L));
    writefln("real    0/ 0:   %s", divCheck(0.0L, 0.0L));
    writeln;
    writefln("real   -4/-2:   %s", divCheck(-4.0L,-2.0L));
    writefln("real    2/-inf: %s", divCheck(2.0L, -real.infinity));
    writeln;
    writefln("real -inf/-2:   %s", divCheck(-real.infinity, -2.0L));
    writefln("real +inf/-2:   %s", divCheck(real.infinity, -2.0L));
    writefln("real  nan/-2:   %s", divCheck(real.nan, -2.0L));
    writefln("real   -2/ nan: %s", divCheck(-2.0L, real.nan));
    writefln("real  nan/ 0:   %s", divCheck(real.nan, 0.0L));
    writefln("real  inf/ inf: %s",
             divCheck(real.infinity, real.infinity));
    writefln("real  nan/ nan: %s", divCheck(real.nan, real.nan));
}


inputStr = ["",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]

for Str in inputStr
    for x = 1 to len(Str)
        for y = x + 1 to len(Str)
            if Str[x] = Str[y]
               char = Str[x]
               ? "Input = " + "'" + Str + "'" + ", length = " + len(Str)
               ? " First duplicate at positions " + x + " and " + y + ", character = " + "'" + char + "'"
               loop 3
            ok
        next
    next
    ? "Input = " + "'" + Str + "'" + ", length = " + len(Str)
    ? " All characters are unique."
next


strings = ["",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",]

strings.each do |str|
  seen = {}
  print "#{str.inspect} (size #{str.size}) "
  res = "has no duplicates." #may change
  str.chars.each_with_index do |c,i|
    if seen[c].nil?
      seen[c] = i
    else
      res =  "has duplicate char #{c} (#{'%#x' % c.ord}) on #{seen[c]} and #{i}."
      break
    end
  end
  puts res
end


fn unique(s: &str) -> Option<(usize, usize, char)> {
    s.chars().enumerate().find_map(|(i, c)| {
        s.chars()
            .enumerate()
            .skip(i + 1)
            .find(|(_, other)| c == *other)
            .map(|(j, _)| (i, j, c))
    })
}

fn main() {
    let strings = [
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    ];

    for string in &strings {
        print!("\"{}\" (length {})", string, string.chars().count());
        match unique(string) {
            None => println!(" is unique"),
            Some((i, j, c)) => println!(
                " is not unique\n\tfirst duplicate: \"{}\" (U+{:0>4X}) at indices {} and {}",
                c, c as usize, i, j
            ),
        }
    }
}


program DivideByZero;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  a, b: Integer;
begin
  a := 1;
  b := 0;
  try
    WriteLn(a / b);
  except
    on e: EZeroDivide do
      Writeln(e.Message);
  end;
end.


divcheck x y:
    true
    try:
        drop / x y
    catch value-error:
        not

if divcheck 1 0:
    !print "Okay"
else:
    !print "Division by zero"


def divide(numerator, denominator) {
    def floatQuotient := numerator / denominator
    if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {
        return ["zero denominator"]
    } else {
        return ["ok", floatQuotient]
    }
}


func index_duplicates(str) {
    gather {
        for k,v in (str.chars.kv) {
            var i = str.index(v, k+1)
            take([k, i]) if (i != -1)
        }
    }
}

var strings = [
    "", ".", "abcABC", "XYZ ZYX",
    "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
    "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
    "hétérogénéité", "🎆🎃🎇🎈", "😍😀🙌💃😍🙌",
    "🐠🐟🐡🦈🐬🐳🐋🐡"
]

strings.each {|str|
    print "\n'#{str}' (size: #{str.len}) "
    var dups = index_duplicates(str)
    say "has duplicated characters:" if dups
    for i,j in (dups) {
        say "#{str[i]} (#{'%#x' % str[i].ord}) in positions: #{i}, #{j}"
    }
    say "has no duplicates." if !dups
}


package require Tcl 8.6 ; # For binary encode

array set yesno {1 Yes 2 No}

set test {
    {}
    {.}
    {abcABC}
    {XYZ ZYX}
    {1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ}
    {hétérogénéité}
}

# Loop through test strings
foreach str $test {
    set chars [dict create] ; # init dictionary
    set num_chars 1 ; # In case of empty string

    # Loop through characters in string
    for {set i 0} {$i < [string length $str]} {incr i} {
        set c [string index $str $i] ; # get char at index
        dict lappend chars $c $i ; # add index to a running list for key=char
        set indexes [dict get $chars $c] ; # get the whole running list
        set num_chars [llength $indexes] ; # count the # of indexes
        if {$num_chars > 1} {
            break ; # Found a duplicate, break out of the loop
        }
    }

    # Handle Output
    puts [format "Tested: %38s (len: %2d). All unique? %3s. " \
              "'$str'" [string length $str] $yesno($num_chars)]
    if {$num_chars > 1} {
        puts [format " --> Character '%s' (hex: 0x%s) reappears at indexes: %s." \
                  $c [binary encode hex $c] $indexes]
    }
}


DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;

#option ('divideByZero', 'zero');
DBZ(10,0); //returns 0.0


class MAIN
    creation main
    feature main is
        local
            x, y: INTEGER;
            retried: BOOLEAN;
        do
            x := 42;
            y := 0;

            if not retried then
                io.put_real(x / y);
            else
                print("NaN%N");
            end
        rescue
            print("Caught division by zero!%N");
            retried := True;
            retry
        end
end


open core number

x /. y = try Some (x `div` y) with
             _ = None

(12 /. 2, 12 /. 0)


defmodule Division do
  def by_zero?(x,y) do
    try do
      _ = x / y
      false
    rescue
      ArithmeticError -> true
    end
  end
end

[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]
|> Enum.each(fn {x,y} ->
  IO.puts "#{x} / #{y}\tdivision by zero  #{Division.by_zero?(x,y)}"
end)


Module Module1

    Sub Main()
        Dim input() = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}
        For Each s In input
            Console.WriteLine($"'{s}' (Length {s.Length}) " + String.Join(", ", s.Select(Function(c, i) (c, i)).GroupBy(Function(t) t.c).Where(Function(g) g.Count() > 1).Select(Function(g) $"'{g.Key}' (0X{AscW(g.Key):X})[{String.Join(", ", g.Select(Function(t) t.i))}]").DefaultIfEmpty("All characters are unique.")))
        Next
    End Sub

End Module


fn analyze(s string) {
    chars := s.runes()
    le := chars.len
    println("Analyzing $s which has a length of $le:")
    if le > 1 {
        for i := 0; i < le-1; i++ {
            for j := i + 1; j < le; j++ {
                if chars[j] == chars[i] {
                    println("  Not all characters in the string are unique.")
                    println("  '${chars[i]}'' (0x${chars[i]:x}) is duplicated at positions ${i+1} and ${j+1}.\n")
                    return
                }
            }
        }
    }
    println("  All characters in the string are unique.\n")
}

fn main() {
    strings := [
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    ]
    for s in strings {
        analyze(s)
    }
}


import "/fmt" for Conv, Fmt

var analyze = Fn.new { |s|
    var chars = s.codePoints.toList
    var le = chars.count
    System.print("Analyzing %(Fmt.q(s)) which has a length of %(le):")
    if (le > 1) {
        for (i in 0...le-1) {
            for (j in i+1...le) {
                if (chars[j] == chars[i]) {
                    System.print("  Not all characters in the string are unique.")
                    var c = String.fromCodePoint(chars[i])
                    var hex = "0x" + Conv.hex(chars[i])
                    System.print("  '%(c)' (%(hex)) is duplicated at positions %(i+1) and %(j+1).\n")
                    return
                }
            }
        }
    }
    System.print("  All characters in the string are unique.\n")
}

var strings = [
    "",
    ".",
    "abcABC",
    "XYZ ZYX",
    "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
    "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
    "hétérogénéité",
    "🎆🎃🎇🎈",
    "😍😀🙌💃😍🙌",
    "🐠🐟🐡🦈🐬🐳🐋🐡"
]
for (s in strings) analyze.call(s)


(condition-case nil
    (/ 1 0)
  (arith-error
   (message "Divide by zero (either integer or float)")))


div_check(X,Y) ->
    case catch X/Y of
        {'EXIT',_} -> true;
        _ -> false
    end.


PROGRAM DIV_BY_ZERO

EXCEPTION
   IF ERR=11 THEN PRINT("Division by Zero") END IF
END EXCEPTION

BEGIN
  PRINT(0/3)
  PRINT(3/0)
END PROGRAM


let detectDivideZero (x : int) (y : int):int option =
    try
        Some(x / y)
    with
        | :? System.ArithmeticException -> None

printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)


include xpllib;                 \contains StrLen function

proc    StrUnique(S);           \Show if string has unique chars
char    S;
int     L, I, J, K;
[L:= StrLen(S);
IntOut(0, L);  Text(0, ":       ^"");  Text(0, S);  ChOut(0, ^");  CrLf(0);
for I:= 0 to L-1 do
    for J:= I+1 to L-1 do
        [if S(I) = S(J) then
                [ChOut(0, \tab\ 9);
                for K:= 0 to I do ChOut(0, ^ );
                ChOut(0, ^^);
                for K:= 0 to J-I-2 do ChOut(0, ^ );
                ChOut(0, ^^);
                Text(0, " Duplicate character: ");
                ChOut(0, S(I));
                Text(0, ", hex ");
                SetHexDigits(2);
                HexOut(0, S(I));
                CrLf(0);
                return;
                ];
        ];
Text(0, "       Unique, no duplicates");  CrLf(0);
];

[Text(0, "Length");  CrLf(0);
StrUnique("");
StrUnique(".");
StrUnique("abcABC");
StrUnique("XYZ ZYX");
StrUnique("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
StrUnique("thequickbrownfoxjumps");
]


sub caracteresunicos (cad$)
    local lngt
	lngt = len(cad$)
    print "cadena = \"", cad$, "\", longitud = ", lngt
    for i = 1 to lngt
        for j = i + 1 to lngt
            if mid$(cad$,i,1) = mid$(cad$,j,1) then
                print " Primer duplicado en las posiciones ", i, " y ", j, ", caracter = \'",  mid$(cad$,i,1), "\', valor hex = ", hex$(asc(mid$(cad$,i,1)))
                print
                return
            end if
        next j
    next i
    print " Todos los caracteres son unicos.\n"
end sub

caracteresunicos ("")
caracteresunicos (".")
caracteresunicos ("abcABC")
caracteresunicos ("XYZ ZYX")
caracteresunicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")


fcn stringUniqueness(str){  // Does not handle Unicode
   sz,unique,uz,counts := str.len(), str.unique(), unique.len(), str.counts();
   println("Length %d: \"%s\"".fmt(sz,str));
   if(sz==uz or uz==1) println("\tAll characters are unique");
   else  // counts is (char,count, char,count, ...)
      println("\tDuplicate: ",
         counts.pump(List,Void.Read,fcn(str,c,n){
            if(n>1){
	       is,z:=List(),-1; do(n){ is.append(z=str.find(c,z+1)) }
	       "'%s' (0x%x)[%s]".fmt(c,c.toAsc(),is.concat(","))
	    }
	    else Void.Skip
	 }.fp(str)).concat(", "));
}


USE: math.floats.env

: try-div ( a b -- )
    '[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;


def divide: x by: y {
  try {
    x / y
  } catch DivisionByZeroError => e {
    e message println # prints error message
  }
}


: safe-/ ( x y -- x/y )
  ['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;


program  rosetta_divbyzero
   implicit none
   integer, parameter :: rdp = kind(1.d0)
   real(rdp) :: normal,zero

   normal = 1.d0
   zero = 0.d0

   call div_by_zero_check(normal,zero)

 contains

   subroutine  div_by_zero_check(x,y)
      use, intrinsic  :: ieee_exceptions
      use, intrinsic  :: ieee_arithmetic
      implicit none
      real(rdp), intent(in) :: x,y

      real(rdp) :: check
      type(ieee_status_type) :: status_value
      logical :: flag
      flag = .false.
      ! Get the flags
      call ieee_get_status(status_value)
      ! Set the flags quiet
      call ieee_set_flag(ieee_divide_by_zero,.false.)
      write(*,*)"Inf supported? ",ieee_support_inf(check)

      ! Calculation involving exception handling
      check = x/y
      write(*,*)"Is check finite?",ieee_is_finite(check), check

      call ieee_get_flag(ieee_divide_by_zero, flag)
      if (flag) write(*,*)"Warning!  Division by zero detected"

      ! Restore the flags
      call ieee_set_status(status_value)

   end subroutine div_by_zero_check

end program rosetta_divbyzero


' FB 1.05.0 Win64

Const divByZeroResult As Integer = -9223372036854775808

Sub CheckForDivByZero(result As Integer)
  If result = divByZeroResult Then
    Print "Division by Zero"
  Else
    Print "Division by Non-Zero"
  End If
End Sub

Dim As Integer x, y

x = 0 : y = 0
CheckForDivByZero(x/y) ' automatic conversion to type of parameter which is Integer
x = 1
CheckForDivByZero(x/y)
x = -1
CheckForDivByZero(x/y)
y = 1
CheckForDivByZero(x/y)
Print
Print "Press any key to exit"
Sleep


include "ConsoleWindow"

on error stop
dim as long a
print a / 0


Public Sub Main()

Try Print 1 / 0
If Error Then Print Error.Text

End


package main

import "fmt"

func divCheck(x, y int) (q int, ok bool) {
    defer func() {
        recover()
    }()
    q = x / y
    return q, true
}

func main() {
    fmt.Println(divCheck(3, 2))
    fmt.Println(divCheck(3, 0))
}


def dividesByZero = { double n, double d ->
    assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'
    (n/d).infinite || (n/d).naN
}


import qualified Control.Exception as C
check x y = C.catch (x `div` y `seq` return False)
                    (\_ -> return True)


let a 1
let b 0
if tostr (a / (b + 0.)) = "inf"
  println "Divide by Zero"
else
  println a / b
endif


FUNCTION zero_divide(num, denom)
    XEQ( num// "/" // denom,  *99) ! on error jump to label 99
    zero_divide = 0                ! division OK
    RETURN

 99 zero_divide = 1
END


try {
  Print("%d\n", 10 / 0);
} catch {
  Print("Divide by zero");
}


//Division by zero is defined in 'i' so the result can be checked to determine division by zero.
concept IsDivisionByZero(a, b) {
	c = a/b
	if c = 0 and a - 0 or a = 0 and c > 0
		print( a, "/", b, " is a division by zero.")
		return
	end
	print( a, "/", b, " is not division by zero.")
}

software {
	IsDivisionByZero(5, 0)
	IsDivisionByZero(5, 2)
	IsDivisionByZero(0, 0)
}


procedure main()
&error := 1
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure")
end


if not finite( <i>expression</i> ) then ...


public static boolean infinity(double numer, double denom){
	return Double.isInfinite(numer/denom);
}


function divByZero(dividend,divisor)
{
	var quotient=dividend/divisor;
        if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity
        return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,0));


def div(x;y): if y==0 then error("NaN") else x/y end;


if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");


isdefinite(n::Number) = !isnan(n) && !isinf(n)

for n in (1, 1//1, 1.0, 1im, 0)
    d = n / 0
    println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).")
end


// version 1.1

fun divideByZero(x: Int, y:Int): Boolean =
    try {
        x / y
        false
    } catch(e: ArithmeticException) {
        true
    }

fun main(args: Array<String>) {
    val x = 1
    val y = 0
    if (divideByZero(x, y)) {
        println("Attempted to divide by zero")
    } else {
        @Suppress("DIVISION_BY_ZERO")
        println("$x / $y = ${x / y}")
    }
}


{def DivByZero?
 {lambda {:w}
  {W.equal? :w Infinity}}}

{DivByZero? {/ 3 2}}
-> false
{DivByZero? {/ 3 0}}
-> true


define dividehandler(a,b) => {
	(
		#a->isNotA(::integer) && #a->isNotA(::decimal) ||
		#b->isNotA(::integer) && #b->isNotA(::decimal)
	) ? return 'Error: Please supply all params as integers or decimals'
	protect => {
		handle_error => { return 'Error: Divide by zero' }
		local(x = #a / #b)
		return #x
	}
}

dividehandler(1,0)


on div (a, b)
  -- for simplicity type check of vars omitted
  res = value("float(a)/b")
  if voidP(res) then
    _player.alert("Division by zero!")
  else
    return res
  end if
end


local function div(a,b)
  if b == 0 then error() end
  return a/b
end


ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')


Check[2/0, Print["division by 0"], Power::infy]


function [isDividedByZero] = dividebyzero(numerator, denomenator)
   isDividedByZero = isinf( numerator/denomenator );
   % If isDividedByZero equals 1, divide by zero occured.


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


if not bit.isFinite (<i>expression</i>) then...


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
}


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


def div_check(x, y)
	try
		(x / y)
		return false
	catch
		return true
	end
end


/**
 Detect division by zero
*/

var ans = 1.0 / 0.0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")

ans = 1 / 0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")

try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n")


;; Division by zero detection using CAREFULLY
;; The CAREFULLY clause exists in NetLogo since version 2.0
;;   In prior versions of NetLogo, you must examine the divisor prior to performing the division.
;;   The variables result, a, and b must all be previously created global, local, or agent -own'd variables.
;; NetLogo variables are dynamically typed, so we are assuming that a and b contain numbers.
;; (All numbers in NetLogo are double-precision floating-point numbers.)
;;   However, even if not numbers, the result is still the same: the carefully clause will
;; supress the run-time error and run the "commands if error" block, setting result to false.
;; this false value can be detected, to alter the rest of the course of the code
;;   This behavior is consistent with other NetLogo primitives, such as POSTIION, that report
;; FALSE, rather than a number, if the operation fails.
carefully
[ ;; commands to try to run
  set result a / b
]
[ ;; commands to run if an error occurs in the previous block.
  set result false
]
ifelse is-number? result
[ output-print (word a " / " b " = " result)
]
[ output-print (word a " / " b " is not calculable"
]


/* NetRexx */
options replace format comments java crossref symbols nobinary

method divide(dividend, divisor) public constant returns Rexx
  do
    quotient = dividend / divisor
  catch exu = DivideException
    exu.printStackTrace()
    quotient = 'undefined'
  catch exr = RuntimeException
    exr.printStackTrace()
    quotient = 'error'
  end
  return quotient

method main(args = String[]) public static
  -- process input arguments and set sensible defaults
  arg = Rexx(args)
  parse arg dividend .',' divisor .
  if dividend.length() = 0 then dividend = 1
  if divisor.length()  = 0 then divisor  = 0
  say dividend '/' divisor '=' divide(dividend, divisor)
  return


#! /usr/local/bin/newlisp

(define (check-division x y)
    (catch (/ x y) 'check-zero)
    (if (not (integer? check-zero))
        (setq check-zero "Division by zero."))
     check-zero
)

(println (check-division 10 4))
(println (check-division 4 0))
(println (check-division 20 5))
(println (check-division 11 0))

(exit)


{.push overflowChecks: on.}
proc divCheck(x, y): bool =
  try:
    discard x div y
  except DivByZeroDefect:
    return true
  return false
{.pop.} # Restore default check settings

echo divCheck(2, 0)


10 ON ERROR GOTO 40
20 PRINT 1/0
30 END
40 IF ERR = 10 THEN PRINT "DIVISION BY ZERO IN LINE"ERL
50 RESUME 30


let div_check x y =
  try
    ignore (x / y);
    false
  with Division_by_zero ->
    true


d = 5/0;
if ( isinf(d) )
  if ( index(lastwarn(), "division by zero") > 0 )
     error("division by zero")
  endif
endif


: divideCheck(n)
| e |
   try: e [ 128 n / ] when: [ "Zero detected..." . ]
   "Leaving" println ;


(define (safediv a b)
   (if (eq? (type b) type-complex)
      (/ a b) ; complex can't be 0
      (let ((z (/ 1 (inexact b))))
         (unless (or (equal? z +inf.0) (equal? z -inf.0))
            (/ a b)))))

; testing:
(for-each (lambda (x)
      (if x (print x) (print "division by zero detected")))
   (list
      (safediv 1 5)    ; => 1/5
      (safediv 2 0)    ; => division by zero detected
      (safediv 3 1+2i) ; => 3/5-6/5i
      (safediv 4 0+i)  ; => 0-4i
      (safediv 5 7/5)  ; => 25/7
))


/* REXX **************************************************************
* program demonstrates  detects and handles  division by zero.
* translated from REXX:
*   removed fancy error reporting (ooRexx does not support linesize)
*   removed label Novalue (as novalue is not enabled there)
* 28.04.2013 Walter Pachl
*********************************************************************/
Signal on Syntax                   /*handle all REXX syntax errors. */
x = sourceline()                   /*being cute, x=size of this pgm.*/
y = x-x                            /*setting to zero the obtuse way.*/
z = x/y                            /* attempt to divide by 0        */
exit                               /* will not be reached           */

Syntax:
  Say 'Syntax raised in line' sigl
  Say sourceline(sigl)
  Say 'rc='rc '('errortext(rc)')'
  Exit 12


try
   {Show 42 div 0}
catch error(kernel(div0 ...) ...) then
   {System.showInfo "Division by zero detected."}
end


iferr(1/0,
      err,
      print("division by 0"); print("or other non-invertible divisor"),
      errname(err) == "e_INV");


sub div_check
 {local [email protected];
  eval {$_[0] / $_[1]};
  [email protected] and [email protected] =~ /division by zero/;}


try
    integer i = 1/0
catch e
    ?e[E_USER]
end try
puts(1,"still running...\n")


function div_check($x, $y) {
  @trigger_error(''); // a dummy to detect when error didn't occur
  @($x / $y);
  $e = error_get_last();
  return $e['message'] != '';
}


Proc DivideDZ(a,b) Returns(Float Bin(33));
    Dcl (a,b,c) Float Bin(33);
    On ZeroDivide GoTo MyError;
    c=a/b;
    Return(c);
MyError:
    Put Skip List('Divide by Zero Detected!');
End DivideDZ;

xx=DivideDZ(1,0);


FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)
RETURN BOOLEAN
IS
  result NUMBER;
BEGIN
  result := n1/n2;
  RETURN(FALSE);
EXCEPTION
  WHEN ZERO_DIVIDE THEN
    RETURN(TRUE);
END divide;


function div ($a, $b) {
    try{$a/$b}
    catch{"Bad parameters: `$a = $a and `$b = $b"}
}
div 10 2
div 1 0


div(A, B, C, Ex) :-
    catch((C is A/B), Ex, (C = infinity)).


def div_check(x, y):
  try:
    x / y
  except ZeroDivisionError:
    return True
  else:
    return False


r:x%0
?[1=sum r=(0n;0w;-0w);"division by zero detected";()]


d <- 5/0
if ( !is.finite(d) ) {
  # it is Inf, -Inf, or NaN
}


#lang racket

(with-handlers ([exn:fail:contract:divide-by-zero?
                 (λ (e) (displayln "Divided by zero"))])
  (/ 1 0))


sub div($a, $b) {
    my $r;
    try {
        $r = $a / $b;
        CATCH {
            default { note "Unexpected exception, $_" }
        }
    }
    return $r // Nil;
}
say div(10,2);
say div(1, sin(0));


rebol [
    Title: "Detect Divide by Zero"
    URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection
]

; The 'try' word returns an error object if the operation fails for
; whatever reason. The 'error?' word detects an error object and
; 'disarm' keeps it from triggering so I can analyze it to print the
; appropriate message. Otherwise, any reference to the error object
; will stop the program.

div-check: func [
	"Attempt to divide two numbers, report result or errors as needed."
	x y
	/local result
] [
	either error? result: try [x / y][
		result: disarm result
		print ["Caught" result/type "error:" result/id]
	] [
		print [x "/" y "=" result]
	]
]

div-check 12 2       ; An ordinary calculation.
div-check 6 0        ; This will detect divide by zero.
div-check "7" 0.0001 ; Other errors can be caught as well.


/*REXX program  demonstrates  detection  and handling  division by zero.                */
signal on syntax                                 /*handle all REXX syntax errors.       */
x = sourceline()                                 /*being cute, x=is the size of this pgm*/
y = x - x                                        /*setting to zero the obtuse way.      */
z = x / y                                        /*this'll trigger it,  furrrr shurrre. */
exit                                             /*We're kaput.   Ja vohl !             */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err:    if rc==42  then do;  say                 /*first,  check for a specific error.  */
                             say center(' ***error*** ', 79, "═")
                             say 'Division by zero detected at line  '       @ ,
                                 "  and the REXX statement is:"
                             say sourceLine(@)
                             say
                             exit 42
                        end
        say
        say center(' error! ', 79, "*")
                        do #=1  for arg();   say;     say arg(#);       say
                        end   /*#*/
        exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: @=sigl;   call err  'REXX program'   condition("C")   'error',   condition('D'), ,
                            'REXX source statement (line'   sigl"):",    sourceLine(sigl)


Try
   see 9/0
Catch
   see "Catch!" + nl + cCatchError
Done


       dcl-c DIVIDE_BY_ZERO 00102;

       dcl-s result zoned(5:2);
       dcl-s value1 zoned(5:2);
       dcl-s value2 zoned(5:2);

       value1 = 10;
       value2 = 0;

       monitor;
         eval(h) result = value1 / value2; // Using half rounding here for the eval result
       on-error DIVIDE_BY_ZERO;
         // Initialise the result to 0. Consider other messaging perhaps.
         result = 0;
       endmon;

       *inlr = *on;


def div_check(x, y)
  begin
    x / y
  rescue ZeroDivisionError
    true
  else
    false
  end
end


fn test_division(numerator: u32, denominator: u32) {
    match numerator.checked_div(denominator) {
        Some(result) => println!("{} / {} = {}", numerator, denominator, result),
        None => println!("{} / {} results in a division by zero", numerator, denominator)
    }
}

fn main() {
    test_division(5, 4);
    test_division(4, 0);
}


object DivideByZero extends Application {

  def check(x: Int, y: Int): Boolean = {
    try {
      val result = x / y
      println(result)
      return false
    } catch {
      case x: ArithmeticException => {
        return true
      }
    }
  }

  println("divided by zero = " + check(1, 0))

  def check1(x: Int, y: Int): Boolean = {
    import scala.util.Try
    Try(y/x).isFailure
  }
  println("divided by zero = " + check1(1, 0))

}


$ include "seed7_05.s7i";
  include "float.s7i";

const proc: doDivide (in integer: numer, in integer: denom) is func
  begin
    block
      writeln(numer <& " div " <& denom <& " = " <& numer div denom);
    exception
      catch NUMERIC_ERROR:
        writeln("Division by zero detected.");
    end block;
  end func;

const proc: doDivide (in float: numer, in float: denom) is func
  local
    var float: quotient is 0.0;
  begin
    quotient := numer / denom;
    if quotient <> Infinity and quotient <> -Infinity then
      writeln(numer <& " / " <& denom <& " = " <& quotient);
    else
      writeln("Division by zero detected.");
    end if;
  end func;

const proc: main is func
  begin
    doDivide(10, 8);
    doDivide(1, 0);
    doDivide(10.0, 8.0);
    doDivide(1.0, 0.0);
  end func;


func div_check(a, b){
    var result = a/b
    result.abs == Inf ? nil : result
}

say div_check(10, 2)  # 5
say div_check(1, 0)   # nil (detected)


[ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity].


|didDivideByZero a b|

didDivideByZero := false.
a := 10.
b := 0.
[
    a/b
] on: ZeroDivide do:[:ex |
   'you tried to divide %P by zero\n' printf:{ex suspendedContext receiver} on:Transcript.
   didDivideByZero := true.
].
didDivideByZero ifTrue:[
    Transcript show:'bad bad bad, but I already told you in the handler'.
].


        define('zdiv(x,y)') :(zdiv_end)
zdiv    &errlimit = 1; setexit(.ztrap)
        zdiv = x / y :(return)
ztrap   zdiv = ?(&errtype ? (14 | 262)) 'Division by zero' :s(continue)f(abort)
zdiv_end

*       # Test and display
        output = '1/1     = ' zdiv(1,1)      ;* Integers non-zero
        output = '1.0/1.0 = ' zdiv(1.0,1.0)  ;* Reals non-zero
        output = '1/0     = ' zdiv(1,0)      ;* Integers zero
        output = '1.0/0.0 = ' zdiv(1.0,0.0)  ;* Reals zero
        output = 'Zero checks complete'
end


--#SET TERMINATOR @

SET SERVEROUTPUT ON@

CREATE OR REPLACE FUNCTION DIVISION(
  IN NUMERATOR DECIMAL(5, 3),
  IN DENOMINATOR DECIMAL(5, 3)
 ) RETURNS SMALLINT
 BEGIN
  DECLARE RET SMALLINT DEFAULT 1;
  DECLARE TMP DECIMAL(5, 3);
  DECLARE CONTINUE HANDLER FOR SQLSTATE '22012'
    SET RET = 1;

  SET RET = 0;
  SET TMP = NUMERATOR / DENOMINATOR;
  RETURN RET;
 END @

VALUES DIVISION(10, 2)@
VALUES DIVISION(10, 3)@
VALUES DIVISION(10, 0)@


fun div_check (x, y) = (
  ignore (x div y);
  false
) handle Div => true


proc div_check {x y} {
    if {[catch {expr {$x/$y}} result] == 0} {
        puts "valid division: $x/$y=$result"
    } else {
        if {$result eq "divide by zero"} {
            puts "caught division by zero: $x/$y -> $result"
        } else {
            puts "caught another error: $x/$y -> $result"
        }
    }
}

foreach denom {1 0 foo} {
    div_check 42 $denom
}


@(do (defun div-check (x y)
       (catch (/ x y)
         (numeric_error (msg)
           'div-check-failed))))
@(bind good @(div-check 32 8))
@(bind bad @(div-check 42 0))