55502f40dc8b7c769880b10874abc9d0

Alright, so for out class, we have to write a program that produces random permutations of the numbers 1-10. To do this, our teacher wants us to make two arrays, one with the numbers 1-10. Then pick one of those numbers at random, remove it, and append it to the second array. We need to implement a class called Permutation to do this. I figured out the code, but there is a small error in it which I don't understand. If anyone can help me, I'd appreciate it! Thanks! Code is below and I point out the error in comment.

import java.util.ArrayList;
import java.util.Random;

public class Permutation
{
	public Permutation(int x)
	{
		size = x;
	}

	public Permutation getNumber()
	{
		ArrayList<Integer> empty=new ArrayList<Integer>();
			for(int i=1; i<=size; i++)
				empty.add(i);

		ArrayList<Integer> full=new ArrayList<Integer>();

		for(int j=0; j<size; j++)
		{
			int num=generator.nextInt(empty.size());

			full.add(empty.get(num));

			empty.remove(num);
		}
		return full; //error is here, my compiler says incompatible types
	}
private int size;
private Random generator = new Random();
}

Refactorings

No refactoring yet !

F9a9ba6663645458aa8630157ed5e71e

Ants

November 7, 2009, November 07, 2009 04:11, permalink

1 rating. Login to rate!

Well... line 11 says you are returning an object that is a Permutation, but in line 27 you are returning full, which is an ArrayList<Integer> based on line 17.

55502f40dc8b7c769880b10874abc9d0

ravi-gill.myopenid.com

October 21, 2010, October 21, 2010 15:44, permalink

1 rating. Login to rate!
import java.util.ArrayList;
import java.util.Random;

public class Permutation{

        private int size;
        private Random generator = new Random();

        public static void main(String[] args){
                Permutation p = new Permutation(10);
                ArrayList<Integer> mutations = p.getNumber();
                for(Integer i:mutations){
                        System.out.println(i);
                }
        }

        public Permutation(int x){
                size = x;
        }

        public ArrayList<Integer> getNumber(){

                ArrayList<Integer> empty=new ArrayList<Integer>();

                        for(int i=1; i<=size; i++)
                                empty.add(i);
 
               ArrayList<Integer> full=new ArrayList<Integer>();
                
                for(int j=0; j<size; j++){
                        int num=generator.nextInt(empty.size());
                        full.add(empty.get(num));
                        empty.remove(num);
                }

                return full; 
        }

}

Your refactoring





Format Copy from initial code

or Cancel