aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/bash/ch-2.sh
blob: b708d0b53bca36601b634ded750f6ecf6e484413 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/sh

#
# See ../README.md
#

#
# Run as: bash ch-2.sh < input-file
#

set -f
declare -a digits

while read -a input
do    #
      # Count the digits of the input
      #
      unset digits
      for   ((i = 0; i < ${#input[@]}; i ++))
      do    ((digits[input[i]] ++))
      done

      #
      # Find smallest even number; this will be last number.
      #
      last=-1
      for   ((i = 8; i >= 0; i -= 2))
      do    if    ((digits[i] > 0))
            then  ((last = i))
            fi
      done

      #
      # Skip if the input doesn't contain an even digit
      #
      if    ((last < 0))
      then  continue
      fi

      ((digits[last] --))

      #
      # Create the output
      #
      out=""
      for   ((i = 9; i >= 0; i --))
      do    for   ((j = 0; j < digits[i]; j ++))
            do    out=$out$i
            done
      done

      echo $out$last
done