Last active
March 20, 2016 19:46
-
-
Save mdk-aza/e18c4431809b88f150e0 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(fourArithmeticOperationsOfTheSequence(1395))) | |
} | |
func fourArithmeticOperationsOfTheSequence(number int) int { | |
//+,-,/を使うと桁数が変わってしまうので、*となしの2つしか演算子は使用しない | |
op := []string{"*", ""} | |
//引数の数がインクリメントされるループ | |
for i := number; i < 10000; i++ { | |
c := strconv.Itoa(i) | |
for _, firstOp := range op { | |
for _, secondOp := range op { | |
for _, thirdOp := range op { | |
//1234の場合、以下のような数字が計算対象としての式を構築する | |
// 1*2*3*4 | |
// 1*23*4 | |
// 1234 | |
exp := c[3:4] + firstOp + c[2:3] + secondOp + c[1:2] + thirdOp + c[0:1] | |
//必ず1つは演算子を入れるための条件 | |
if (4 < len(exp)) { | |
var lex Lex | |
lex.Init(strings.NewReader(exp)) | |
if (i == expression(&lex)) { | |
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) int { | |
var n int | |
fmt.Sscan(lex.TokenText(), &n) | |
lex.getToken() | |
return n | |
} | |
// 項の処理 | |
func term(lex *Lex) int { | |
val := factor(lex) | |
for { | |
switch lex.Token { | |
case '*': | |
lex.getToken() | |
val *= factor(lex) | |
default: | |
return val | |
} | |
} | |
} | |
// 式の評価 | |
func expression(lex *Lex) int { | |
lex.getToken() | |
return term(lex) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment