Simplifying lines of code into 1 line?

edited February 2017 in Questions about Code

Right now my code is something like this, and I was wondering if there's a way to shorten this code

if (score >10)speed += 5;
if (score >20)speed += 5;
if (score >30)speed += 5;
Tagged:

Answers

  • why?

    it's perfectly clear as it is.

  • Answer ✓
    speed += 5 * (score / 10); // NB integer division
    

    score is 11, score / 10 = 1 so add 5 * 1

    score is 24, score / 10 = 2 so add 5 * 2...

    that has no bounds checking on it so 60 will add 30 to the original speed etc

  • Answer ✓

    if (score < 40)speed += 5 * int((score-1)/10);

    For 0 to 10, inclusive, adds nothing
    For 11 to 20, inclusive, adds 5
    For 21 to 30, inclusive, adds 10
    For 31 to 40, inclusive, adds 15

    int score;
    for (score=0; score<45; score++) {
      int speed=0;
      if (score < 40)speed += 5 * int((score-1)/10);
    
      println(score+" "+speed);
    }
    

    I assume scores is an integer. Note compact code sacrifices clarity which will make it really difficult for maintenance.

    Kf

  • edited February 2017 Answer ✓

    if(score%10==0) speed+=5;

    initially 3 if-lines won't work as expected btw

  • Answer ✓

    mine needs to be (score - 1) / 10 rather than score / 10

    kfrajer noticed the conditions were strictly greater than, mine is actually >=

  • once the score is 10, it rapidly starts increasing for all of your codes, how do i only make it increase once every 10 pts

  • Answer ✓

    If you look at my code with %

    Don't call it in draw()

    Call it only once every time the score gets increased

  • Personally, I'd say don't try to make the speed code as compact as possible. Instead, make it as easy to read and change as possible. To me that means isolating the if statements with else so that each sets its own speed based on the current score.

    int score, speed;
    void setup(){
      frameRate(1);
    }
    void draw(){
      score = (int)(40*random(1));
      speedUp(score);
      println(score, speed);
    }
    
    void speedUp(int score){
      if(score >30) speed += 15;
      else if(score >20) speed += 10;
      else if(score >10) speed += 5;
    }
    
  • Answer ✓
    speed+=(score>10?5:0)+(score>20?5:0)+(score>30?5:0)
    
  • edited February 2017 Answer ✓

    Nice 1 @TfGuy44! :-bd Here's mine as well: >:) speed += 5 * min(3, score/10);

    P.S.: Oops! Just looked the 1st replies and my attempt is almost the same as theirs. 8-X

Sign In or Register to comment.