1 回答

TA貢獻1886條經驗 獲得超2個贊
根據您的描述 GetFromIndex(122) 應該返回 a8,而不是 bb
要么我沒有得到正確的場景,要么我們缺少信息
-編輯-
我不確定這是最好的方法
第一個角色每次都會移動
第 2 -> 3 次
第 3 次 -> 9 次 ...
我減去無用的循環
第二個 -> 每個 3 * len(array)
第三個 -> 每個 9 * len(array)
并獲得他們在數組中的位置
func TestA(t *testing.T) {
for i:=0; i<=30; i++ {
fmt.Printf("%s i:{%d} \n",GetFromIndexBis(i),i)
}
}
func GetFromIndex(index int) string {
var basicChars = []rune("abc")
len := len(basicChars)
pow := 1
sumPow := 0
res :=""
// the first is a simple modulo
res += string(basicChars[index%len])
for {
pow = pow * len
// is the index big enought ?
if index < pow+sumPow{
break
}
// remove the first cycles where nothing pushed the wheels
start := index - sumPow
// number of cycle we need to make a full turn
fullCycles := pow * len
if start>=fullCycles {
nbrOfUselessCycles := start / fullCycles
start = start - fullCycles * nbrOfUselessCycles
}
index := (start / pow) -1
// it's the last one
if (index == -1) {
res += string(basicChars[len-1])
}else {
res += string(basicChars[index])
}
sumPow += pow
}
return res
}
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報