Created
August 7, 2021 09:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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