Last active
May 31, 2020 23:40
-
-
Save derekkenney/d19db4855558c7be0b247948d33c8f07 to your computer and use it in GitHub Desktop.
Count distinct number of ints from a list of 1 million ints.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"math/rand" | |
"time" | |
) | |
// Find the count of distinct ints in a slice. | |
// Inputs = array of random ints | |
// Output = count of unique int values. | |
// I use a map to store the unique int values. It's more efficient | |
// than a linear lookup of a slice | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
ints := randomArray(10) | |
UniqueInts(ints) | |
} | |
func UniqueInts(ints []int) { | |
// Store the unique int values. Lookups | |
// are performed in constant time. I use a map | |
// instead of an array which would be a linear algorithm | |
unique := make(map[int]struct{}) | |
for _, val := range ints { | |
if _, ok := unique[val]; !ok { | |
// I'm using only the keys of the map to identify | |
// unique int values | |
unique[val] = struct{}{} | |
} | |
} | |
log.Printf("The number of unique ints is %d out of %d ints\n", len(unique), len(ints)) | |
} | |
func randomArray(len int) []int { | |
a := make([]int, len) | |
for i := 0; i <= len-1; i++ { | |
a[i] = rand.Intn(len) | |
} | |
return a | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment