Go語言程式:陣列元素洗牌


陣列是元素的固定序列,其中元素放置在連續的記憶體位置。我們將對陣列的元素進行洗牌並隨機放置。在第一種情況下,我們將使用Fisher-Yates洗牌演算法。讓我們看看如何使用Go語言程式碼中不同的邏輯來執行它。

語法

rand.Seed(value)

Rand.Seed()函式用於生成隨機數。它接受使用者輸入作為引數,該引數是生成隨機數的上限。

func Now() Time

Now()函式定義在time包中。此函式生成當前本地時間。要使用此函式,我們必須首先在程式中匯入time包。

func (t Time) UnixNano() int64

UnixNano()函式定義在time包中。此函式用於獲取自1970年1月1日UTC以來經過的秒數。它返回的最終結果是64位的整數型別。

rand.Intn(n)

Intn()函式定義在math/rand包中。它用於生成區間[0, n]內的隨機數,其中n是使用者提供的數字。如果提供的數字小於0,則該函式會丟擲錯誤。

演算法

  • 步驟1 - 建立一個package main並宣告fmt(格式化包)、time和math/rand包

  • 步驟2 - 在main函式中建立一個數組

  • 步驟3 - 使用內部/使用者定義的函式來建立隨機數

  • 步驟4 - 使用使用者定義的函式開始洗牌過程。

  • 步驟5 - 列印洗牌後陣列的輸出

示例1

在這個例子中,我們將學習如何使用Fisher-Yates洗牌演算法來洗牌陣列的元素。

package main
import (
   "fmt"
   "math/rand" //import fmt and math/rand
)

//create main function to execute the program
func main() {
   array := []int{10, 20, 30, 40, 50, 60, 70, 80} //create an array which is to shuffled
   fmt.Println("The elements of array are:", array)
   shuffle(array) //call the function shuffle
   fmt.Println("The shuffled array given here is:")
   fmt.Println(array)
}

// shuffle shuffles the elements of an array in place
func shuffle(array []int) {
   for i := range array { //run the loop till the range of array
      j := rand.Intn(i + 1) //choose any random number
      array[i], array[j] = array[j], array[i] //swap the random element with current element
   }
}

輸出

The elements of array are: [10 20 30 40 50 60 70 80]
The shuffled array given here is:
[60 50 30 70 80 10 40 20]

示例2

在這個例子中,我們將使用rand.Seed函式來洗牌陣列的元素。

package main
import (
   "fmt"
   "math/rand" //import fmt, math/rand and time
   "time"
)

//create main function to execute the program
func main() {
   array := []int{10, 20, 30, 40, 50, 60} //create an array which is to shuffled
   fmt.Println("The elements of array are:", array)
   rand.Seed(time.Now().UnixNano()) // generate random numbers using this function
   shuffle(array)
   fmt.Println("The shuffled array is:")
   fmt.Println(array)
}
func shuffle(array []int) {
   for i := len(array) - 1; i > 0; i-- { //run the loop from the end till the start
      j := rand.Intn(i + 1)
      array[i], array[j] = array[j], array[i] //swap the random element with the current element
   }
}

輸出

The elements of array are: [10 20 30 40 50 60]
The shuffled array is:
[10 30 60 50 20 40]

結論

我們使用兩組示例執行了這個陣列洗牌程式。在第一個示例中,我們使用了Fisher-Yates演算法,在第二個示例中,我們使用了rand.Seed函式。我們使用不同的邏輯對陣列進行了洗牌。因此,程式成功執行。

更新於:2023年2月13日

852 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告