How to shuffle the content in file in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to shuffle the content in file using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.
##############SOURCE CODE#########################
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
func shuffleLines(lines []string) {
rand.Seed(time.Now().UnixNano())
for i := len(lines) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
lines[i], lines[j] = lines[j], lines[i]
}
}
func main() {
// open the input file for reading
inputFile, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer inputFile.Close()
// create a scanner to read the file line by line
scanner := bufio.NewScanner(inputFile)
// read the lines of the file into a slice of strings
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// shuffle the lines
shuffleLines(lines)
// open the output file for writing
outputFile, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer outputFile.Close()
// write the shuffled lines to the output file
writer := bufio.NewWriter(outputFile)
for _, line := range lines {
fmt.Fprintln(writer, line)
}
writer.Flush()
fmt.Println("File shuffled successfully!")
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
This program first opens the input file for reading using the os.Open function and creates a scanner to read the file line by line using the bufio.NewScanner function.
It reads the lines of the file into a slice of strings using a for loop and the scanner.Text method.
Next, it defines a function called shuffleLines that takes a slice of strings as an argument and shuffles its elements using the Fisher-Yates shuffle algorithm.
The shuffleLines function works similarly to the previous example, except that it operates on a slice of strings instead of an array of integers.
The main function calls the shuffleLines function to shuffle the lines of the input file, opens the output file for writing using the os.Create function, and writes the shuffled lines to the output file using a for loop and the fmt.Fprintln function.
Finally, it flushes the output buffer using the writer.Flush method and prints a success message to the console.
#go #goprogramming #golang #golangtutorial #golanguage