Eliminating Duplicate Numbers in Arrays Java - java

I need to know how to eliminate duplicate numbers in the same array. I only know creating arrays, getting data from user and print it out. Following shows my progress:
import java.util.Scanner;
public class DuplicateElimination {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int [] x = new int [10];
for (int i = 0; i < 10; i++){
System.out.println("Enter a number");
x[i] = scn.nextInt();
}
for (int i = 0 ; i<10 ; i++)
System.out.print(x[i] + " ");
}
}
The real statement is
Write a method that returns a new array by eliminating the duplicate values in the
array using the following method header:
public static int[] eliminateDuplicates(int[] list)
Write a test program that reads in ten integers, invokes the method, and displays the
result.

You can use java set data structure to eliminate duplicates. Add each element into the set. it will eliminates duplicates
Set<Integer> set=new HashSet<Integer>();
set.add(1);

Just after the statement:
x[i] = scn.nextInt();
You could loop accross the array like:
boolean isNumberFound = false;
for (int j =0; j<i; j++) {
if (lastNumberScanned == x[j]) {
isNumberFound = true;
break;
}
}
if (!isNumberFound)
x[i] = lastNumberScanned;
If you dont want to stick with Arrays, then i would suggest you using Set data structure like:
Set<Integer> myset = new HashSet<>();
myset.add(scn.nextInt());

Related

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Store random integers in array

package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers RE:

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers
I have a problem that I have looked into Doestovsky's question but from his question, I need to know on how to make the part on finding duplicates into a function of it's own:
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
I have tried this part of this code and it worked but I need this to take the part that find duplicates into a function of it's own that is powered by arrays.
Credits to ThimoKl for creating this code.
Let's try something else, using Treeset, and let's get rid of that for for
import java.util.*;
public class duplicate {
private static TreeSet<Integer> numbers = new TreeSet<Integer>();
private static TreeSet<Integer> duplicates = new TreeSet<Integer>();
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
int numberOfIntToRead=10;
for (int i = 0; i < numberOfIntToRead; i++) {
// Read number from console
n=input.nextInt();
// Check if number was inserted before
checkIfDuplicate(n);
}
// Print all numbers that were not inserted more than one time
for (Integer j : numbers) {
System.out.print(j+" ");
}
}
public static void checkIfDuplicate(int n){
if(!numbers.contains(n) && !duplicates.contains(n)){
numbers.add(n);
}else{
numbers.remove(n);
duplicates.add(n);
}
}
}
But if you really want to use arrays an not a Collection of any sort, then you need to declare your arrays as class members, that way you can put the "for" that checks for duplicates in a function a give it your i, and this way you can also put the "for" that does the printing in a function. and give to it numbers.length. That should do the trick.
You can make use of a Set to make finding duplicates easy:
List<Integer> dups = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i : numbers)
if (!set.add(i))
dups.add(i);
This works because Set#add() returns false if it doesn't change as a result if being called, which happens eggnog the set already contains the number - ie it's a dup.

Java: how do I initialize an array size if it's unknown?

I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number.
How should I assign the array length?
If user enters 5 6 7 8 9 (5 numbers), then
int[] list;
becomes
int[] list = new int[5];
I'm trying to use a loop, but it won't stop.
int[] integers;
int j = 0;
do {
integers = new int[j + 1];
integers[j] = in.nextInt();
j++;
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.
import java.util.Scanner;
public class ArrayModify {
public static void main(String[] args) {
int[] list;
String st;
String[] stNew;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9
st = scan.nextLine();
stNew = st.split("\\s+");
list = new int[stNew.length]; // Sets array size to 5
for (int i = 0; i < stNew.length; i++){
list[i] = Integer.parseInt(stNew[i]);
System.out.println("You Enterred: " + list[i]);
}
}
}
String line=sc.nextLine();
int counter=1;
for(int i=0;i<line.length();i++) {
if(line.charAt(i)==' ') {
counter++;
}
}
long[] numbers=new long[counter];
counter=0;
for(int i=0;i<line.length();i++){
int j=i;
while(true) {
if(j>=line.length() || line.charAt(j)==' ') {
break;
}
j++;
}
numbers[counter]=Integer.parseInt(line.substring(i,j));
i=j;
counter++;
}
for(int i=0;i<counter;i++) {
System.out.println(numbers[i]);
}
I always use this code for situations like this. beside you can recognize two or three or more digit numbers.
int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
arr[j] = scan.nextInt();
}
The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.
**input of list of number for array from single line.
String input = sc.nextLine();
String arr[] = input.split(" ");
int new_arr[] = new int[arr.length];
for(int i=0; i<arr.length; i++)
{
new_arr[i] = Integer.parseInt(arr[i]);
}

Printing distinct integers in an array

I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function checkDuplicate.
Here's my code so far:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.
First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").
Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of CheckDuplicate() would be:
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
But of course, some kind of Set would be much more efficient for bigger arrays...
EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...
Put them in a set ordered by insertion time, then convert back to an array if necessary.
new LinkedHashSet<Integer>(array).toArray()
Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.
What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().
Using them, method to remove duplicated elements from an integer array looks something like this:
public static int[] removeDuplicates(int... array) {
Integer[] ints = ArrayUtils.toObject(array);
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!
It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.
Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.
import java.util.Scanner;
public class PrintDistinctNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] numberArray = createArray();
System.out.println("The number u entered are: ");
displayArray(numberArray);
getDistinctNumbers(numberArray);
}
public static int[] createArray() {
Scanner input = new Scanner(System.in);
int [] numberCollection = new int [10];
System.out.println("Enter 10 numbers");
for(int i = 0; i < numberCollection.length; i++){
numberCollection[i] = input.nextInt();
}
return numberCollection;
}
public static void displayArray(int[] numberArray) {
for(int i = 0; i < numberArray.length; i++){
System.out.print(numberArray[i]+" ");
}
}
public static void getDistinctNumbers(int[] numberArray) {
boolean isDistinct = true;
int temp = 0;
int [] distinctArrayNumbers = new int [10];
for ( int i = 0; i < numberArray.length; i++){
isDistinct = true;
temp = numberArray[i];
for( int j = 0; j < distinctArrayNumbers.length; j++){
if( numberArray[i] == distinctArrayNumbers[j] ){
isDistinct = false;
}
}
if(isDistinct){
distinctArrayNumbers[temp]=numberArray[i];
temp++;
}
}
displayDistinctArray(distinctArrayNumbers);
}
public static void displayDistinctArray(int[] distinctArrayNumbers) {
for( int i = 0; i < distinctArrayNumbers.length; i++){
if(distinctArrayNumbers[i] != 0){
System.out.println(distinctArrayNumbers[i]);
}
}
}
}

Categories