How to print unique numbers in array in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to print unique numbers in array using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
// Define an array of integers
arr := []int{2, 3, 3, 5, 5, 5, 7, 7, 7, 7}
// Initialize a map to keep track of unique numbers
unique := map[int]bool{}
// Iterate over each element in the array
for _, num := range arr {
// Check if the number is already in the map
if _, ok := unique[num]; !ok {
// If it's not, add it to the map and print it
unique[num] = true
fmt.Println(num)
}
}
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we define an array of integers and initialize an empty map unique to keep track of unique numbers. We then use a for loop to iterate over each element in the array.
For each element, we check whether it is already in the unique map. If it is not, we add it to the map with a value of true (to indicate that the number is unique), and then print the number.
By using a map to keep track of unique numbers, we ensure that each number is only printed once, even if it appears multiple times in the original array.
#go #goprogramming #golang #golangtutorial #golanguage