Say I have an array of 8 elements: old_array = [6, 3, 0, 12, 14, 2, 10, 5]
and I start at the last element old_array[7]=5
. I want to use the new element as the index of the next element I want to copy from old_array
to new_array
.
Result is new_array = [0,2,5]
.
Here is some pseudocode to do this:
old_array = [6, 3, 0, 12, 14, 2, 10, 5]
i=7
len=0
while i>0:
len+=1
i=old_array[i]
i=7
while i>0:
new_array[len]=old_array[i]
len-=1
i=old_array[i]
This method does work, however it does not seem efficient since it uses repeated code; one loop to get the length of the new array and another to copy the array. My question is there a better way of doing this?
Edit: I am expecting some pseudocode that would do this better than my current code. Note that the array can be arbritrary, except there will eventually be a 0 element and there is a way to get to it from the last element. Also we know the last index in the old array. The preferred language is Python, but I am ok with other languages.
If this question has been answered before or can be improved kindly point me to it. Thank you.