Third Biggest Number
April 13, 2018
Today’s exercise is for all the beginning programming students who read this blog:
Write a program to read ten numbers input by the user and write the third largest of those ten numbers.
Your task is to write the program described above. 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.
Alternate solution keeps track of the three largest values using an array:
Mumps solutions
USER>k
USER>d 3rd^zjsg
Enter number: 999999
Enter number: 10000
Enter number: 2345
Enter number: 781
Enter number: 56
Enter number: 1
Enter number: 2
Enter number: 99
Enter number: 678
Enter number: 3456
3rd number is 56
A Haskell version.
Python 3
Sample output:
[76631, 719928, 63284, 348692, 521266, 687164, 663331, 845208, 466387, 33721]
[687164]
Ruby. Assumes clean input of positive integers. This is a trick question right?
My previous entry is invalid Ruby. This one does the trick.
(1..10 | % { (Read-Host -Prompt “Enter a number”) -as [int] } | Sort -Unique)[-3]
A translation of my Ruby version in Go.
A classic interview answer is to use a min-heap of fixed-size:
Kotlin with a recursion approach. Give the first parameter
fun main(args: Array) {
var myList = mutableListOf(1,65,89,45,32,75,11,32,82,11)
println(recThirdBig(myList,null,null,null))
}
tailrec fun recThirdBig(testList: List, oneBig: Int?, twoBig: Int?, threeBig: Int?): Int? {
if (testList.isEmpty()) return threeBig
if (oneBig == null || testList[0] > oneBig) return recThirdBig(testList.drop(1), testList[0], oneBig, twoBig)
if (twoBig == null || testList[0] > twoBig) return recThirdBig(testList.drop(1), oneBig, testList[0], twoBig)
if (threeBig == null || testList[0] > threeBig) return recThirdBig(testList.drop(1), oneBig, twoBig, testList[0])
return recThirdBig(testList.drop(1), oneBig, twoBig, threeBig)
}
This is similar to a prior problem.
Here’s a solution in C.
Example: