LoginSignup
65
59

More than 5 years have passed since last update.

競技プログラミングで使うGo言語基礎

Last updated at Posted at 2016-09-26

これだけ知ってればとりあえず問題は解けるよってやつ。
間違いの指摘等、コメントお待ちしてます。

入力

一行読み込む

var sc = bufio.NewScanner(os.Stdin)

func nextLine() string {
    sc.Scan()
    return sc.Text()
}

func main() {
    line := nextLine()
    // 処理
}

参考:Go 言語で標準入力から読み込む競技プログラミングのアレ --- 改訂第二版

文字列を空白区切りでばらす

s := "1 2 3 4"
cols := strings.Split(s, " ")
// cols[index]でアクセス

文字列をint変換する。

s := "1234"
n, _ := strconv.Atoi(s)

文字列をfloat64に変換する

s := "12.34"
f, _ := strconv.ParseFloat(s, 64) 

文字列に1文字ずつアクセス

s := "abcd"
cols := strings.Split(s, "")
for _, c := range cols {
    // 処理
}

部分文字列を取り出す

s1 := "0123456"
// 2番目から4番目(の手前)までを取り出す
s2 := s1[2:4]
// s2 : 23

出力

fmt.Printもしくは、fmt.Println

  • 引数はinterface{}型なので、int型等でもそのまま引数に渡せる
  • 引数は可変長
// 最後に改行あり、複数引数は間に半角スペース
fmt.Println(hoge, fuga)

// 改行なし、間に半角スペースなし
fmt.Print(hoge, fuga)

パフォーマンスを気にするときはこちらを参考
Go 言語で標準出力に書き出す競技プログラミングのアレ

2次元配列

配列より可変であるSliceを使うことのほうが多い。一発でmakeできないので、以下のようにfor文で初期化する。

// x*yのbool型のスライス
field := make([][]bool, x)
for i := 0; i < x; i++ {
    field[i] = make([]bool, y)
}
65
59
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
65
59