LoginSignup
0
0

More than 5 years have passed since last update.

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

Posted at

問題 : http://nabetani.sakura.ne.jp/hena/ordf10updown/
実装リンク集 : https://qiita.com/Nabetani/items/dae474bc17827f9b1537

で。

https://qiita.com/Nabetani/items/1e673478d99e5dbfc1be にある実装のうちのひとつ(ruby の方 ) を、go で書いてみた。

実装
package f10

import (
    "fmt"
    "strconv"
)

func numAt(f map[string]int, x int, y int) string {
    val, ok := f[fmt.Sprintf("%d,%d", x, y)]
    if !ok {
        return "-"
    }
    return strconv.Itoa(val)
}

func solve(src string) string {
    num, _ := strconv.Atoi(src)
    f := map[string]int{}
    phase := 0
    x := 0
    y := 0
    var numx int
    var numy int
    upperbound := num*2 + 100 // 根拠のない計算
    for i := 1; i < upperbound; i++ {
        f[fmt.Sprintf("%d,%d", x, y)] = i
        if i == num {
            numx, numy = x, y
        }
        switch phase {
        case 0:
            y++
            phase = 1
        case 1:
            x++
            if x == y {
                phase = 2
            }
        case 2:
            y--
            if y == 0 {
                phase = 3
            }
        case 3:
            x++
            phase = 4
        case 4:
            y++
            if x == y {
                phase = 5
            }
        case 5:
            x--
            if x == 0 {
                phase = 0
            }
        }
    }
    v0 := numAt(f, numx, numy-1)
    v1 := numAt(f, numx, numy+1)
    v2 := numAt(f, numx-1, numy)
    v3 := numAt(f, numx+1, numy)
    return fmt.Sprintf("%s,%s,%s,%s", v0, v1, v2, v3)
}
test
package f10

import (
    "testing"
)

func TestKoch(t *testing.T) {
    var tests = []struct {
        name  string
        input string
        want  string
    }{
        {"0", "10", "9,25,-,11"},
        {"1", "1", "-,2,-,4"},
        {"2", "2", "1,9,-,3"},
        // 中略
        {"35", "6772", "6771,6773,6677,7009"},
    }
    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)
        }
    }
}

別に難しいことはなくて、順当な感じ。
後置if がほしいなぁとか、そういう気分。

v0〜v3 への代入をもう少しなんとかしたいところだけど、goならこんな感じかなとも思ったりする。

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