Go 語言程式檢查一個集合是否為另一個切片的子集


切片類似於陣列,唯一的區別是陣列是元素的固定序列,而切片的陣列元素是動態的。這使得切片在各種應用中更加高效和快速。在切片中,元素是透過引用而不是值傳遞的。在本文中,我們將學習使用 Go 程式語言檢查一個切片的集合是否為另一個切片的子集的各種技術。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)包在程式中,其中 main 生成可執行程式碼,而 fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個子集切片和一個超集切片,其中子集將是較小的集合,超集將是較大的集合。

  • 步驟 3 − 使用 Go 語言中的 print 語句在控制檯上列印子集和超集。

  • 步驟 4 − 呼叫函式 is_subset,並傳遞兩個引數:子集和超集,在其上執行操作。

  • 步驟 5 − 在函式中使用 make 函式建立 checkset 對映,該函式是 Go 語言中的內建函式。

  • 步驟 6 − 執行一個迴圈,直到子集的範圍,並將子集的元素新增到對映中,值為 true。

  • 步驟 7 − 執行另一個迴圈,直到超集的範圍,並檢查超集元素是否在對映中存在,然後從對映中移除該元素。

  • 步驟 8 − 迴圈終止後,返回 checkset 對映的長度,如果長度等於零,則表示該集合是另一個集合的超集。

  • 步驟 9 − 布林值將使用 fmt.Println() 函式列印到控制檯上,其中 ln 表示換行。

示例 1

在這個示例中,我們將看到如何使用對映檢查集合是否為另一個切片的子集,該對映將使用 make 函式構造。

package main
import (
   "fmt"
)
func main() {
   subset := []int{10, 20, 30} //create subset
   fmt.Println("The elements of set are:", subset)
   superset := []int{10, 20, 30, 40, 50} //create superset
   fmt.Println("The elements of superset are:", superset)
   is_Subset := is_Subset(subset, superset)
   fmt.Println("The elements are present in superset or not?")
   fmt.Println(is_Subset)
}
func is_Subset(subset []int, superset []int) bool {
   checkset := make(map[int]bool)
   for _, element := range subset {
      checkset[element] = true
   }
   for _, value := range superset {
      if checkset[value] {
         delete(checkset, value)
      }
   }
   return len(checkset) == 0 //this implies that set is subset of superset
}

輸出

The elements of set are: [10 20 30]
The elements of superset are: [10 20 30 40 50]
The elements are present in superset or not?
true

示例 2

在這個示例中,我們將使用對映和範圍檢查集合是否為另一個切片的子集。我們將為超集和子集執行一個迴圈,輸出將以布林值的形式列印。

package main
import (
   "fmt"
)
func main() {
   subset := []int{10, 20, 30, 40, 50} //create subset
   fmt.Println("The elements in the subset are:", subset)
   superset := []int{10, 20, 30, 40, 50} //create superset
   fmt.Println("The elements in the superset are:", superset)
   is_subset := is_subset(subset, superset)
   fmt.Println("Is the set subset of superset?")
   fmt.Println(is_subset)
}
func is_subset(subset []int, superset []int) bool {
   checkset := make(map[int]bool)
   for _, element := range subset {
      checkset[element] = true
   }
   for _, value := range superset {
      if !checkset[value] {
         return false //return false if set is not subset of superset
      }
   }
   return true //return true if set is subset of superset
}

輸出

The elements in the subset are: [10 20 30 40 50]
The elements in the superset are: [10 20 30 40 50]
Is the set subset of superset?
true

結論

我們執行了使用不同示例集檢查切片是否為超集的子集的程式。在第一個示例中,我們使用了子集長度 = 0 的方法,在第二個示例中,我們使用了對映和範圍方法,輸出結果為真或假。因此,程式執行成功。

更新於: 2023 年 2 月 13 日

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.