How to find the second biggest number in a set of random numbers in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

func findSecondMax(total int, rndmax int) *int {
    rand.Seed(time.Now().UnixNano())
    numbers := make([]int, total)

    for i := 0; i < total; i++ {
        n := rand.Intn(rndmax) + 1
        numbers[i] = n
        fmt.Println(n)
    }

    // Remove duplicates
    uniqueMap := make(map[int]bool)
    var uniqueNumbers []int
    for _, num := range numbers {
        if !uniqueMap[num] {
            uniqueMap[num] = true
            uniqueNumbers = append(uniqueNumbers, num)
        }
    }

    sort.Sort(sort.Reverse(sort.IntSlice(uniqueNumbers)))

    if len(uniqueNumbers) > 1 {
        return &uniqueNumbers[1]
    }
    return nil
}

func main() {
    secondMax := findSecondMax(10, 100)
    if secondMax != nil {
        fmt.Printf("The second biggest number is: %d\n", *secondMax)
    } else {
        fmt.Println("Not enough unique numbers to determine a second maximum.")
    }
}



/*
run:

63
56
67
3
29
48
28
96
48
46
The second biggest number is: 67

*/

 



answered Oct 4, 2025 by avibootz
...