3 ms·
I never found it to be a big deal, unless you're trying to copy algorithms from another language nearly verbatim. There's not really any math that relies on 0 i
by ominous_prime 14y ago
I never found it to be a big deal, unless you're trying to copy algorithms from another language nearly verbatim. There's not really any math that relies on 0 indexing,
- greggman 14y agoI guess it depends on what you mean by "relies" Using a single dimensional array as a 2 dimensional array relies on zero indexing. index = y * width + x array[index] Using modulo to covert an index back to 2 dimensions relies on 0 indexing x = index % width y = index / width Skipping a prefix in a string. prefix = "ABC" string = "ABCdef" unprefixed = string[prefix.length:] I'm sure there are tons of others. Yes, you can add 1 or subtract 1 in the right places. That's the annoying part of it though.
- Dylan16807 14y agoWell lua doesn't even have an operator for integer division.
- ominous_prime 14y agoGood points. I was thinking that there are probably an equal number of array arrithmatic tricks that also require a +-1 here and there, but it was just a hunch. As I said though, never found it to be a problem in practice.
- rbehrends 14y agoEh, for every use case where it's more convenient that arrays start at zero, there's one where it's more convenient that arrays start at one, and vice versa. For example, to get a prefix of length 'n', you need characters 0 through n-1 with zero-based indexing and 1 through n with one-based indexing. (That Python hides the -1 when using a [0:n] range is a convenience; the subtraction still happens internally.) Similarly, to get the last element of a one-based array with a[length(a)] and the last element of a zero-based array with a[length(a)-1]. What it comes down to is that sometimes you have to write +1 or -1 for zero-based indexing where you can avoid it for one-based indexing and vice versa. What is not the case is that it only universally happens for one of those schemes.
- anonymoushn 14y agoThe first two examples already work in lua if you just put something at 0.
- qznc 14y agoMathematically, starting with zero is more consistent, because it leads to the fact that the length of a range is the difference between its bounds (length x..y == y-x). More elaborate and rigorous: http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831.html http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831....