-2

I want to get four images from a array but I need same position images from other array as like in example.

images = new int[] {
    R.drawable.a, R.drawable.f, R.drawable.k,
    R.drawable.u, R.drawable.y, R.drawable.w, R.drawable.t, R.drawable.g,
    R.drawable.b, R.drawable.o
};

images2 = new int[] {
    R.drawable.apple, R.drawable.fan,
    R.drawable.kite, R.drawable.umbrells,
    R.drawable.yark,R.drawable.watch, R.drawable.tap,
    R.drawable.gun, R.drawable.ball, R.drawable.orange
};

I have now 2 arrays of 10 pictures. Now I need 5 images from same both arrays but randomly and same corresponding 5 images from other array.

As like I need

array1={R.drawable.a, R.drawable.w,R.drawable.o,R.drawable.g}

and same correspondence .

array2 = {R.drawable.apple, R.drawable.watch,R.drawable.orange,R.drawable.gun}
J. Steen
  • 15,470
  • 15
  • 56
  • 63
Android
  • 171
  • 1
  • 2
  • 11

2 Answers2

0

1) Make a collection of the numbers {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

2) Shuffle the collection ( http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle(java.util.List) )

Now you have something like {7, 9, 5, 2, 4, 3, 1, 0, 8}

3) Use the first five numbers as your five indexes - they will be random and unique from each other, and reusable for both arrays.

In this case we'd use 7, 9, 5, 2 and 4 for both arrays.

By the way, if you want to implement random shuffling yourself (for instance if you want to shuffle an array rather than a collection), refer to Random shuffling of an array

Community
  • 1
  • 1
Patashu
  • 21,443
  • 3
  • 45
  • 53
0

this is your solution

ArrayList<Integer> list=new ArrayList<Integer>();
        ArrayList<Integer> list1=new ArrayList<Integer>();
        Random r1=new Random();
        int[] images = new int[] {R.drawable.a, R.drawable.f, R.drawable.k,
                R.drawable.u, R.drawable.y, R.drawable.w, R.drawable.t, R.drawable.g,
                R.drawable.b, R.drawable.o};
        int[] images2 = new int[] {  R.drawable.apple, R.drawable.fan,
                R.drawable.kite, R.drawable.umbrells,
                R.drawable.yark,R.drawable.watch, R.drawable.tap,
                R.drawable.gun, R.drawable.ball, R.drawable.orange};
        for(int i=0;i<4;i++)
        {
            while(true)
            {
                int next=r1.nextInt(10)+1;
                if(!list.contains(next))
                {
                list.add(images[next]);
                list1.add(images2[next]);
                break;
                }
            }
        }
        array1 = convertIntegers(list);
        array2 = convertIntegers(list1);

this is your convert function

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}
stackoverflow
  • 2,320
  • 3
  • 17
  • 21