How to set a range of values in an array?

edited April 2017 in Questions about Code

I have an array float[] positionx = new float[100]. I want to be able to add 1 to all of the values in that array from 0 to a certain variable (let's say its value is 50). I don't want to do positionx[0] = positionx[0] + 1, positionx[1] = positionx[1] + 1, and so on all the way to 50. Is there a simpler way to do it? Something like positionx[0 through X] = positionx[0 through X] + 1

Answers

  • for loop?

    Kf

  • edited April 2017

    Could you give an example please? I have no idea how to use a for loop here.

    Edit: I see how it could be done but wouldn't using a for loop mean adding 1 to each of them one after another? I need them all to add 1 at the same moment.

  • Answer ✓

    Use a for loop. Yes, they are increase one after another, but this happens so fast that it might as well happen at the same moment. Example:

    int values[] = new int[10];
    
    void setup(){
      size(220,220);
    }
    
    void draw(){
      background(0);
      for( int i = 0; i < 10; i++){
        text("" + values[i], 10 + 20 * i, 20+ 20*i);
      }
    }
    
    void mousePressed(){
      for( int i = 0; i < 5; i++){
        values[i]++;
      }
    }
    
  • edited April 2017

    This is perfect, thank you.

  • edited April 2017
    // forum.Processing.org/two/discussion/21865/how-to-set-a-range-of-values-in-an-array
    // GoToLoop (2017-Apr-06)
    
    final float[] floats = new float[10];
    
    void setup() {
      println(incArr(0, 5, floats));
      exit();
    }
    
    @ SafeVarargs static final float[] incArr(int initIdx, int endIdx, final float... arr) {
      if (arr == null) return null;
    
      initIdx = constrain(initIdx, 0, arr.length);
      endIdx = endIdx >= 0? constrain(endIdx, initIdx, arr.length) : arr.length;
    
      for (int i = initIdx; i < endIdx; ++arr[i++]);
    
      return arr;
    }
    
  • this happens so fast that it might as well happen at the same moment

    Importantly, it also happens before the next time that draw() refreshes the screen -- so even if it was slow (and it is blazing fast) nothing will every be drawn based only some array members in the loop being updated. It will be none or all.

Sign In or Register to comment.