根據輸入生成隨機 6 個字符。就像我想1028797107357892628變成j4w8p. 或102879708974181177進入lg36k,但我希望它是一致的。就像我每次喂食一樣1028797107357892628,它應該總是吐出來j4w8p。這可能嗎?(如果可能,沒有資料庫。)我知道如何生成隨機 6 個字符,但我不知道如何將它與輸入 tbh 連接起來。我會很感激任何幫助,謝謝。
let rid = (Math.random() 1).toString(36).substring(7);
uj5u.com熱心網友回復:
您可以創建一個自定義散列函式,您的代碼的一個簡單函式將是
const seed = "1028797089741811773";
function customHash(str, outLen){
//The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
const splitted = str.match(regx);
let out = "";
for(const c of splitted){
let ASCII = c % 126;
if( ASCII < 33) ASCII = 33
out = String.fromCharCode(ASCII)
}
return out.slice(0, outLen)
}
const output = customHash(seed, 6)
console.log(output)
uj5u.com熱心網友回復:
它被稱為散列,散列不是隨機的。在你的例子中得到rid:
let rid = (Math.random() 1).toString(36).substring(7);
因為它是隨機的,所以不可能像你期望的那樣產生“一致的結果”。
您需要演算法來產生“隨機”一致的結果。
uj5u.com熱心網友回復:
謝謝大家,解決了我的問題。
代碼:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(0,6)
console.log(rid)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512728.html
標籤:javascript数学
下一篇:如何在c源代碼中實作積分
