LoginSignup
0
0

More than 5 years have passed since last update.

オフラインリアルタイムどう書く F09 の実装(Go)

Posted at

オフラインリアルタイムどう書く F09 の実装例
問題 : http://nabetani.sakura.ne.jp/hena/ordf09rotbox/
解答リンク集 : https://qiita.com/Nabetani/items/61e13fa5cf0abe5979be

実装
package f09

import "strconv"

func format(cells [9]byte) string {
    s := ""
    for i := 0; i < 9; i++ {
        s += strconv.Itoa(int(cells[i]))
        if i == 2 || i == 5 {
            s += "/"
        }
    }
    return s
}

func solve(src string) string {
    c := [9]byte{
        1, 2, 3, 4, 5, 6, 7, 8, 9,
    }
    for _, cmd := range src {
        switch cmd {
        case 'a', 'b', 'c':
            d := (cmd - 'a') * 3
            c[0+d], c[1+d], c[2+d] = c[1+d], c[2+d], c[0+d]
        case 'd', 'e', 'f':
            d := (cmd - 'd')
            c[0+d], c[3+d], c[6+d] = c[6+d], c[0+d], c[3+d]
        case 'g', 'h', 'i':
            d := ('i' - cmd) * 3
            c[0+d], c[1+d], c[2+d] = c[2+d], c[0+d], c[1+d]
        case 'j', 'k', 'l':
            d := ('l' - cmd)
            c[0+d], c[3+d], c[6+d] = c[3+d], c[6+d], c[0+d]
        }
    }
    return format(c)
}
テスト
package f09

import (
    "testing"
)

func TestKoch(t *testing.T) {
    var tests = []struct {
        name  string
        input string
        want  string
    }{
        {"0", "aegj", "286/435/971"},
        {"1", "a", "231/456/789"},
        {"2", "e", "183/426/759"},
        {"3", "g", "123/456/978"},
        // 中略
        {"48", "baciefjhgkdl", "153/482/796"},
    }
    for _, test := range tests {
        got := solve(test.input)
        if got != test.want {
            t.Errorf("%v: solve(%q)=%q, want %q\n", test.name, test.input, got, test.want)
        }
    }
}

switchcase と多重代入の練習という感じ。
formatif 文がやや無様。どうするのが安いかなぁ。

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