## Min-Min-Max

### August 12, 2016

My statistics always decline in the summer, but they are starting to pick up, so I guess school must be starting in some places. Here’s a simple homework problem for beginning programmers:

Given an unsorted array of integers, find the smallest number in the array, the largest number in the array, and the smallest number between the two array bounds that is not in the array. For instance, given the array [-1, 4, 5, -23, 24], the smallest number is -23, the largest number is 24, and the smallest number between the array bounds is -22. You may assume the input is well-formed.

Your task is to provide two solutions to the problem, the first a straight forward solution that a beginning programmer might write, and a second solution that is rather more “creative;” feel free to define creative however you wish. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

I think my naive perl queue version is similar to your second solution…

Here’s a solution in Java.

The first solution sorts the array, getting min and max from the ends, and looping over the array to find the smallest number between the two array bounds that is not in the array.

The second solution is not particularly creative. It loops over the array, finding the min and max elements, and creating a hash set of array elements. Then it loops over a range from min to max to find the smallest number between the two array bounds that is not in the array.

Output:

Sorry, should be this:

My last solution was not particularly creative. Here’s a bash script that solves the problem.

In my last post, my code was mistakenly reading in the data already sorted. Here’s the corrected version.

Output:

My two cents in D…

Output:

[-23, -22, 24]

Powershell…

#build array

$array = @(-1, 4, 5, -23, 24)

#sort array

$sarray = $array | sort

#first element of array – smallest

$sarray[0]

#use array count to find last element of array – largest

$sarrayc = $sarray.Count – 1

#last element of array

$sarray[$sarrayc]

#use for loop to count up from smallest number

for($i = $sarray[0];$i -le $sarray[$sarrayc];$i++)

{

#loop over each number is sorted array

foreach($num in $sarray)

{

#if the count equals a number in the array break

if($i -eq $num)

{

break

}

}

#if the counter doesn’t equal a number in the array break

if($i -ne $num)

{

#print the counter #

write-host $i

break

}

}

JAVASCRIPT:

Three solutions in Racket. The straightforward one uses sorting, the creative one uses a hash table like (almost) everybody else, and the other creative one uses a priority queue.