4 ms·
You clearly have a different experience using 1-based index than me, it has caused me many off-by-one mistakes. Also, I almost never need to -1 with 0-based ind
by bilkow 6y ago
You clearly have a different experience using 1-based index than me, it has caused me many off-by-one mistakes. Also, I almost never need to -1 with 0-based index, but in 1-based index its pretty common, specially if moving slices inside an array, the new index of the element is move_position + old_index - 1 (see example). Also see arguments by Djikstra [0].
Example:
# python
lov = ['l', 'o', 'v']
o_index = 1;
array = ['a', 'b', 'c', 'd', 'e', 'f']
move_position = 3
# elements moved here
array = ['a', 'b', 'c', 'l', 'o', 'v']
new_o_index = move_position + o_index
print(array[new_o_index]) # prints 'o'
-- lua
local lov = { 'l', 'o', 'v' }
local o_index = 2;
local array = { 'a', 'b', 'c', 'd', 'e', 'f' }
local move_position = 4
-- elements moved here
array = { 'a', 'b', 'c', 'l', 'o', 'v' }
local new_o_index = move_position + o_index - 1
print(array[new_o_index]) -- prints 'o'
Note that I'm not saying 0-based indexing is always absolutely better, but I generally prefer it and believe it usually makes more sense even outside of programming (including math), we're just not taught that way.
[0] https://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF https://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
transcript: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/E...