Skip to content

Instantly share code, notes, and snippets.

@definev
Created August 7, 2021 09:24
Show Gist options
  • Save definev/f94c64e53dc8ac5832ef255cc5bf38ab to your computer and use it in GitHub Desktop.
Save definev/f94c64e53dc8ac5832ef255cc5bf38ab to your computer and use it in GitHub Desktop.
Tìm ngày tháng năm sinh trong một tỉ số Pi đầu tiên bằng Golang
package main
import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func main() {
var file *os.File
// Chưa download thì sẽ down dữ liệu về
if !fileExists("pi-billion.txt") {
// Tạo file text lưu trữ 1 tỉ số pi
file, _ = os.Create("pi-billion.txt")
defer file.Close()
// Download dữ liệu sẽ hơi lâu một chút
resp, err := http.Get("https://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt")
if err == nil {
defer resp.Body.Close()
}
// Truyền dữ liệu vào file
_, _ = io.Copy(file, resp.Body)
} else {
file, _ = os.Open("pi-billion.txt")
}
// Đọc file và tìm kiếm số
b, _ := ioutil.ReadAll(file)
str := string(b)
strLen := len(str)
// Hãy tự thay ngày tháng năm sinh của bạn nhé!
srcStr := "24062003"
for i := 0; i < strLen; i++ {
if i+8 > strLen {
break
}
compareStr := str[i : i+8]
if srcStr == compareStr {
// In toàn bộ các kết quả
log.Println(i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment