js给定一个数生成另一个4位数,作为下标取数组下标值


	generateUniqueFourDigitConstruct(inputNumber,arr) {
    // 哈希函数
    function simpleHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            hash = (hash * 31 + str.charCodeAt(i)) >>> 0;
        }
        return Math.abs(hash);
    }
    
    const inputStr = String(inputNumber);
    const hash = simpleHash(inputStr);
    
    // 可用数字 0-9
    const allDigits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let tempHash = hash;
    
    // 选择千位(不能是0)
    const thousandIndex = (tempHash >> 0) % 9; // 0-8 对应 1-9
    const thousand = allDigits[thousandIndex + 1];
    
    // 移除已选的千位数字
    const remaining1 = allDigits.filter(d => d !== thousand);
    tempHash = (tempHash * 1664525 + 1013904223) >>> 0;
    
    // 选择百位
    const hundredIndex = tempHash % remaining1.length;
    const hundred = remaining1[hundredIndex];
    
    // 移除已选的百位数字
    const remaining2 = remaining1.filter(d => d !== hundred);
    tempHash = (tempHash * 1664525 + 1013904223) >>> 0;
    
    // 选择十位
    const tenIndex = tempHash % remaining2.length;
    const ten = remaining2[tenIndex];
    
    // 选择个位
    const remaining3 = remaining2.filter(d => d !== ten);
    const unit = remaining3[0]; // 只剩一个数字了
    
		let tm= thousand * 1000 + hundred * 100 + ten * 10 + unit;
	 console.log(tm);
		if(inputNumber%2==0){
			arr=arr.reverse();//反转
		}
		let result=[];
		(tm+"").split("").forEach(f=>{
			result.push(arr[f])
		})
		return result;
}

数组长度不要超过18位,超过拿不到中间值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值