亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據索引計算字符

根據索引計算字符

Go
楊__羊羊 2023-02-21 16:53:05
我當前的代碼: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 循環,但沒有保存狀態或無限期上升的好方法
查看完整描述

1 回答

?
MM們

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

}


查看完整回答
反對 回復 2023-02-21
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號