Third Biggest Number
April 13, 2018
Our program reads ten numbers in a loop, stores them in a list, then sorts the list and returns the third largest, with appropriate prompts:
(define (third-biggest-number)
(let loop ((n 10) (xs (list)))
(cond ((positive? n)
(display "Enter a number: ")
(loop (- n 1) (cons (read) xs)))
(else
(display "The third biggest number is ")
(display (caddr (sort > xs))) (newline)))))
> (third-biggest-number) Enter a number: 14 Enter a number: 23 Enter a number: 102 Enter a number: 97 Enter a number: 29 Enter a number: 4 Enter a number: 19 Enter a number: 85 Enter a number: 53 Enter a number: 111 The third biggest number is 97
Here’s another version of the program, written in a more imperative style:
(define (third-biggest-number)
(let ((n 10) (xs (list)))
(while (positive? n)
(display "Enter a number: ")
(set! n (- n 1))
(set! xs (cons (read) xs)))
(display "The third biggest number is ")
(display (caddr (sort > xs))) (newline)))
You can run the program at https://ideone.com/H9Itwr.
Alternate solution keeps track of the three largest values using an array:
#!perl use strict; use warnings; use feature qw(say); my @biggest3 = (0, 0, 0); while(my $n = readline(*DATA)) { chomp $n; foreach my $i (0 .. $#biggest3) { if ($n >= $biggest3[$i]) { my $tmp = $biggest3[$i]; $biggest3[$i] = $n; foreach my $k ($i + 1 .. $#biggest3) { ($biggest3[$k], $tmp) = ($tmp, $biggest3[$k]); } last; } } } say $biggest3[-1]; __DATA__ 14 23 102 97 29 4 19 85 53 111int third_biggest(int arr[], int size){ int third = -1; int second = -1; int biggest = -1; printf("size: %d\n", size); int i = 0; while (size > i){ if (arr[i] > biggest) { third = second; second = biggest; biggest = arr[i]; } else if (arr[i] > second){ third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; i++; printf("third: %d\n", third); } return third; } int main() { int input={100, 7, 50, 1, 2, 3, 4, 5, 6, 40}; int size = sizeof(input) / sizeof(int); printf("third largest %d\n", third_biggest(input, size)); // 40 is the answer return 0; }Mumps solutions
zjsg ; q 3rd ; k arr f i=1:1:10 r !,"Enter number: ",x s arr(x)=1 w !!,"3rd number is ",$o(arr($o(arr($o(arr("")))))) qUSER>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.
-- Given a series of integers on standard input first remove duplicates, then -- print the 3'rd biggest number of those remaining, if it exists. -- -- Why remove duplicates? Consider the list [1, 1, 2, 2, 3, 3]. The third -- biggest number in the list is 1, not 2 (the third element after sorting). import Data.List.Ordered (nubSortOn) import Data.Ord (Down(Down)) -- Just the n'th element of a list (starting at 1) or Nothing if n < 1 or if the -- list has fewer than n elements. nth :: Int -> [a] -> Maybe a nth n xs = if n < 1 then Nothing else go n xs where go _ [] = Nothing go 1 (y:_) = Just y go m (_:ys) = go (m-1) ys -- Just the n'th biggest element of the list after duplicates have been removed, -- or Nothing if there are fewer than n elements left. nthBiggest :: Ord a => Int -> [a] -> Maybe a nthBiggest n = nth n . nubSortOn Down main :: IO () main = do x <- nthBiggest 3 . map read . words <$> getContents print (x :: Maybe Int)Python 3
import random def third_biggest(seq): uniq = sorted(set(seq)) return uniq[-3:-2] if len(uniq) > 2 else None if __name__ == "__main__": data = [random.randint(1, 10**6) for k in range(10)] print (data) print (third_biggest(data))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?
puts "#{10.times.map { print "Enter a number: "; Integer(gets) }.uniq.sort[-3] || 'Nop'}"My previous entry is invalid Ruby. This one does the trick.
puts 10.times.map { print "Enter a number: "; Integer(gets) }.uniq.sort[-3] || 'Nop'(1..10 | % { (Read-Host -Prompt “Enter a number”) -as [int] } | Sort -Unique)[-3]
A translation of my Ruby version in Go.
package main import ( "fmt" "sort" ) func main() { numbers := make([]int, 10) // Get numbers from user for i := range numbers { fmt.Print("Enter a number: ") fmt.Scan(&numbers[i]) } // Remove duplicates uniqNumbers := []int{} m := make(map[int]bool) for _, x := range numbers { m[x] = true } for k, _ := range m { uniqNumbers = append(uniqNumbers, k) } if len(uniqNumbers) < 3 { fmt.Println("Nop") return } // Sort in descending order sort.Sort(sort.Reverse(sort.IntSlice(numbers))) fmt.Println("Third lagest is:", numbers[2]) }A classic interview answer is to use a min-heap of fixed-size:
import java.util.PriorityQueue; import java.util.Scanner; public class ThirdBiggest { public static void main(String[] args) { PriorityQueue<Integer> numbers = new PriorityQueue<>(); System.out.println("Enter 10 numbers:"); Scanner sc = null; try { sc = new Scanner(System.in); for (int i = 0; i < 10; i++) { int num = sc.nextInt(); if (numbers.size() < 3) { numbers.add(num); } else if (num >= numbers.peek()){ numbers.remove(); numbers.add(num); } } } finally { if (sc != null) { sc.close(); } } System.out.println("The third biggest is " + numbers.peek()); } }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.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define N_ENTERED 10 #define N_RETAINED 3 int main(void) { int array[N_RETAINED]; for (size_t i = 0; i < N_ENTERED; ++i) { int x; while (true) { printf("Enter Number %zu: ", i+1); int n_assigned = scanf("%d", &x); size_t n_trailing = 0; while (getchar() != '\n') ++n_trailing; if (n_assigned == 1 && n_trailing == 0) break; } bool reorder = true; if (i < N_RETAINED) { array[i] = x; } else if (x > array[0]) { array[0] = x; } else { reorder = false; } if (reorder) { for (size_t j = 1; j < N_RETAINED; ++j) { if (j > i) break; if (array[j-1] > array[j]) { int tmp = array[j-1]; array[j-1] = array[j]; array[j] = tmp; } } } } printf("Biggest Number %d: %d\n", N_RETAINED, array[0]); return EXIT_SUCCESS; }Example: