Go語言列印反轉雜湊集合的程式


在Go語言中,我們可以使用反向對映方法列印反轉的雜湊集合。雜湊集合中,雜湊對映以鍵值對的形式儲存資料,從而減少了執行時間。在這篇文章中,我們將看到兩個不同的例子,來了解如何建立一個Go語言程式來列印反轉的雜湊集合。

語法

func make ([] type, size, capacity)

Go語言中的`make`函式用於建立陣列/對映,它接受要建立的變數型別、大小和容量作為引數。

func len(v Type) int

`len()`函式用於獲取任何引數的長度。它接受一個引數作為要查詢其長度的資料型別變數,並返回一個整數型別的長度值。

演算法

  • 在程式中匯入所需的包

  • 建立一個主函式

  • 在該函式中建立一個雜湊對映

  • 然後,使用內部函式建立一個反轉對映

  • 在控制檯上列印反轉對映

示例 1

在這個例子中,我們將建立一個雜湊對映和一個名為`inverted`的附加對映,以獲得反轉的輸出,即鍵分配給值。雜湊對映將被迭代以在每次迭代中獲得反轉的輸出。讓我們瞭解這個例子,仔細看看程式碼和演算法。

//Golang program to print the inverted hash collection
package main

import "fmt"

//Main to execute the program
func main() {
   // Create a map with keys of type string and values of type int
   hashmap := map[string]int{"apple": 100, "mango": 180, "banana": 120}
   
   // Create a new map with inverted keys and values
   inverted := make(map[int]string)
   for k, element := range hashmap {
      inverted[element] = k
   }
   
   // Print the inverted map
   fmt.Println("This is the following inverted map:")
   fmt.Println(inverted)
}

輸出

This is the following inverted map:
map[100:apple 120:banana 180:mango]

示例 2

在這個例子中,我們將在`make`函式中使用`len(map)`來建立反轉對映,該對映將用於儲存反轉的鍵值對。輸出將是使用`fmt`包在控制檯上列印的反轉對映。讓我們透過程式碼和演算法來了解執行過程。

//Golang program to print the inverted hash collection
package main

import "fmt"

//Main function to execute the program
func main() {
   // Create a map with keys of type string and values of type int
   hashmap := map[string]int{"apple": 100, "mango": 120, "banana": 130}
   
   // Create a new map with inverted keys and values
   inverted := make(map[int]string, len(hashmap))
   for k, element := range hashmap {
      inverted[element] = k
   }
   
   // Print the inverted map
   fmt.Println("The inverted map is presented as follows:")
   fmt.Println(inverted)
}

輸出

The inverted map is presented as follows:
map[100:apple 120:mango 130:banana]

結論

我們使用兩個例子執行了列印反轉雜湊集合的程式。在第一個例子中,我們建立了不使用`len(hashmap)`的附加對映,而在第二個例子中,我們使用`len(hashmap)`函式建立了對映。

更新於:2023年3月27日

瀏覽量:121

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.