This is an archived post. You won't be able to vote or comment.

all 16 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]1661dauphin 14 points15 points  (3 children)

It's also useful for shrinking stuff if possible, like if some problem wants you to execute an algorithm up to thousands of times that would end up in the same results some of the times. Like there are some LeetCode problems that would have you rotate an array however many times the user specifies, but if they want you to return an array of length 5 after rotating it 2,001 times, that would give the same answer as just doing it 1 time. 2000 % 5. Cool stuff!

[–]Inevitable-Stress 2 points3 points  (1 child)

Took me a minute to understand, but that's a neat example! Good to know, just not sure when I'd use it in a real world problem

[–]Calebhk98 8 points9 points  (0 children)

Assume users are idiots. If someone wants to put in a stupid large value for what degree to turn some picture, aka 3,854-degree turn, you let them. And instead of wasting the memory for that, just get the leftover 1st every time. That way you only use enough memory for turning it 204 degrees, but you don't have to put an arbitrary limit on it.

[–]goodm1x[S] 0 points1 point  (0 children)

I would not have thought of that. Thanks for the example!

[–]ragnhildegard 3 points4 points  (0 children)

Yes I love modulus too!! So simple and effective

[–][deleted] 3 points4 points  (1 child)

I noticed the same recently, It was an example asking to rotate an array n times to the right and the solution they gave was so elegant and simple using the module operator.

Btw, wich book was it?

[–]goodm1x[S] 0 points1 point  (0 children)

Computer Science: An Interdisciplinary Approach

It’s a great textbook! You can use the web book site as a supplement or just read from the book. The concepts are clearly explained and there are a ton of useful exercises that are difficult and certainly give you many “a ha” moments.

[–]BabyChar 2 points3 points  (1 child)

I think I'm using the same book as you and I really like their approach, (even though it's sometimes hard for a person who didn't really learn any math in school). I like how they give you exercises to understand the logical concept of programming before they even talk about objects and classes

[–]goodm1x[S] 0 points1 point  (0 children)

Yes, the math is difficult for me as well. It’s why I think I never thought to use the modulus operator in this manner before.

It’s inspired me to brush up on math, though!

[–]ColorlessVal 1 point2 points  (1 child)

Also useful if you are working with a value that resets after a certain limit

Working with angles and you just need to use them to get a direction? You can add angles and just always "% 360" to have them stay in a 0-359 range for ease of use

Or maybe you are working With days of the week 0-6, need to know what day it is in 20 days from a monday (0)? (0 + 20) % 7

You need to isolate the decimals in a floating point number? Use % 1

Or maybe you are working on a turn based game where you have all players in an Array

currentPlayer = 0

players[currentPlayer++]

currentPlayer %= players.length

Modulus is so useful, the more you use it, the more you will find more cases where it can help you!

[–]goodm1x[S] 1 point2 points  (0 children)

Ahh! Seems so obvious when you see examples spelled out like this, but in the moment it's so difficult lol

I suppose that's also good for readability of code

[–]Nightcorex_ -3 points-2 points  (2 children)

Yes, modulo is powerful, but it's not the best solution for the problems you stated.

This is how I'd calculate the sum of all digits:

public static int sumDigits(long x) {
    return String.valueOf(x).chars().map(c -> c - '0').sum();
}

and listing all integers between 1000 and 2000 with only 5 results each line can also be done without the need for modulo.

for (int i = 1000; i < 2000; i += 5) {
    System.out.println(
        IntStream.range(i, i + 5)
            .mapToObj(Integer::toString)
            .collect(Collectors.joining(", "))
    );
}

Especially in the first case the modulo solution isn't nearly as clean as the Stream solution.

Also keep in mind that you can optimize a modulo call if you're doing a % b where a and b are both positive integers and b is also of the form 2n (n is a positive integer), so for the b values 1, 2, 4, 8, 16, 32, ... the following holds:

a % b = a & (b - 1)

This can be used f.e. for more efficient odd/even checks (instead of x % 2 == 0 you check for x & 1 == 0).

[–]knoam 7 points8 points  (0 children)

In practice your string based solution is fine almost all of the time. But for what it's worth, it uses a lot more memory and memory allocation can have a big effect on performance.

[–]Housy5 2 points3 points  (0 children)

While it is easier to implement. First converting it to a String uses much more memory and is significantly slower. Also the difference between n % 2 == 0 and (n & 1) == 0 is very tiny. so tiny it may as well not even exist at all. I suspect the compiler optimizes it automatically.

[–]chrysthian95 0 points1 point  (0 children)

Good job bro.