2

I have a simple problem and I need a fast way to achieve that. Suppose I have two columns like

1 6 
3 5
5 3 

As you see, element 3, and 5 are there in the 2nd column, I would like to generate a new random elements in column one, such that there will be no elements in the 2nd column matched. The elements can be from 1 ->12

My approach : I have added all the elements in the 2nd column to a hash set, then I search for the elements in column one, and check if they are in the hash set, if that's true, try to generate a new random element.

I have another idea is to visualize the problem as a 1D array, remove the duplicates,..etc., but I don't want to modify any elements in the 2nd Array.

Trying
  • 14,004
  • 9
  • 70
  • 110
andre_lamothe
  • 2,171
  • 2
  • 41
  • 74

4 Answers4

0
  1. Put the column2 values to HashSet.

  2. Just use (Math.random() * 12)+1 which will generate number form 1 to 12.

  3. Now search whether the number generated is present in set if present in set than regenerate i.e. go to step 2, else done.

Hope it helps.

EDIT

O(1)

I am taking just a a small sample i.e. 5

  1. first create an array which contains 1 to 5 than a [] = {1, 2, 3, 4, 5}
  2. Now try to generate a random number from 1 to 5 (here you are generating an index of the array) , lets suppose it generates 2 than replace last element to 2 . So now the array will be a[] = {1, 5, 3, 4} and decrement the index value.
  3. now you will have to generate a random number from 1 to 4. Lets suppose 3 than swap 3 and last value. So array is {1, 5, 4}. Decrement the index i.e. now 3.
Trying
  • 14,004
  • 9
  • 70
  • 110
0

I think this is a rather straight forward solution

    Random r = new Random();
    List<Integer> numbers = new ArrayList<>(Arrays.asList(new Integer[] {
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }));

    Integer[] colOne = new Integer[] { 6, 5, 3 };
    numbers.removeAll(Arrays.asList(colOne));

    int notFoundInColOne = numbers.get(r.nextInt(numbers.size()));

Essentially we create our range, remove the elements in the range that are also in the column, then pick a random element from what remains of our range.

arynaq
  • 6,710
  • 9
  • 44
  • 74
0

I think this approach will work for you: For each number from 1 to 12, if the number is not in column 2 then add it to a list. While column 1 is not filled, randomly choose an item from the list and remove it, then add it to column 1.

Duncan
  • 984
  • 10
  • 20
0

You can use these steps: 1. Create an array. 2. Fill it with minimum value to maximum value. 3. Suffle the array. Read array sequentially.

Use Fisher–Yates shuffle Algorithm for suffle

dkumar
  • 33
  • 4