根据索引计算字符

我当前的代码:


var basicChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

func GetFromIndex(index int) string {

    length := len(basicChars)


    size := 0 // size is the amount of characters in the final string

    for {

        if float64(index) > math.Pow(float64(length), float64(size))-2 {

            size++

        } else {

            break

        }

    }


    str := make([]rune, size)


    for i := 0; i < size; i++ {

        str[i] = basicChars[index%length]

    }


    return string(str)

}

我正在尝试用字母而不是数字来计算。


我知道我可以使用 for 循环,但没有保存状态或无限期上升的好方法


杨__羊羊
浏览 99回答 1
1回答

MM们

根据您的描述 GetFromIndex(122) 应该返回 a8,而不是 bb要么我没有得到正确的场景,要么我们缺少信息-编辑-我不确定这是最好的方法第一个角色每次都会移动第 2 -> 3 次第 3 次 -> 9 次 ...我减去无用的循环第二个 -> 每个 3 * len(array)第三个 -> 每个 9 * len(array)并获得他们在数组中的位置func TestA(t *testing.T) {&nbsp; &nbsp; for i:=0; i<=30; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s i:{%d} \n",GetFromIndexBis(i),i)&nbsp; &nbsp; }}func GetFromIndex(index int) string {&nbsp; &nbsp; var basicChars = []rune("abc")&nbsp; &nbsp; len := len(basicChars)&nbsp; &nbsp; pow := 1&nbsp; &nbsp; sumPow := 0&nbsp; &nbsp; res :=""&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // the first is a simple modulo&nbsp; &nbsp; res += string(basicChars[index%len])&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; pow = pow * len&nbsp; &nbsp; &nbsp; &nbsp; // is the index big enought ?&nbsp; &nbsp; &nbsp; &nbsp; if index < pow+sumPow{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // remove the first cycles where nothing pushed the wheels&nbsp; &nbsp; &nbsp; &nbsp; start := index - sumPow&nbsp; &nbsp; &nbsp; &nbsp; // number of cycle we need to make a full turn&nbsp; &nbsp; &nbsp; &nbsp; fullCycles := pow * len&nbsp; &nbsp; &nbsp; &nbsp; if start>=fullCycles {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nbrOfUselessCycles := start / fullCycles&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; start = start - fullCycles * nbrOfUselessCycles&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; index := (start / pow) -1&nbsp; &nbsp; &nbsp; &nbsp; // it's the last one&nbsp; &nbsp; &nbsp; &nbsp; if (index == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res += string(basicChars[len-1])&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res += string(basicChars[index])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; sumPow += pow&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return res}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go