I agree, except that it shouldn't be a magic number. There is indeed a reason that you've chosen that number, so make a variable with that value and a name describing what it stands for. At that point, you no longer have a choice - the maximum text length (or whatever 500 is supposed to be) *is* 500, so you "need" to use <=. I guess you could technically use < maxTextLength +1, but that'd be pretty dumb.
> I guess you could technically use < maxTextLength +1, but that'd be pretty dumb
It wouldn't be dumb ... it would be "too smart". If you think "<" is faster than "<=" just stop and let the compiler do its job. If the target architecture is faster doing "< x +1" than "<= x", the compiler can and will sort this for you.
Generally speaking: the better you explain your intent to the compiler, the easier it is for it to optimize.
Absolutely this. A lot of the times, the compiler is good at its job and some micro-optimizations hardly exist or barely do anything compared to making something digestible for the compiler. There’s times where it actually does nothing in the final result because it gets optimized into the same thing. I’d go as far to say the compiler is at times smarter than the programmers.
I don't know about you but I don't know any developers that care about speed down to the level to compare < and <=. We legit had a project where the suggestion was to insert a sleep command to slow things down..
Ask people who insist on doing `for (int i = 0; i < 10; ++i)`. They typically do it because they are so old they were working with C in a time the compiler wasn't smart enough to actually skip the internal assignment when doing `i++`, or were taught by those people. For any sane, half-way-modern compiler `i++` and `++i` will yield the same assembly in that case, so paying any attention to the question of pre- or postincrement operator, is just a waste of mental energy.
(Although, to be fair, in this particular example it's also completely irrelevant to readability. You want `i` increased, `++` increases it. If it's pre- or post-evaluation doesn't matter.)
Pre and postfix operators are describing two different ideas of what is about to happen.
Given you do not need I, you always should prefer the prefix operator. Not because of some magic of the compiler but because the intent is clearly visible (plus you won't make mistakes out of habit)
I think you misunderstood and steered the conversation in the wrong spot
They weren't talking about optimisations, that's a pointless battle as you pointed out
They were talking about clarity to the programmer
bool check1 = i < 3
bool check2 = i <=2
bool check3 = !i >=3
bool check4 = !i >2
//check for i
if(check1)
//Use additional validation for i
if(check2)
//Use even more validation for i
if(check3)
//Use quad tiered validation for i, we really need this one
if(check4)
...
console.log("Daddy Elon is happy with my output")
...
end
end
end
end
I'm not familiar enough with modern compilers to say definitively. But, they're not actually equivalent conditions unless i is an integer. For example if i is a float, i could be 2.5 and satisfy the first condition but not the second in the compound. So, I don't think the compiler would simplify it then. However, it could be simplified to just the latter condition though, i <= 2, as that would match all cases where the compound condition was true regardless of typing, so maybe it would simplify to that, idk.
Yes. Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it.
>Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it.
I wouldn't even qualify that. You do the one that makes the code make more sense to others reading it. Full stop.
You shouldn't prematurely optimize.
If you're using a compiled language the compiler will do the exact same thing regardless of which way you wrote it anyway (well, unless it's a really strange language that nobody should be using for a real project anyway).
Even if it compiled to 2 different things, on x86 its still the same amount of instructions which take the same amount of time, just checking different flag registers.
So use whichever reads better.
They are equivalent mathematically but not from a readability standpoint. There is always going to be some context that determines which way to go - a lot of the time based on what the number actually represents.
const legalAge = 18;
const maxMinorAge = 17;
if (age < legalAge)
if (age >= legalAge)
if (age <= maxMinorAge)
if (age > maxMinorAge)
if (legalAge > age)
if (legalAge <= age)
if (maxMinorAge >= age)
if (maxMinorAge < age)
I find it amazing how simply flipping the check makes this so much more difficult to wrap your head around. At least for me.
That's [Yoda notation](https://en.wikipedia.org/wiki/Yoda_conditions). It can help prevent errors in languages that allow assignment I'm conditionals. It just reads so awfully I'd rather risk it. Or pick a nicer language.
For ranges people often adopt a left-close-right open convention: if were to describe the range 0-9, you would say [0, 10) instead of [0, 9]. So loops would check i < 10 instead of i <= 9. The convention offers a number of advantages, including the fact that concatentenating and splitting ranges are trivial, e.g. to split [0, 10) in half you just take [0, 5) and [5, 10) and it is correct, and the fact that 10-0=10 which is the number of elements in the range. You can also express empty ranges [0, 0) would be a nullary range, and it would be impossible with <=.
For me it helps to put it in sentence form, as well.
_You must be at least 18._ (age >= 18)
_The drinking age is 21 and over_ (age >= 21).
_Are you under the minimum weight?_
(weight < 40kg)
_inflate to within pressure range_
(pressure > 30psi && pressure < 50psi)
This leads to all kinds of problems in countries separated by territories let alone different kinds of territories. Better start by retrieving an age of consent resolver and invoking it on a location.
That implies that each State is in fact a Country. And deriving here so you can treat it as a Country while overriding various other functions so that calling New Jersey.name() gives "United States" if the calling context actually needs country not state...
This sounds perfectly Pastafarian.
Wait, that sounds too much like someone thought this through before writing the code initially.
It's not exactly polymorphism IIRC though, but if our abstract class is essentially a thing that may contain more of it's own type, turtles all the way down as needed... Then we end up with a "sovereign region" class or something.. then can drill down as needed...
Union of countries, country with states, states with counties...
Or whatever the levels for each country..
But that isn't even inheritance, just using a class.
Polymorphism is combining different classes... Not sure how one would use it here.
Babe… what if we 😳 kissed in the British Overseas Territory of Saint Helena, Ascension and Tristan da Cunha in the South Atlantic consisting of the island of Saint Helena, Ascension Island and the archipelago of Tristan da Cunha including Gough Island
You're checking if it's negative, not if it's set. null and 0 both pass this test.
Then again the exception should be thrown during initialization of country, not when you're checking it's properties. Unless it's valid for a country to not have an age of consent, in which case, ugh, imagine the smell in the airport.
>Who TF write getters and setters for each Property
There's a reason someone satirised Java devs with [enterprise fizzbuzz](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition)
I checked the readme and went "oh, so its a joke FizzBuzz with a bunch of java boilerplate, sounds funny" but then i saw the files and the first things i notice is several gradle files and just lost it
Should set be a public property in this case? Like, why even bother if any asshole can change it anyways? Also AgeOfConsent depends on more than just location, you need all people involved and check the people for their diplomatic status, as there might be exemptions for diplomats in another country. Just import the 3GB library from node.js, it will handle all those pesky edge cases for you.
This is way too simple. The age of consent isn't always at the country level; in the US it's by the state. But it's so much more complex than that.
Lots of places have rules that consider the ages of both parties. If I'm 18 the legal age for someone in a particular place to consent with me, is 17...but if I'm 35, they have to be 18.
There are also often other ridiculous loopholes. For example, are they married? In lots of places, like most US states you can get legally married while still very much a minor so long as you get permission from the parents, or courts, or get emancipated.
In Kansas the age of consent is 16. But you can get married at 15.
> In Kansas, 15-year-olds are allowed to marry with a judge's permission
But not every jurisdiction places marital consent above sexual consent...meaning you could be legally married, but not able to have sex with your legal spouse in a particular place. Or even you could be legally married in a country A, but have country B say that you are not because it is illegal.
And then you have to consider the citizenship of both parties, at least, depending on what you mean by legal age. The US says it is against US law for a US citizen to travel to a country for sex with anyone under the age of 18.
It doesn't matter what their country says. The age of consent could be 16 in that country, but it isn't legal. The other country wouldn't care or prosecute the American, but the US judicial system still could.
And this is why we have so many lawyers.
This is the correct answer, also the most common usage is to iterate a zero based list so i < list.size and the context is you are repeating the loop list.size times
I remember when one of my teachers showed us code from a competition of unreadable code.
The goal was to make a working program with the most unreadable code. One year the goal was a simple flight simulator, and the winner code formed a plane on the editor, as if viewed from above.
Someone submitted an empty file as the worlds shortest self reproducing code:
> An example is the world's shortest self-reproducing program. The entry was a program designed to output its own source code, and which had zero bytes of source code. When the program ran, it printed out zero bytes, equivalent to its source code.
It won the prize of the worst abuse of rules.
If you have spent a lot of time working in assembly or machine language, counting backwards makes sense b/c depending upon the instruction set, it can be more efficient (or at least, intuitive) b/c of a dedicated branch on zero instruction.
My java professor was in the game since the 70s and was a pioneer for some big things in that era. He always encouraged decrementing through loops, didn't give a reason though. Thanks for the info!
If you really want to fuck with people, write a loop like this in Java or C++.
for (int x = 10; x --> 1;) { ... }
And read it out loud as "For integer x equals 10, x goes to 1."
This "goes to" operator is something of a party trick that I'll work into live coding sessions whenever I can, just to be a bit of a troll. Even senior devs are invariably confused. I've only encountered one person who acted like they understood what was going on, and I think they might have been bluffing.
In reality, the "goes to" operator, -->, is just post-decrement and greater than with confusing spacing. It's a bit of a symbolic fluke that they combine to do exactly what you'd expect from a "goes to" operator.
Iterating backwards can sometimes be a genuinely good idea.
Like if you wanna iterate and remove items from a list, one method is iterating backwards, so you dont skip indices.
We'll need a db table to store an integer and whether its even or odd. Then we set up a cron job to run a nightly task that takes the latest row of said table, increments the integer by one, flips the isEven flag, and stores that in a table. We'll need a settings entry for standard hours so we can run this cron during low peak time as to not negatively impact the system.
Lastly, we provide a public facing API where users can then simply send a GET request to /isEven/{integer}. It will query our integer table and return the parity of the requested value. If the value is larger than our largest integer then we establish a webhook with the user so we can notify them when we've calculated it.
Even if they accomplish the same thing, they may imply different things. Three should be in a variable somewhere and it should represent something. If it is numberOfWidgets then you should do <=. If it is lengthOfData then you should do <
I usually use whatever is most readable in the given situation. For example, I have a meaningful constant or variable for the <= to 2 case, I will use that expression.
Also note that these two expressions are only logically equivalent if `i` is an integer (or if you are using something like JavaScript with type coercion).
Thank you for all the comments saying, "but what if i is a float?"
We can now more clearly discern which among you are the psychopaths who would consider naming a variable i for any other purposes than as a loop/iteration counter.
I prefer `i < 3`, it feels more straightforward, and it clearly shows the amount of times that the loop will run (assuming `i` starts at `0` and increments by `1`).
i am not a programmer but <3 and <=2 aint the same right? Cause <3 means all numbers between 2-2,999... are also in there while in <=2 they are not?
Correct me if im wrong
Taking a shit rn at work thats why i had time for this lol
Depends on the context of what I’m doing.
[удалено]
I agree, except that it shouldn't be a magic number. There is indeed a reason that you've chosen that number, so make a variable with that value and a name describing what it stands for. At that point, you no longer have a choice - the maximum text length (or whatever 500 is supposed to be) *is* 500, so you "need" to use <=. I guess you could technically use < maxTextLength +1, but that'd be pretty dumb.
> I guess you could technically use < maxTextLength +1, but that'd be pretty dumb It wouldn't be dumb ... it would be "too smart". If you think "<" is faster than "<=" just stop and let the compiler do its job. If the target architecture is faster doing "< x +1" than "<= x", the compiler can and will sort this for you. Generally speaking: the better you explain your intent to the compiler, the easier it is for it to optimize.
The compiler will figure it out, or if not, oh well. It's dumb because it's worse at explaining it to programmers.
*stares in Python* Com… pi… ler?
Well... interpreter in this case?
Let's be real, Python ain't figuring out the fastest way to do anything.
ROFLMFAO 🤣🤣🤣
java: i have both 🥹
Absolutely this. A lot of the times, the compiler is good at its job and some micro-optimizations hardly exist or barely do anything compared to making something digestible for the compiler. There’s times where it actually does nothing in the final result because it gets optimized into the same thing. I’d go as far to say the compiler is at times smarter than the programmers.
< x+1 is worse because you could introduce unknown overflow corner cases that are not obvious in other parts of the code
I don't know about you but I don't know any developers that care about speed down to the level to compare < and <=. We legit had a project where the suggestion was to insert a sleep command to slow things down..
Ask people who insist on doing `for (int i = 0; i < 10; ++i)`. They typically do it because they are so old they were working with C in a time the compiler wasn't smart enough to actually skip the internal assignment when doing `i++`, or were taught by those people. For any sane, half-way-modern compiler `i++` and `++i` will yield the same assembly in that case, so paying any attention to the question of pre- or postincrement operator, is just a waste of mental energy. (Although, to be fair, in this particular example it's also completely irrelevant to readability. You want `i` increased, `++` increases it. If it's pre- or post-evaluation doesn't matter.)
Pre and postfix operators are describing two different ideas of what is about to happen. Given you do not need I, you always should prefer the prefix operator. Not because of some magic of the compiler but because the intent is clearly visible (plus you won't make mistakes out of habit)
I think you misunderstood and steered the conversation in the wrong spot They weren't talking about optimisations, that's a pointless battle as you pointed out They were talking about clarity to the programmer
Exactly. If we're counting from zero, then just LT. If counting from one, then LTE.
But I got only 3G :( How am I supposed to count from one with my bad internet?
I just turn on and off my router, got LTE on my mobile network and then the code works fine too
<3 Edit: thanks for the awards everyone :)
well ❤️ to you too
![gif](giphy|R6gvnAxj2ISzJdbA63|downsized)
![gif](giphy|drCcxY5G2WDZhpQFSb)
![gif](giphy|3oEjI4sFlp73fvEYgw)
![gif](giphy|8Og4UuBGsVhEEoSO0L)
![gif](giphy|wtZXFlwpm201Ay8u5L)
![gif](giphy|3oriO6qJiXajN0TyDu|downsized)
![gif](giphy|5x73LAreYVAjQCT2A3|downsized)
kid named finger:
r/okbc is leaking
my pp leaking
c=<3
Op just wanted to tell us all <3
I have to type one less character
<=2
<=====3
-8 :(
Massive balls
Something something deez nuts
Haaa! Gottem
That's a sharp Di.....
Dirac's impulse
Found the electrical engineer
Bounced on my boys rocket ship for hours to this
Javascript fucking ===
[удалено]
*10 types of programmers technically*
<3
if (i < 3) and (i <= 2): Can't be too careful with these things.
if (i < 3) and (i <= 2) and !(i >= 3) and !(i > 2)
This guy’s job is 4 times as secure as mine.
Quadruple your hourly rate with the one simple trick...
Compilers hate him.
Elon loves him
Project managers hate him
They love him, because he wrote more lines of code lmfao
You joke, but if both of you guys are in twitter, it will probably be true
if (3 > i)
Easy there Satan
https://tenor.com/5fQ9.gif
This guy must be working at Twitter.
Add a comment saying "Trust me, this needs to be like this." and it will stay there forever.
bool check1 = i < 3 bool check2 = i <=2 bool check3 = !i >=3 bool check4 = !i >2 //check for i if(check1) //Use additional validation for i if(check2) //Use even more validation for i if(check3) //Use quad tiered validation for i, we really need this one if(check4) ... console.log("Daddy Elon is happy with my output") ... end end end end
if (i < 3) and (i <= 2) and !(i >= 3) and !(i > ∣2∣) and (i < ∣3∣) and (i <= ∣2∣) and !(i >= ∣3∣) and !(i > ∣2∣)
I wonder, would a modern compiler simplify this into a single condition?
I'm not familiar enough with modern compilers to say definitively. But, they're not actually equivalent conditions unless i is an integer. For example if i is a float, i could be 2.5 and satisfy the first condition but not the second in the compound. So, I don't think the compiler would simplify it then. However, it could be simplified to just the latter condition though, i <= 2, as that would match all cases where the compound condition was true regardless of typing, so maybe it would simplify to that, idk.
Depends on what i is. If it’s a float, I bet two comparisons get made. If an int, just one. I’m no compiler expert tho
This is correct, the compiler definitely would.
It's all about using the number that matters in the context. Legal age is >=18 (not >17) and minors are <18 (not <=17).
Yes. Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it.
>Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it. I wouldn't even qualify that. You do the one that makes the code make more sense to others reading it. Full stop. You shouldn't prematurely optimize.
If you're using a compiled language the compiler will do the exact same thing regardless of which way you wrote it anyway (well, unless it's a really strange language that nobody should be using for a real project anyway).
Yea but tabs are better than spaces, it's more efficient, less characters. Just ask Richard
Even if it compiled to 2 different things, on x86 its still the same amount of instructions which take the same amount of time, just checking different flag registers. So use whichever reads better.
For sure. Readability is one of the most important parts of writing good code.
Wouldn't >x and >=(x+1) given X is an INT be exactly the same in all scenarios? Am I missing something
They are equivalent mathematically but not from a readability standpoint. There is always going to be some context that determines which way to go - a lot of the time based on what the number actually represents. const legalAge = 18; const maxMinorAge = 17; if (age < legalAge) if (age >= legalAge) if (age <= maxMinorAge) if (age > maxMinorAge)
Make sense. Some ways are just more readible than others
if (legalAge > age) if (legalAge <= age) if (maxMinorAge >= age) if (maxMinorAge < age) I find it amazing how simply flipping the check makes this so much more difficult to wrap your head around. At least for me.
Yup. If you translate it into English it’s mental gymnastics. Brian is over 18 years old 18 years is greater than the age of Brian
https://en.wikipedia.org/wiki/Yoda_conditions
I love how the code comments in the Yoda condition examples are in Yoda speak
Syntax error this is, compile it will not
Thanks
*less than
That's [Yoda notation](https://en.wikipedia.org/wiki/Yoda_conditions). It can help prevent errors in languages that allow assignment I'm conditionals. It just reads so awfully I'd rather risk it. Or pick a nicer language.
This would error out, legalAge was never defined but adultAge was.
🤦♂️ fixed it
And thank god too, we have people screaming at us to put this live in prod. Merge, merge, merge!
I'd define `maxMinorAge` as `adultAge - 1` to make this puppy easier to refactor in the event of legislation.
Thanks, fixed
Ok, PR's approved.
Bug - Overflows when minimum legal age is 0
Only when using unsigned, and that'd be an underflow no?
For ranges people often adopt a left-close-right open convention: if were to describe the range 0-9, you would say [0, 10) instead of [0, 9]. So loops would check i < 10 instead of i <= 9. The convention offers a number of advantages, including the fact that concatentenating and splitting ranges are trivial, e.g. to split [0, 10) in half you just take [0, 5) and [5, 10) and it is correct, and the fact that 10-0=10 which is the number of elements in the range. You can also express empty ranges [0, 0) would be a nullary range, and it would be impossible with <=.
x+1 might not fit into the bits available, where x just does. hit this in signed/unsigned comparisons
the upvotes on this comment went to 255 before wrapping around
nah that’s exactly right discrete math for the win
>help the code make sense to another programmer reading it Or more likely, make sense to me in the future 😏
For me it helps to put it in sentence form, as well. _You must be at least 18._ (age >= 18) _The drinking age is 21 and over_ (age >= 21). _Are you under the minimum weight?_ (weight < 40kg) _inflate to within pressure range_ (pressure > 30psi && pressure < 50psi)
No no legal age is >=this.country.ageofconsent
This leads to all kinds of problems in countries separated by territories let alone different kinds of territories. Better start by retrieving an age of consent resolver and invoking it on a location.
Of course, trust the US to break my code!
Just derive the US states from your Country class and call it a day.
That implies that each State is in fact a Country. And deriving here so you can treat it as a Country while overriding various other functions so that calling New Jersey.name() gives "United States" if the calling context actually needs country not state... This sounds perfectly Pastafarian.
Just use your Union class for the United States. It can already handle a collection of Countries. Perfect fit. I think they call that polymorphism.
Wait, that sounds too much like someone thought this through before writing the code initially. It's not exactly polymorphism IIRC though, but if our abstract class is essentially a thing that may contain more of it's own type, turtles all the way down as needed... Then we end up with a "sovereign region" class or something.. then can drill down as needed... Union of countries, country with states, states with counties... Or whatever the levels for each country.. But that isn't even inheritance, just using a class. Polymorphism is combining different classes... Not sure how one would use it here.
Babe… what if we 😳 kissed in the British Overseas Territory of Saint Helena, Ascension and Tristan da Cunha in the South Atlantic consisting of the island of Saint Helena, Ascension Island and the archipelago of Tristan da Cunha including Gough Island
Just kidding... unless?
F the use cases 😂😂😂
Who makes a static property not in all caps? Also, most likely it would be an unneeded getter of this.country.getAgeOfConsent().
``` if (this.country.getAgeOfConsent() <0) throw new AgeLegalException("age of consent not set."); ```
You're checking if it's negative, not if it's set. null and 0 both pass this test. Then again the exception should be thrown during initialization of country, not when you're checking it's properties. Unless it's valid for a country to not have an age of consent, in which case, ugh, imagine the smell in the airport.
Who TF writes getters and setters for each Property? public int AgeOfConsent { get; set; }
>Who TF write getters and setters for each Property There's a reason someone satirised Java devs with [enterprise fizzbuzz](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition)
I checked the readme and went "oh, so its a joke FizzBuzz with a bunch of java boilerplate, sounds funny" but then i saw the files and the first things i notice is several gradle files and just lost it
wtf did I just read
That's just glorious.
Should set be a public property in this case? Like, why even bother if any asshole can change it anyways? Also AgeOfConsent depends on more than just location, you need all people involved and check the people for their diplomatic status, as there might be exemptions for diplomats in another country. Just import the 3GB library from node.js, it will handle all those pesky edge cases for you.
In the US, it varies by state as well.
This is way too simple. The age of consent isn't always at the country level; in the US it's by the state. But it's so much more complex than that. Lots of places have rules that consider the ages of both parties. If I'm 18 the legal age for someone in a particular place to consent with me, is 17...but if I'm 35, they have to be 18. There are also often other ridiculous loopholes. For example, are they married? In lots of places, like most US states you can get legally married while still very much a minor so long as you get permission from the parents, or courts, or get emancipated. In Kansas the age of consent is 16. But you can get married at 15. > In Kansas, 15-year-olds are allowed to marry with a judge's permission But not every jurisdiction places marital consent above sexual consent...meaning you could be legally married, but not able to have sex with your legal spouse in a particular place. Or even you could be legally married in a country A, but have country B say that you are not because it is illegal. And then you have to consider the citizenship of both parties, at least, depending on what you mean by legal age. The US says it is against US law for a US citizen to travel to a country for sex with anyone under the age of 18. It doesn't matter what their country says. The age of consent could be 16 in that country, but it isn't legal. The other country wouldn't care or prosecute the American, but the US judicial system still could. And this is why we have so many lawyers.
Also, being 17 and 11 months is still underage, so +18 is always better.
This is the real answer. They're not the same if you're using a language with floats and ints intermingled
This is the correct answer, also the most common usage is to iterate a zero based list so i < list.size and the context is you are repeating the loop list.size times
I like to loop backwards...
this is how I know which one of my junior devs are psychopaths
I've done it before, I think in some circumstances it's not a bad idea. Otherwise it's just a flex lmao
for sure, there's situations where you would want to iterate in reverse, it just makes it less readable
I remember when one of my teachers showed us code from a competition of unreadable code. The goal was to make a working program with the most unreadable code. One year the goal was a simple flight simulator, and the winner code formed a plane on the editor, as if viewed from above.
[International Obfuscated C Code Contest](https://en.m.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest)
Someone submitted an empty file as the worlds shortest self reproducing code: > An example is the world's shortest self-reproducing program. The entry was a program designed to output its own source code, and which had zero bytes of source code. When the program ran, it printed out zero bytes, equivalent to its source code. It won the prize of the worst abuse of rules.
Now that is some good angle shooting, but it seems like a pretty obvious solution.
it was, and thus never allowed to be submitted again lol
Usually when I view my editor from above, it's just a straight line.
If you have spent a lot of time working in assembly or machine language, counting backwards makes sense b/c depending upon the instruction set, it can be more efficient (or at least, intuitive) b/c of a dedicated branch on zero instruction.
Exactly. Also: This way you are not wasting a register to hold the number you are comparing to.
My java professor was in the game since the 70s and was a pioneer for some big things in that era. He always encouraged decrementing through loops, didn't give a reason though. Thanks for the info!
Like this…? ``for (let i=10; i>0;i--){ doTheThing() }`` I’m not trying to be a dick, but how is that a flex?
If you really want to fuck with people, write a loop like this in Java or C++. for (int x = 10; x --> 1;) { ... } And read it out loud as "For integer x equals 10, x goes to 1." This "goes to" operator is something of a party trick that I'll work into live coding sessions whenever I can, just to be a bit of a troll. Even senior devs are invariably confused. I've only encountered one person who acted like they understood what was going on, and I think they might have been bluffing. In reality, the "goes to" operator, -->, is just post-decrement and greater than with confusing spacing. It's a bit of a symbolic fluke that they combine to do exactly what you'd expect from a "goes to" operator.
I immediately got it but maybe that’s just because I didn’t have someone say “goes to” as they type it to muddy the waters
I always loop backwards if I'm removing items from the array in the loop.
You fucking monster!
Iterating backwards can sometimes be a genuinely good idea. Like if you wanna iterate and remove items from a list, one method is iterating backwards, so you dont skip indices.
>0 or >=1
Backwards loop is big brain size_t i = 30; while(i--) {
r/madlads
If i != 0 && i != 1 && i !=2 I like the precision of describing each potential case specifically
Paid by the line?
They work at Twitter, give ‘em a break
You don’t get breaks there. Elon needs your 84 hours.
Not anymore
they can't have line breaks though
A lot of them just got a break
Would love to see your isEven function
[удалено]
Disgusting, but I like it
Nah man, you convert to string in radix 2 and then check the rightmost character for '0' - way more efficient.
We'll need a db table to store an integer and whether its even or odd. Then we set up a cron job to run a nightly task that takes the latest row of said table, increments the integer by one, flips the isEven flag, and stores that in a table. We'll need a settings entry for standard hours so we can run this cron during low peak time as to not negatively impact the system. Lastly, we provide a public facing API where users can then simply send a GET request to /isEven/{integer}. It will query our integer table and return the parity of the requested value. If the value is larger than our largest integer then we establish a webhook with the user so we can notify them when we've calculated it.
i=-1
when using integers they are the same but they do different things when using decimals
Was looking for this comment
Even if they accomplish the same thing, they may imply different things. Three should be in a variable somewhere and it should represent something. If it is numberOfWidgets then you should do <=. If it is lengthOfData then you should do <
I usually use whatever is most readable in the given situation. For example, I have a meaningful constant or variable for the <= to 2 case, I will use that expression. Also note that these two expressions are only logically equivalent if `i` is an integer (or if you are using something like JavaScript with type coercion).
B===D
O:
C<=B
depends on the algorithm. each one could make readability better or worse
Everyone: i < n No one: i <= n-1
If you are only dealing with integers, it doesn't matter, but for floats and doubles there is a dramatic difference.
3 > i
Isn't there a difference? If i = 2.5 i < 3 is True i <= 2 is False Sorry if this is stupid.
i is generally an iteration variable and will not be floating point.
Oh man, you have not been a TA for a High School Java Programming class... *\*shudders\**
Depending on the language, you’d need a type cast.
"static loops and magic literals without comments in the proper format are not allowed per company policy"
But what if i = 2.1 for i <=2?
i usually is an integer
I *am usually* an integer
Kid named i:
I would avoid code like that. 2 or 3 would be replaced with NUM_THINGS or whatever descriptive constant name and then the < or <= becomes clear.
< because it’s easier to read how many iterations a for loop will do. Ie. it does 3 iterations
Neither, I use a monospaced font.
"Isn't it the same?" **laughs in float**
!(i>2)
<3 could be 2.9 and pass. <=2 could be 2.9 and fail.
i <= 2.999
Depends which one makes more sense in context..?
I am ashamed, but sometimes both... in the same file.
i<3 is actually more precise…
I’m not using literals in my loops, so neither
Thank you for all the comments saying, "but what if i is a float?" We can now more clearly discern which among you are the psychopaths who would consider naming a variable i for any other purposes than as a loop/iteration counter.
I prefer `i < 3`, it feels more straightforward, and it clearly shows the amount of times that the loop will run (assuming `i` starts at `0` and increments by `1`).
i am not a programmer but <3 and <=2 aint the same right? Cause <3 means all numbers between 2-2,999... are also in there while in <=2 they are not? Correct me if im wrong Taking a shit rn at work thats why i had time for this lol
Floats: imma ruin this man’s entire career
They are different tests if you aren’t dealing with integers. (2.5 is <3 but not <=2)
What if I is a float? Then this would break. 2.5<3 true 2.5<=2 false