I am a newbie here. I wanted to print out the duplicate elements in an array.
This code will print out the duplicate elements.
Suppose I'm taking an array of size 5 with elements [1,2,5,5,5]
This code will print:
Duplicate elements: 5,5,5 //(since 5 is being repeated thrice.)
But I want the output something like this
Duplicate Elements: 5 //( instead of printing 5 thrice)
import java.util.*;
import java.util.Scanner;
public class duplicateArray{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x =sc.nextInt();
int arr[]=new int[x];
int i,count=0;
for(i=0;i<x;i++){
arr[i]=sc.nextInt();
}
System.out.print("Array: ");
for(i=0;i<x;i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
System.out.print("Duplicate elements: ");
for(i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
System.out.print(arr[j]+" ");
}
}
}
}
}
The following code does it without creating any additional data structure. For each element, it counts the number of duplicates previously encountered and only prints the first duplicate.
If I were doing this in the real world, I would use a Set but I'm assuming you haven't learnt about them yet, so I'm only using the array that you've already created.
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}
One solution is to create a separate List to store any duplicates found.
That, in addition to using the .contains() method of the List, you can ensure only one entry per int is made.
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
Output:
Duplicates: [1, 5]
This is pretty simple however you need to sort array before. All you need to know if duplicate for an element exists or not and do the printing in the outside for loop. Rest is described in comments
Arrays.sort(arr); // Sort Array
for (int i = 0; i < arr.length; i++) {
boolean hasDuplicate = false; // Assume that arr[i] is not repeating
for (int j = i + 1; j < arr.length; j++) {
// Check if it is repeating
if (arr[i] == arr[j]) {
// If it repeats
hasDuplicate = true;
}
// Since array is sorted we know that there is no value of arr[i] after this
if (arr[i] != arr[j]) {
// Set i to the last occurrence of arr[i] value
i = j - 1;
break; // Since there no occurrence of arr[i] value there is no need to continue
}
}
// Print the element at i
if (hasDuplicate)
System.out.print(arr[i] + " ");
// In next iteration loop will start from the index next to the last occurrence of value of arr[i]
}
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}
Without using Hashmaps, I think your best option would be to first sort the array and then count the duplicates. Since the array is now in order you can print the duplicates after each number switch!
If this is for an assignment go ahead and google bubble sort and implement it as a method.
Related
please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error:
at first.firstt.sorting_v2.sorting(sorting_v2.java:35).
Completely do not know why it occured, when I choose 2 or three element to sort it works perfect.
I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.
Also see the image below:enter image description here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose how much number you want to sort:");
int sizeOfTab = scanner.nextInt();
int[] numbers = new int[sizeOfTab];
for (int i = 0; i < sizeOfTab; i++) {
System.out.println("Choose number to collection: ");
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(Arrays.toString(sorting(numbers)));
}
private static int[] sorting(int[] numbers) {
boolean notDone = false;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int tmp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tmp;
notDone = true;
}
}
}
return notDone ? sorting(numbers) : numbers;
}
}
Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in
for (int j = 1; j < numbers.length; j++) { ... }
You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.
Lets say you have the array [1, 2, 3, 4]
Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.
To fix this simply always have your second loop start from the current value of i with 1 added:
for (int j = i+1; j < numbers.length; j++) { ... }
So, I don't see any errors prior to running the program. Basically it's an array program in which the user enter 10 numbers. Once the user types the number of Arrays, it then just pops up a GUI where it says type in an Array of 10. It only lets you do it once, and it just repeats the same number the user typed 10 times. It's all jacked up and it doesn't help that I've only been doing it for several weeks while doing 12 hr shifts. If anyone can point me in the right direction, that'd be awesome!
package Array;
import javax.swing.JOptionPane;
public class Array {
public static void main(String[] args) {
String response;
response = JOptionPane.showInputDialog("Enter the numbers : ");
int n = Integer.parseInt(response);
int[] a=new int[n];
int i,j,temp=0;
JOptionPane.showInputDialog("Enter "+n+" Array Elements : ");
for(i=0;i<n;i++){
a[i]=Integer.parseInt(response);
}
JOptionPane.showMessageDialog(null,"\nArray Elements Are : ");
for(i=0;i<n;i++) {
JOptionPane.showMessageDialog(null," "+a[i]);
}
for(i=0;i<n;i++) {
for(j=i+1;j<n;j++) {
if(a[i]<a[j]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
JOptionPane.showMessageDialog(null,"\nArray Elements in Descending Order : ");
for(i=0;i<n;i++) {
JOptionPane.showMessageDialog(null," "+a[i]);
}
}
}
The core issue is, you're just not asking the user to enter a value for each element in the array and simply parsing the last response, which is the number of elements for the array.
I stripped back your solution and removed the JOptionPane as it's probably not the best solution to the immediate problem. It wouldn't, however, take much to replace Scanner with JOptionPane as generally they are doing the same things
Scanner input = new Scanner(System.in);
System.out.print("Number of elements: ");
String response = input.nextLine();
int numberOfElements = Integer.parseInt(response);
int[] values = new int[numberOfElements];
for (int index = 0; index < numberOfElements; index++) {
System.out.print("Element " + index + ": ");
response = input.nextLine();
int value = Integer.parseInt(response);
values[index] = value;
}
for (int i = 0; i < numberOfElements; i++) {
for (int j = i + 1; j < numberOfElements; j++) {
if (values[i] < values[j]) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
System.out.println("Sorted:");
for (int index = 0; index < numberOfElements; index++) {
System.out.println(values[index]);
}
I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so a kind of bubble sort for the first and second array togheter. I wrote this below, but I don t know how to compare with one method the two different arrays.
public static void main(String[] args) {
public static int[] macello(int[]A){
for(int i=0; i<A.length-1; i++){
for(int j=0; j<A.length-1-i;j++){
if(A[j]>A[j+1]){
int temp = A[j+1];
A[j+1]= A[j];
A[j] = temp;
}
}
}
return A;
}
public static void printArray2(int[]A){
for(int i = 0; i<A.length; i++){
System.out.print(A[i]+",");
}
}
Scanner scan = new Scanner(System.in);
System.out.println("Insert the capacity's array1: ");
int n = scan.nextInt();
int[]numbers1 = {n};
for(int i=0; i<n; i++){
System.out.println("Insert the value of each numbers: ");
int j =0;
numbers1[j] = scan.nextInt();
j++;
}
System.out.println("Insert the capacity's array2: ");
int m = scan.nextInt();
int[]numbers2 = {m};
for(int i=0; i<m; i++){
System.out.println("Insert the value of each numbers: ");
int j=0;
numbers2[j] = scan.nextInt();
j++;
}
macello(Arrays.equals(numbers1,numbers2));
printArray2(Arrays.equals(numbers1,numbers2));
}
}
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr).
Your code shows you understand how to acquire an array from the user, so we don't need to handle that.
Now what you're describing is bubbleSorting these two arrays. To do this, you need one -big- array that holds them both.
int combinedLength = array1.length + array2.length;
int[] combined = new int[combinedLength];
for(int i = 0; i < array1.length; i++) {
combined[i] = array1[i];
}
for(int i = 0; i < array2.length; i++) {
combined[array1.length + i] = array2[i];
}
// now you can bubbleSort
bubbleSort(combined);
arrayPrint(combined);
Ideally you wrap that logic in a merge method - this particular method leverages the Arrays and System classes to do some of the lifting for you. Obviously you could use the "naive" logic above if you want.
int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
If you also make a method that acquires an array, like this:
public int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
Then your code becomes very, very clean:
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
arrayPrint(c);
I made a driver to test each of these ideas out to make sure they all work. I am a bit concerned, though, because you mention recursion. As you can see in this driver, there is no recursion here. Also be aware that I take a number of shortcuts that are probably not allowed (such as System.arraycopy, Arrays.copyOf, and Arrays.toString). I just wanted to validate the various pieces of functionality. The message uses 1 indexing because that's what most people think in. If you enter 5 elements, they'll be 1-5. You and I know Java stores them 0 indexed, 0-4. It's just a matter of taste and UX.
import java.util.*;
public class BubbleSort {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
printArray(c);
}
public static int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
public static int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
public static void bubbleSort(int[] a) {
boolean swapped = true;
int j = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < a.length - j; i++) {
if(a[i] > a[i+1]) {
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
swapped = true;
}
}
}
}
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
}
And here's what I get when I run it
C:\files\j>java BubbleSort
Length?
5
Enter element 1:
1
Enter element 2:
5
Enter element 3:
3
Enter element 4:
9
Enter element 5:
7
Length?
5
Enter element 1:
2
Enter element 2:
6
Enter element 3:
4
Enter element 4:
0
Enter element 5:
8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest).
The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
System.out.println("\n" + "Organized Array: ");
int[] array2 = new int[i];
for (i = 0; i < array1[i]; i++) {
System.out.println(+array1[i]);
for (int j = 0; j < i; j++) {
int temp;
boolean numerical = false;
while (numerical == false) {
numerical = true;
for (i = 0; i < array1.length - 1; i++) {
if (array2[i] > array2[i + 1]) {
temp = array2[i + 1];
array2[i + 1] = array2[i];
array2[i] = temp;
numerical = false;
}
}
}
}
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
You have several issues that you need to fix to make your program run:
You have forgotten to copy array1 into array2:
The output that you think is coming from sorting array2 is actually from the process of sorting.
int[] array2 = new int[i];
for (int j = 0; j < i; j++) {
array2[j] = array1[j];
}
You placed the output of sorted array inside the loop that does sorting:
Check the level of curly braces, and move the output loop to after the sorting loop
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Your sorting algorithm has an extra loop:
Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting:
for (i = 0; i < array1[i]; i++) { // Remove the loop
... // <<== Keep the body
}
Your innermost loop reuses i incorrectly:
Replace loop variable i with another variable, e.g. m
for (int m = 0 ; m < array2.length - 1; m++) {
if (array2[m] > array2[m + 1]) {
temp = array2[m + 1];
array2[m + 1] = array2[m];
array2[m] = temp;
numerical = false;
}
}
Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong.
you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops
you never copied the array1 values to array2
Ok, so this is for a Java class, but I'm not looking for someone to write the code, just help me debug this one. I want to enter 10 integers and have the inputs sorted in ascending order as they are entered then displayed, without any zeros (0) that may exist in the array.
Example of what the assignment should look like:
Enter 10 integers - one at a time...
Enter integer #1: 21
Sorted numbers: 21
Enter integer #2: 48
Sorted numbers: 21 48
Enter integer #3: 37
Sorted numbers: 21 37 48
etc....
I have tried a Selection Sort, Insertion and Bubble Sort, but the array will not hold or display more than 5 numbers.
Help.
Here is my Main:
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
int[] list = new int[10];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length; i++){
System.out.print("Enter integer #" + j + ": ");
list[i] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.length; p++){
if (list[p] !=0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
Here is my Selection Sort:
public class SelectionSort {
public static void sort (int[] list){
for(int i=0; i<list.length; i++)
{
for(int j=i+1; j<list.length; j++)
{
if(list[i] > list[j] )
{
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
}
}
Thanks in advance!
Why don't you use List insteed of array and ready-to-go sorting implementations from jdk -> Collections.sort() ?
Anyway the problem is that you are inserting new integers into already sorted array and that causes disfunction of your code. So as you inserting new elements on indexes 0,1,2,3,4 - sorting algorithm moves them to positions 5,6,7,8,9. From this point your inputs starts overriding sorted values with new ones from input - (Main loop i>=5).All in all, it accepted 10 integers, but 5 of them where kindly overriten.
Here is little modified version of your work whitch works like you want. Analyze it!
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
list[0] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
class SelectionSort {
public static void sort(int[] list) {
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] > list[j]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
i--;
break;
}
}
}
}
}
You are replacing sorted value with list[i] = input.nextInt(); with every input. So, 5 values always 0 in list. Use List<Integer> instead of int[] and add new value to List<Integer>. Try following code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
List<Integer> list = new ArrayList<>();
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < 10; i++){
System.out.print("Enter integer #" + j + ": ");
list.add(input.nextInt());
j++;
//SortMethod.sort(list, list.length);
// SelectionSort.sort(list);
Collections.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.size(); p++){
if (list.get(p) !=0)
System.out.print(list.get(p) + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
I just modified the lines below the comments I put (temp declaration and for loop).
This changes makes program support negative numbers too, read the comments below:
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
// Add temporal variable to store input
int temp = input.nextInt();
// Check for empty place in list (as far as it seems you don't care about zeros)
for (int p = 0; p < list.length; p++) {
if (list[p] == 0) {
list[p] = temp;
break;
}
}
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}