home

unix shell (bash)


#!/bin/bash


#
# find a value in the given list that occurs an odd number of times
#
function findOddCount {
  local srcarray
  declare -a bucket
  srcarray=( `echo "$1"` )

  for i in "${srcarray[@]}"; do
    ((bucket[$i] += 1))
  done

  for i in "${srcarray[@]}"; do
    if (( 1==${bucket[$i]}%2 )); then
      echo $i
      return
    fi
  done
  echo x
}


a1=(1 1 2 2 3 3 4 4 5 5 6 7 7 7 7)
a2=(10 10 7 7 6 6 2 2 3 3 4 4 5 5 6 7 7 7 7 10 10)
a3=(6 6 10 10 7 7 6 6 2 2 3 3 4 4 5 5 6 7 7 7 7 10 10)
a4=(10 10 7 7 2 2 3 3 4 4 5 5 7 7 7 7 10 10 6)
a5=(6 6)
a6=(1)

echo odd value in a1 is `findOddCount "\`echo ${a1[@]}\`"`
echo odd value in a2 is `findOddCount "\`echo ${a2[@]}\`"`
echo odd value in a3 is `findOddCount "\`echo ${a3[@]}\`"`
echo odd value in a4 is `findOddCount "\`echo ${a4[@]}\`"`
echo odd value in a5 is `findOddCount "\`echo ${a5[@]}\`"`
echo odd value in a6 is `findOddCount "\`echo ${a6[@]}\`"`