How to make array values MOVE UP

How do i make values in an array move up, everytime the array receives a new value?
I want to have the newest incoming variable always to be in the 1st array slot. The rest should move up to the next slot.

Example:

[0] 550
[1] 240
[2] 160
[3]

when a new value (830) will be added

[0] 830
[1] 550
[2] 240
[3] 160

1 Like

You can use a “for” loop. Start from the end (length -1) and work to the beginning.

1 Like

check out the array append method.

Expands an array by one element and adds data to the new position. The datatype of the element parameter must be the same as the datatype of the array.

https://processing.org/reference/append_.html

2 Likes

If you are expanding your array, you should consider using IntList or ArrayList. You can add to the end of the list and access the first element right at the end of the list at the position defined by IntList.size()-1.

Kf

2 Likes

See this post.
https://forum.processing.org/one/topic/array-pop-push.html

2 Likes

Performance-wise, pushing new elements to the head/top is the slowest, b/c it demands that all the others already inside the container to have their indices right-shifted in order to make room! :japanese_goblin:

Therefore, it’s much preferable to push new elements to the tail/bottom of a container, so there’s no index-shifting. :ok_hand:

Given those values you’re using are all int numbers, best container for them would be the IntList: :face_with_monocle:

Use its append() method in order to push a new int value to its tail: :sunglasses:

2 Likes

However, if you don’t mind the performance hit, and prefer to keep on pushing new values to the head/top, you should instead go w/ the container ArrayDeque, and use it as a Deque: :stuck_out_tongue:

  1. https://Docs.Oracle.com/javase/10/docs/api/java/util/ArrayDeque.html
  2. https://Docs.Oracle.com/javase/10/docs/api/java/util/Deque.html

Use its method addFirst() to push to the head/top and pollLast() to pop from the tail/bottom: :money_mouth_face:

  1. https://Docs.Oracle.com/javase/10/docs/api/java/util/Deque.html#addFirst(E)
  2. https://Docs.Oracle.com/javase/10/docs/api/java/util/Deque.html#pollLast()

Here’s a demo I just did for it: :cowboy_hat_face:

/**
 * ArrayDeque's addFirst() (v1.0)
 * GoToLoop (2018/Jun/23)
 *
 * https://Discourse.Processing.org/t/
 * how-to-make-array-values-move-up/1184/7
 */

import java.util.Deque;
import java.util.ArrayDeque;

final Deque<Integer> ints = new ArrayDeque<Integer>();

void setup() {
  noLoop();
}

void draw() {
  background((color) random(#000000));
  println(ints, ENTER);
}

void mousePressed() {
  if (mouseButton == LEFT) ints.addFirst((int) random(1000));
  else println("Removed oldest:", ints.pollLast());
  redraw = true;
}
3 Likes

@GoToLoop please go easy with the emojis

1 Like

Looks pretty useful, thanks

1 Like