6 ms·
Look at your hand and start counting your fingers while naming them: [1] thumb [2] index [3] middle [4] ring [5] pinkie so we have a simple range [1..5]
by TweedHeads 17y ago
Look at your hand and start counting your fingers while naming them:
[1] thumb
[2] index
[3] middle
[4] ring
[5] pinkie
so we have a simple range [1..5]
which can be represented in so many ways in computer programs:
for i=1 to 5 print finger[i]
for(i in [1..5]) print finger[i]
my first finger[1] is my thumb
my last finger[5] is my pinkie
how many fingers we have? as many as the last index in the list: 5
-
now, C programmers like to count this way:
for(i=0;i<5;i++) print finger[i]
where finger[0] is thumb
and finger[4] is pinkie
how many fingers we have?
as many as the last index in the list plus one: 4+1
how human-like!
And that's why you get so messy when trying to get the string position of a substring:
if(pos>-1) exists, since pos=0 means the substring is in the starting position
again, how human-like!
But how dare I argue with C programmers without being burned at the stake?
- maweaver 17y agofor i=1 to 5 print finger[i] for(i in [1..5]) print finger[i] You're using an inclusive upper range here. Not that that's necessarily wrong, but it isn't standard for the reason Dijkstra mentioned (how many fingers do I have? 5 - 1 = 4. Oops.)
- TweedHeads 17y ago"how many fingers do I have? 5 - 1 = 4. Oops." Upper-Lower+1, easy. Whenever the lower is 1, just the upper is enough. In your case you go from 0 to 4, how's that different from how many fingers you have? 4-0=4 Oops.
- gloob 17y agoCongratulations; you have successfully introduced a whole new way to have off-by-one errors. People are used, due to forty years or more of tradition in the great majority of major languages, to zero-based indexing. Tossing that away Because It's Inelegant won't do much good to anyone, especially when you take into consideration the fact that an awful lot of math is more convenient with 0-based indexing.
- jongraehl 17y agoWhat makes you think people who 0-index arrays and prefer half-open intervals count any differently? Is this argument directed at a four year old? 4+1=5 never enters into it. What a rubbish argument. I might as well complain that your [a,b] has (b-a+1) integers in it. (5-0)=5 so the half open interval has 5 things in it. What's the measure of a real interval 1<=x<=5? 4. 0<=x<5? 5.
- TweedHeads 17y agoDon't try your cheap tricks on me. We go from 1 to 5, so the math would be 5-1 +1 You go from 0 to 4, the math would be the same, 4-0 +1 Using 5 as your upper bound, then starting from 0 to 4 is the same as me using 6 as my upper bound then going from 1 to 5.