A
A
Alexey Medvedev2015-07-26 22:12:07
Java
Alexey Medvedev, 2015-07-26 22:12:07

How to match an element from one array to an element of another array?

There are several phrases. When the button was pressed, it initially generated a random number in a given range equal to the number of phrases, and assigned its own text to each number. But I need no repetition. I found Google, many solutions from SO to generate random numbers without repetitions did not help me, without proper experience I could not cope with them.
As a result, I liked this option more, using JavaScript as an example , and created an array of type String with my own phrases.
I began to use the code from the example on one site:

// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar) {
  Random rnd = new Random();
  for (int i = ar.length - 1; i > 0; i--) {
    int index = rnd.nextInt(i + 1);
    // Simple swap
    int a = ar[index];
    ar[index] = ar[i];
    ar[i] = a;
  }
}

// создадим массив и перемешаем его
int[] mSolutionArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
    13, 14 };
shuffleArray(mSolutionArray);

Log.i("Array", Arrays.toString(mSolutionArray));

Shuffles only an array of type int.
The first thing that came to mind was a stupid (they don't refuse the truth) idea to make a second int array, mix it up.
I made this trick:
int mSolutionArray[] = { 0, 1, 2, 3 };

    String rnd[] = {
             getResources().getString(R.string.random0),
             getResources().getString(R.string.random1),
             getResources().getString(R.string.random2),
             getResources().getString(R.string.random3),
    };

But now I don't know how I can assign, for example, the number "1" from the int array to the random1 string from the second array. And is it worth doing it at all? How stupid is that?
Or is it possible to somehow mix the array of type String?
Perhaps suggest something better?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abs0lut, 2015-07-26
@RockBearLTD

Shuffles only an array of type int.

By changing the type of a pair of variables, you can also mix String[] . Or use generics.
static void shuffleArray(String[] ar) {
  		Random rnd = new Random();
  		for (int i = ar.length - 1; i > 0; i--) {
    		int index = rnd.nextInt(i + 1);
    		// Simple swap
    		String a = ar[index];
    		ar[index] = ar[i];
    		ar[i] = a;
  		}
}

To be honest, I still don't understand what the goal is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question