How to check whether a non-sequential array is a subset of another non-sequential array in Go

2 Answers

0 votes
package main

import (
    "fmt"
)

func isSubset(arr1 []int, arr2 []int) bool {
    size1 := len(arr1)
    size2 := len(arr2)

    for i := 0; i < size2; i++ {
        found := false
        for j := 0; j < size1; j++ {
            if arr2[i] == arr1[j] {
                found = true
                break
            }
        }
        if !found {
            return false
        }
    }
    
    return true
}

func main() {
    arr1 := []int{5, 1, 8, 12, 40, 7, 9, 100}
    arr2 := []int{8, 40, 9, 1}

    if isSubset(arr1, arr2) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}



/*
run:

yes

*/

 



answered Mar 24, 2025 by avibootz
0 votes
package main

import (
    "fmt"
)

func isSubset(arr1 []int, arr2 []int) bool {
    // Create a map to store elements of arr1
    elements := make(map[int]bool)

    // Populate the map with elements from arr1
    for _, value := range arr1 {
        elements[value] = true
    }

    // Check if all elements of arr2 exist in the map
    for _, value := range arr2 {
        if !elements[value] {
            return false // Element not found, arr2 is not a subset
        }
    }

    return true // All elements found, arr2 is a subset
}

func main() {
    arr1 := []int{5, 1, 8, 12, 40, 7, 9, 100}
    arr2 := []int{8, 40, 9, 1}

    if isSubset(arr1, arr2) {
        fmt.Println("Yes, arr2 is a subset of arr1")
    } else {
        fmt.Println("No, arr2 is not a subset of arr1")
    }
}



/*
run:

Yes, arr2 is a subset of arr1

*/

 



answered Mar 24, 2025 by avibootz
...