简体   繁体   中英

Trying to Print Array without Repeating Numbers

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.

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;
    }

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]

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM