Created
March 20, 2016 17:03
-
-
Save mdk-aza/b3bb3358610349cbb9ac to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"text/scanner" | |
"strings" | |
"strconv" | |
) | |
func main() { | |
fmt.Println(reverseIntToStr(reverseNumber(1000))) | |
} | |
func reverseNumber(number int) int { | |
op := []string{"*", ""} | |
//引数の数がインクリメントされるループ | |
for i := number; i <= 10000; i++ { | |
var numberStr = strconv.Itoa(i) | |
var c []string | |
for _, value := range numberStr { | |
c = append(c, string(value)) | |
} | |
for j := 0; j < len(op); j++ { | |
for k := 0; k < len(op); k++ { | |
for l := 0; l < len(op); l++ { | |
//1234の場合、以下のような数字が計算対象としての式を構築する | |
// 1*2*3*4 | |
// 1*23*4 | |
// 1234 | |
result := string(c[3] + op[j] + c[2] + op[k] + c[1] + op[l] + c[0]) | |
//必ず1つは演算子を入れる | |
if (4 < len(result)) { | |
var lex Lex | |
lex.Init(strings.NewReader(result)) | |
val := expression(&lex) | |
if (i == int(val)) { | |
return i | |
} | |
} | |
} | |
} | |
} | |
} | |
return 0 | |
} | |
func reverseIntToStr(num int) string { | |
runes := []rune(strconv.Itoa(num)) | |
for i, j := 0, len(runes) - 1; i < j; i, j = i + 1, j - 1 { | |
runes[i], runes[j] = runes[j], runes[i] | |
} | |
return string(runes) | |
} | |
// 字句解析 | |
type Lex struct { | |
scanner.Scanner | |
Token rune | |
} | |
// トークンを求める | |
func (lex *Lex) getToken() { | |
lex.Token = lex.Scan() | |
} | |
// 因子の処理 | |
func factor(lex *Lex) float64 { | |
switch lex.Token { | |
case scanner.Int, scanner.Float: | |
var n float64 | |
fmt.Sscan(lex.TokenText(), &n) | |
lex.getToken() | |
return n | |
default: | |
panic(fmt.Errorf("unexpected token: %v", lex.TokenText())) | |
} | |
} | |
// 項の処理 | |
func term(lex *Lex) float64 { | |
val := factor(lex) | |
for { | |
switch lex.Token { | |
case '*': | |
lex.getToken() | |
val *= factor(lex) | |
default: | |
return val | |
} | |
} | |
} | |
// 式の入力と評価 | |
func expression(lex *Lex) float64 { | |
lex.getToken() | |
return term(lex) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment