我正在用 Javascript 實作一個brainfuck 解釋器。我用陣串列示記憶體,我希望可以選擇將陣列索引限制在一個范圍內。如果指數超出此范圍,我希望它超過或低于限制。我在正確描述問題時遇到了一些麻煩。這是我正在考慮的一個例子:
lbound: 0, ubound: 10, index: 10, result: 0
lbound: 0, ubound: 10, index: 11, result: 1
lbound: -10, ubound: 0, index: -10, result: 0
lbound: -10, ubound: 0, index: -11, result: -1
lbound: -5, ubound: 15, index: 16, result: -4
lbound: 5, ubound: 15, index: 26, result: 6
我可以組成一個函式,例如:
if (index < lbound) {
// underflow
return ubound - index - index * Math.round(index / lbound)
}
if (index > ubound) {
// overflow
return lbound index - index * Math.round(index / ubound)
}
return index
但這太天真了,錯過了除以零的情況。我想我在這里有一個錯誤的方法。基本上,我正在尋找一個數學公式來映射一個范圍內的特定數字,包括負數。但不是簡單的重新分配。必須計算正確的過沖數或下沖數。因此,必須從索引中減去 lbound 或 ubound 的全部部分。最后,必須將差異添加或減去 lbound 或 ubound。
任何幫助都會很棒。:)
uj5u.com熱心網友回復:
基本上模是您正在尋找的操作。只是你讓它有點棘手,因為你也想支持負數,所以需要將模數結果添加到“公式”中。
下面的這個函式應該可以解決問題:
function keepIndexInsideRange(index, lbound, ubound) {
var range = Math.abs(ubound - lbound);
var result = index % range;
if (lbound < 0 && index > ubound) {
result = -(range - result);
}
return result;
}
console.log('should return 0', keepIndexInsideRange(10, 0, 10)); // OK
console.log('should return 1', keepIndexInsideRange(11, 0, 10)); // OK
console.log('should return 0', keepIndexInsideRange(-10, -10, 0)); // OK
console.log('should return -1', keepIndexInsideRange(-11, -10, 0)); // OK
console.log('should return -9', keepIndexInsideRange(1, -10, 0)); // OK
console.log('should return -4', keepIndexInsideRange(16, -5, 15)); // OK
console.log('should return 6', keepIndexInsideRange(26, 5, 15)); // OK
你可以在這里玩它https://stackblitz.com/edit/typescript-lxw3ai?file=index.ts(只需展開螢屏右側的控制臺)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361221.html
標籤:javascript 数学
