Today I Learned - Rocky Kev

TIL One-by-one errors

POSTED ON:

TAGS:

Off by one errors

An off-by-one error is when you expect something to be of value N, but in reality it ends up being N-1 or N+1.

For example, you were expecting the program to perform an operation 10 times, but it ends up performing 9 or 11 times (one too few or one too many times).

In programming this is most commonly seen happening when dealing with "for" loops.


let n = 10;

// for (int i = 1; i < n; ++i) { ... }
let countStartAtOne = "0";
for (let i = 1; i < n; ++i) {
countStartAtOne += `, ${i}`;
}

// RESULTS: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

// for (int i = 0; i <= n; ++i) { ... }
let countStartAtZeroGreaterEqual = "0";
for (let j = 0; j <= n; ++j) {
countStartAtZeroGreaterEqual += `, ${j}`;
}

// RESULTS: 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

See the Pen by rockykev (@rockykev) on CodePen.

REF:
https://en.wikipedia.org/wiki/Off-by-one_error
https://stackoverflow.com/questions/2939869/what-is-an-off-by-one-error-and-how-do-i-fix-it


Related TILs

Tagged:

TIL math module in SASS!

math in Sass, oh my!

TIL the Quake 3 Fast Inverse Square Root hack

Quake III Arena, a first-person shooter video game, was released in 1999 by id Software and used the algorithm.

TIL that the max size of a Map/Set is 26843544

JS Maps and Sets are implemented by OrderedHashTable. OrderedHashTables double in size when they need to grow, and their max size is 26843544. After 16777216 elements, doubling that exceeds the max, so the allocation fails.Currently these data structures are not implemented to be usable for large in-memory datasets. Also note that the JS specification itself doesn't require that Maps and Sets must scale with available memory.