📌 Title: Working with Random Numbers, Filtering, Sorting, and Searching in Go

📝 Problem Statement :

In this exercise, you will write a Go program that :

Your program should also handle errors properly and provide clear messages to the user.

🎯 Learning Objectives :

By completing this task, you will learn how to :

🔍 Understanding the Problem :

1️⃣ Generating Random Numbers :

To generate random numbers in Go, we use themath/rand/v2package.

2️⃣ Filtering Even Numbers :

Once we have a list of numbers, we need to extract only the even numbers.

3️⃣ Sorting the Numbers :

Sorting is a common task in programming. Fortunately, Go provides a built-in function for this.

4️⃣ Searching for a Number :

After sorting, we need to check if a specific number (provided by the user) exists in the list. The most efficient way to do this is binary search.

✍️ Functions to Implement :

1️⃣ GenerateRandomSlice(n int) []int :

2️⃣ PrintSlice(label string, slice []int) :

3️⃣ FilterEvenNumbers(slice []int) []int :

4️⃣ SortSlice(slice []int) :

5️⃣ SearchNumber(slice []int, target int) bool :

Create the main() function

Write the main() function and integrate all the previously implemented functions.

Use the commandgo run filename.goto execute the code.

Solution :


package main

import (
	"fmt"
	"math/rand/v2"
	"slices"
	"time"
)

// GenerateRandomSlice creates a slice of 'n' random integers between 1 and 100.
func GenerateRandomSlice(n int) []int {
	if n <= 0 {
		return nil
	}

	seed1 := uint64(time.Now().UnixNano())
	seed2 := uint64(seed1 >> 32) // Generate a second seed value
	rng := rand.NewPCG(seed1, seed2)

	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = int(rng.Uint64()%100 + 1) 
	}

	return slice
}

// PrintSlice displays the contents of an integer slice in a readable format.
func PrintSlice(label string, slice []int) {
	fmt.Print(label, ": ")
	if len(slice) == 0 {
		fmt.Println("Empty slice.")
		return
	}
	for _, num := range slice {
		fmt.Printf("%d ", num)
	}
	fmt.Println()
}

// FilterEvenNumbers returns a new slice containing only even numbers.
func FilterEvenNumbers(slice []int) []int {
	var evenNumbers []int
	for _, num := range slice {
		if num%2 == 0 {
			evenNumbers = append(evenNumbers, num)
		}
	}
	return evenNumbers
}

// SortSlice sorts the given slice in ascending order.
func SortSlice(slice []int) {
	slices.Sort(slice) // Sort in place
}

// SearchNumber checks if a target number exists in a sorted slice using binary search.
func SearchNumber(slice []int, target int) bool {
	_, found := slices.BinarySearch(slice, target)
	return found
}

// Main function to test everything
func main() {
	var n int

	// Ask for the size of the array
	fmt.Print("Enter the size of the array: ")
	_, err := fmt.Scan(&n)
	if err != nil || n <= 0 {
		fmt.Println("Invalid input. Please enter a positive integer.")
		return
	}

	// Generate and display the random slice
	randomNumbers := GenerateRandomSlice(n)
	PrintSlice("Generated slice", randomNumbers)

	// Filter even numbers and display them
	evenNumbers := FilterEvenNumbers(randomNumbers)
	PrintSlice("Even numbers", evenNumbers)

	// Sort and display the slice
	SortSlice(randomNumbers)
	PrintSlice("Sorted slice", randomNumbers)

	// Ask for a number to search
	var target int
	fmt.Print("Enter a number to search: ")
	_, err = fmt.Scan(&target)
	if err != nil {
		fmt.Println("Invalid input. Please enter an integer.")
		return
	}

	// Search the number and display the result
	if SearchNumber(randomNumbers, target) {
		fmt.Println(target, "is in the sorted slice.")
	} else {
		fmt.Println(target, "is not in the sorted slice.")
	}
}

                

🚀 Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! ☕😊

💻 I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! 🙌


☕ Buy me a coffee