Moving an array in Java

2

I have an array with integers

int[] intColorArray = new int[3];

I would like to obtain a different value sequentially of the array but if you reach the end that you get back from the beginning, that is

0,1,2,0,1,2,0,1,2...

I had thought of doing a side shift to the left and the value put it back to the end and so only get the position 0 would return the color sequentially.

I can not find in java how to make a left shift in an array

    
asked by Webserveis 12.08.2017 в 21:16
source

1 answer

2

The idea would be if the index sought is greater than the size of the array, make the difference: n=n-array.length; until it is no longer greater.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int [] a={1,2,3,4};
        secuenceGetID(a,6);
    }

    public static int secuenceGetID(int[] array, int n){

        while(n>=array.length){
            n=n-array.length;

        }
        System.out.println(array[n]);
        return array[n];

    }
}

now I present another solution, by congruence of numbers , that is:

26 es congruente a 11 con modulo 5
26%5==1    y      11%5==1

according to this analogy, it would only be enough with: n=n%array.length ;

ejemplo:  * n=5 es el indice a buscar
          * mi array es {1,2,3,4}, con tam de 3
          entonces 5%3=2 el resultado sera 3

the serious code:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int [] a={1,2,3,4};
        secuenceGetID(a,6);
    }

    public static int secuenceGetID(int[] array, int n){

            n=n%array.length;

        System.out.println(array[n]);
        return array[n];

    }
}
    
answered by 13.08.2017 / 00:10
source