0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go言語】PaizaでGOの勉強を始めました。

Posted at

はじめに

Go言語での標準入出力や基本的な処理パターンを学習したので備忘録として残します。

標準入力の基本テンプレート

1行読み取り

package main
import (
    "fmt"
    "bufio"
    "os"
    "strconv"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    sc.Scan()
    input := sc.Text()
    num, _ := strconv.Atoi(input)
    fmt.Println(num)
}

スペース区切りの複数値

sc := bufio.NewScanner(os.Stdin)
sc.Scan()
parts := strings.Split(sc.Text(), " ")
a, _ := strconv.Atoi(parts[0])
b, _ := strconv.Atoi(parts[1])

配列操作

push_back / pop_back的な操作

// 末尾に追加
arr = append(arr, newValue)

// 末尾を削除
arr = arr[:len(arr)-1]

最大値・最小値

maxVal, minVal := arr[0], arr[0]
for _, num := range arr {
    if num > maxVal { maxVal = num }
    if num < minVal { minVal = num }
}

出力パターン

区切り文字付き出力

// 手動制御
for i, value := range array {
    if i > 0 {
        fmt.Print(",")
    }
    fmt.Print(value)
}
fmt.Println()

// strings.Join使用(推奨)
fmt.Println(strings.Join(array, ","))

// NG
num, err := strconv.Atoi(input1)
num, err := strconv.Atoi(input2) // エラー

// OK
num, err := strconv.Atoi(input1)
num, err = strconv.Atoi(input2) // = を使用


### 3. スコープ問題
```go
// NG: forループ外でvalueは使えない
for _, value := range array {
    // ...
}
fmt.Println(value) // エラー

// OK: 事前に変数宣言
var result string
for _, value := range array {
    result = value
}
fmt.Println(result)

4. 1-indexed と 0-indexed

// 問題でA_Mが1-indexedの場合
A_M := array[M-1]  // 配列は0-indexedなのでM-1

頻出の入力パターン

パターン1: N個の要素

N
A_1 A_2 ... A_N
sc.Scan()
N, _ := strconv.Atoi(sc.Text())
sc.Scan()
A := strings.Split(sc.Text(), " ")

パターン2: N M + 配列 + クエリ

N M
A_1 ... A_N
Q
B_1 ... B_Q
// N M読み取り
sc.Scan()
nm := strings.Split(sc.Text(), " ")

// A配列読み取り
sc.Scan()
A := strings.Split(sc.Text(), " ")

// Q読み取り
sc.Scan()

// B配列読み取り
sc.Scan()
B := strings.Split(sc.Text(), " ")

便利なコードスニペット

文字列を3桁ごとにカンマ区切り

var parts []string
for i := 0; i < len(str); i += 3 {
    parts = append(parts, str[i:i+3])
}
fmt.Println(strings.Join(parts, ","))

超大きな数値(10^1000など)

数値型では扱えないので文字列として処理

// 文字列のまま3文字ずつ処理
n := sc.Text()  // "123456789"
for i := 0; i < len(n); i += 3 {
    if i > 0 {
        fmt.Print(",")
    }
    fmt.Print(n[i:i+3])
}

感想

  • Goはシンプルで覚えやすい
  • range文が便利

引き続きPaizaで問題を解いて慣れていきます!

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?