lundi 16 novembre 2015

Java Create a a Randomized ArrayList

I have been having trouble with this one problem.

I need to write a program that produces random permutations of the numbers 1 to 10.

My strategy to approach this would be to:

To generate a random permutation, you need to fill an ArrayList with the numbers 1 to 10 so that no two entries of the array have the same contents. I want to avoid calling Random.nextInt(). and instead implement a smarter method by making a second ArrayList and filling it with the numbers 1 to 10. Then picking one of those at random, removing it, and appending it to the permutation ArrayList. Repeat ten times.

Here is what I have basically:

import java.util.ArrayList;
import java.util.Random;
public class P4_Icel_Murad_Permutations
{

public static void main(String[] args){
   ArrayList <Integer> myArrayList = new ArrayList <Integer> ();
   P4_Icel_Murad_Permutations obj = new P4_Icel_Murad_Permutations();
   obj.perma(10,1,10);
}
static java.lang.Object[] perma(int n, int a, int b){
    ArrayList <Integer> myArrayList = new ArrayList <Integer> ();
    ArrayList <Integer> randomized = new ArrayList <Integer> ();  

     randomized.add(new Integer(1));
     randomized.add(new Integer(2));
     randomized.add(new Integer(3));
     randomized.add(new Integer(4));
     randomized.add(new Integer(5));
     randomized.add(new Integer(6));
     randomized.add(new Integer(7));
     randomized.add(new Integer(8));
     randomized.add(new Integer(9));
     randomized.add(new Integer(10));
     for(Integer N: randomized){
         Random r = new Random();
        randomized.remove(r);
        myArrayList.add(N);
    }

}

}

my problem is that I am not quite sure how I can take from the other list by removing and adding a number to the myArrayList. I cannot seem to use r since it is a primitive type, and I don't know how to make an object for the random class.

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire