0

I have a programming assignment where I am tasked with the following:

I am taking two int values (x and y) and creating two different arrays: the first (size x) will print an array starting from x and descending down to 1. The second (size y) will take random values from the first array (size x) and store it in its own array. I will then print out the second array. However, the second array cannot have any repeating values. For example, if the array was size 10, it could not have two of the same digit within its 10 individual indexes. I am attempting to store unique elements in my second array by creating two arrays, one boolean to check for unique elements and another one to store those unique elements. Here is my code:

/*
* user will enter desired size x for first array labeled arr_1
* arr_1 will contain values descending from x down to 1
* user will enter desired size y for second array labeled arr_2
* arr_2 will contain random values taken from arr_1 w/o repeating numbers
*/

import java.util.Arrays;
// import java.util.Arrays;
import java.util.Random;
// import java.util.Scanner;
public class Prog1B  
{
    public static void main(String[] args)
    {
        System.out.println("Program 1B, Christopher Moussa, masc1574");
        // Scanner scnr = new Scanner(System.in); 
        int x = 20;
        int v = x;
        int[] arr_1 = new int[x];

        for (int i = x-1; i >= 0; i--)
        {
            arr_1[i] = v;   // System.out.print(i+1 + " "); prints 20, 19, ... , 1
            v--;            // System.out.print(arr_1[i] + " "); prints 20, 19, ... , 1
        }
        // int[] b = unique(arr_1);
        System.out.println(Arrays.toString(unique(arr_1)));
    }

    public static int[] unique (int[] n)
    {
        boolean[] seen = new boolean[n.length];
        int[] unique = new int[n.length];
        Random rand = new Random(123L);
        for (int i = 0; i < n.length; i++)
        {
            int index = rand.nextInt(n.length);
            while (seen[index])
            {
                index = rand.nextInt(n.length);
            }
            unique[i] = n[index];
        }
        return unique;
    }



}

The code compiles and runs, but it still prints out an array with repeating values. I am trying to write the program so that it does not print out an array with repeating values, only unique values. Do you have any suggestions as to where the problem lies? I am pretty sure it lies within the "unique" method, more specifically when the boolean array is checking for unique values (I noticed while trying to debug that even if the random index it generated was not unique, it still skipped the while condition and printed it out). I am a beginning programmer (a freshman at San Diego State studying computer science) and any feedback/advice will be greatly appreciated. Thanks you very much.

  • What is the purpose of using random indexes? – diziaq Feb 10 '16 at 03:54
  • Why not use a set instead? Sets cannot have duplicates. – JimLohse Feb 10 '16 at 04:00
  • Everyone this is not Chegg, don't solve the problem for Christopher, lead him in the right direction per http://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions – JimLohse Feb 10 '16 at 04:10
  • @JimLohse How do you suggest that we "lead him in the right direction"? He had a simple problem and we showed him what was wrong. He simply made a mistake which doesn't really reflect the quality of his approach. – Benjamin Lowry Feb 10 '16 at 04:15
  • @Benjamin If you read the link I posted you will see how, I didn't write the policy I just try to follow it :) – JimLohse Feb 10 '16 at 04:17
  • @BenjaminLowry for example you could have provided a plain-English explanation and some sample code but not directly provided the answer. Then come back later and edit in the correct answer -- per the linked policy – JimLohse Feb 10 '16 at 04:19

4 Answers4

2

You need to even set your array seen[index] = true;

public static int[] unique (int[] n)
    {
        boolean[] seen = new boolean[n.length];
        int[] unique = new int[n.length];
        Random rand = new Random(123L);
        for (int i = 0; i < n.length; i++)
        {
            int index = rand.nextInt(n.length);
            while (seen[index])
            {
                index = rand.nextInt(n.length);
            }
            unique[i] = n[index];
            seen[index] = true;
        }
        return unique;
    }
Sanchita
  • 84
  • 3
  • Changed my DV to UV but per cmnt on Benjamin's answer, "It's usually better not to provide a complete code sample if you believe it would not help the student, using your best judgment. You can use pseudo-code first, and, in the spirit of creating a programming resource, you may come back after a suitable amount of time and edit your response to include more complete code. This way, the student still has to write their own code, but a full solution can become available after the assignment has ended." From http://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions – JimLohse Feb 10 '16 at 04:16
2

I found the problem in your code. You never update your "seen" Boolean array. See the code below for fix:

public static int[] unique (int[] n){
 boolean[] seen = new boolean[n.length];
 int[] unique = new int[n.length];
 Random rand = new Random(123L);
 for (int i = 0; i < n.length; i++)
 {
     int index = rand.nextInt(n.length);
     while (seen[index])
     {
         index = rand.nextInt(n.length);
     }
     seen[index] = true; //boolean array updated
     unique[i] = n[index];
 }
 return unique;

}

Using this fix, I was able to get the output below (which has no repeats):

[3, 11, 17, 10, 16, 18, 15, 6, 14, 20, 7, 13, 1, 19, 9, 2, 5, 4, 12, 8]

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • I went ahead and changed my DV to UP, just read the link I posted about how to answer homework and maybe just make suggestions until after the homework is due, I will quote the relevant text on a comment to Sanchita's answer. – JimLohse Feb 10 '16 at 04:17
  • Thank you so much Benjamin Lowry! I was able to update my code and it ran just like yours. –  Feb 10 '16 at 04:24
1

Unless you specifically have to do it this way, I suggest you take a step back and try a totally different approach, something like this:

Set<int> mySet = new HashSet<int>(Arrays.asList(someArray));

NOTE: You will want to adjust the return type of unique() to be Set

The rest of the implementation is left as an excercise for the reader. Basically you take the array and convert it to a set as the example above.

(Credit where credit is due)

I just wanted to steer you in the right direction per https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions

Good luck, I would say the biggest lesson here is how to walk away from code that has become inefficient when a better solution exists. Good luck!

Community
  • 1
  • 1
JimLohse
  • 1,209
  • 4
  • 19
  • 44
  • I was also considering this approach when trying to think of how to tackle this problem; I approached my teacher about using a Hash Set and she said she would prefer that I do not use it (we have not gone over sets just yet). Thank you very much for the advice though, I will definitely be putting it to good use. –  Feb 10 '16 at 04:26
  • @ChristopherMoussa Yeah thanks per the very doc I linked, it notes that often homework imposes constraints, good thinking! Staying one step ahead of the lesson plan will serve you well :) – JimLohse Feb 10 '16 at 04:29
  • @Christopher and don't forget to accept one of the other answers, per these guidelines, the one that actually solved your problem (not mine haha) http://stackoverflow.com/help/someone-answers "What should I do when someone answers my question" – JimLohse Feb 10 '16 at 04:30
0

Heres is how to do this using java8 lambdas

    ArrayList<Integer> arrayli = new ArrayList<Integer>(Arrays.asList(arr_1));//converted array to list
    System.out.println();
    List<Integer> distinctIntegers = arrayli.stream().
    .distinct()
    .boxed()
    .collect(Collectors.toList());
 distinctIntegers.foreach(System.out::println);
Akhil
  • 78
  • 12