Duplicate array in java and need to print rest of array element - java

Please look in to the below code. It print the only duplicate elements in array. I need to print also rest of array element, please try to help me.
public class DuplicateArray {
public static void main(String args[]) {
int array[] = { 10, 20, 30, 20, 40, 40, 50, 60, 70, 80 };// array of ten elements
int size = array.length;
System.out.println("Size before deletion: " + size);
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if ((array[i]== array[j])) { // checking one element with all the element
System.out.println(array[i]);
}
}
}
Ouput:
20
40
Here I need to print the rest of array element ?

In Java 8, you can easily remove duplicates from an integer array using IntStream.
int[] noDuplicates = IntStream.of(array).distinct().toArray();
To print them instead of putting them in an array, use
IntStream.of(array).distinct().forEach(System.out::println);

You can use Set to solve this.
List<Integer> list = Arrays.asList(ArrayUtils.toObject(array));
Set<Integer> set = new HashSet<Integer>(list);
List<Integer> withoutDuplicates = new ArrayList<Integer>(set);
int[] newArrayWithoutDuplicates = ArrayUtils.toPrimitive(withoutDuplicates.toArray(new int[withoutDuplicates.size()]));
Finally, you have the array without duplicates.

Your question as to what you want to do isn't very clear but what I think is you want is to print the array elements without repetition.
If this is indeed the case, the following code will do it.(The explanation of the code is given after the output)
public class DuplicateArray {
public static void main(String args[]) {
int array[] = { 10, 20, 30, 20, 40, 40, 50, 60, 70, 80 };// array of ten elements
int size = array.length;
System.out.println("Size before deletion: " + size);
boolean duplicateElement=false;//this becomes true if there is a duplicate element in the array before the occurrence of this element
for (int i = 0; i < size; i++, duplicateElement=false) {
for (int j = 0; j < i; j++) {
if ((array[i]== array[j])) { // checking one element with all the elements
duplicateElement=true; //Duplicate element found in array
break;
}
}
if(!duplicateElement)
System.out.println(array[i]);
}
}
}
Output:
10
20
30
40
50
60
70
80
Now, the idea in this code is instead of starting the inner loop from i+1 and going till array.size, start it from 0 and go till i. duplicateElement is a flag variable the value of which becomes true if a duplicate element of array[i] is present in the array at position < i. However, when it's the first occurrence of the duplicate element, there is no other same element before array[i], only after. Hence the repetitive elements are also printed just once

Related

How can I get N smallest number in an array?

I'm trying to get the N smallest numbers (given by the user) in an array without using methods like sort()... in the last step, I keep getting only the smallest values and 0 for the rest.. where's the problem?
//1- Scanner to take inputs
Scanner input = new Scanner(System.in);
//2- Take the array size as input and store it in "sizeOfArr" var
System.out.print("Enter the array size: ");
int sizeOfArr = input.nextInt();
//3- Assign the input as an array size
int array[] = new int[sizeOfArr];
//4- Looping on the array and update its values by inputs taken from the user
for(int i = 0; i < array.length; i++) {
System.out.print("Enter "+ (i+1) + "-st element: ");
array[i] = input.nextInt();
}
//5- Print out the array after convert it to String
System.out.println(Arrays.toString(array));
//6- Find the smallest element in the array and print it
int minVal = array[0];
for(int i = 0; i < array.length; i++) {
if (array[i] < minVal) {
minVal = array[i];
}
}
// System.out.println(minVal);
//7- Find the (n) smallest of number defined by the user
System.out.print("Enter the number of smallest numbers do you want: ");
int n = input.nextInt();
//8- new array to store n smallest numbers
int smallestNums[] = new int[n];
//9- trying to loop on the original array n times
int counter;
for(int i = 0; i < n ; i++) {
//10- trying to loop on the original array to store the smallest values in smallestNum[] array.
for(int j = 0; j < array.length; j++) {
smallestNums[i] = minVal;
}
if(smallestNums[i] == smallestNums[i]) {
break;
}
}
System.out.println(Arrays.toString(smallestNums));
Here is one way. Just do a partial sort with the outer loop limit equal to the number of items required. This is variant of the selection sort. This example, varies n in the outer list for demo purposes.
int[] array = { 10, 1, 5, 8, 7, 6, 3 };
for (int n = 1; n <= array.length; n++) {
int[] smallest = getNSmallest(n, array);
System.out.printf("smallest %2d = %s%n", n,
Arrays.toString(smallest));
}
prints
smallest 1 = [1]
smallest 2 = [1, 3]
smallest 3 = [1, 3, 5]
smallest 4 = [1, 3, 5, 6]
smallest 5 = [1, 3, 5, 6, 7]
smallest 6 = [1, 3, 5, 6, 7, 8]
smallest 7 = [1, 3, 5, 6, 7, 8, 10]
Here is the method. The first thing to do is copy the array so the
original is preserved. Then just do the sort and return array of smallest elements.
public static int[] getNSmallest(int n, int[] arr) {
int[] ar = Arrays.copyOf(arr, arr.length);
int[] smallest = new int[n];
for (int i = 0; i < n; i++) {
for (int k = i + 1; k < ar.length; k++) {
if (ar[i] > ar[k]) {
int t = ar[i];
ar[i] = ar[k];
ar[k] = t;
}
}
smallest[i] = ar[i];
}
return smallest;
}
For this task, you don't have to sort the whole array. Only a group of N elements has to be sorted. I.e. only a partial sorting is required.
Below, I've provided two implementations for this problem. The first utilizes only plane arrays and loops, the second makes use of the PriorytyQueue.
The first solution maintains a variable pos which denotes the position in the result array which isn't assigned yet. Note that the default value for an element of the int[] is 0. It's important to be able to distinguish between the default value and a zero-element from the given array. Hence we can't rely on the values and have to track the number of elements that are assigned.
Every element of the source array gets compared with all the elements of the result array that are already assigned. The new element will be added to the result array in two cases:
nested loop has reached an unoccupied position pos in the result array;
an element in the result array that is greater than the next element from the given array has been found.
In the first case, a new element gets assigned the position denoted by pos. In the second case, a new element has to be inserted
nested loop iterates over the given array at the current position i and all elements must be shifted to the right. That's what the method shiftElements() does.
The First solution - Arrays & Loops
public static int[] getSmallest(int[] arr, int limit) {
int[] result = new int[Math.min(limit, arr.length)];
int pos = 0;
for (int next: arr) {
for (int i = 0; i < Math.min(pos + 1, result.length); i++) {
if (i == pos) result[i] = next;
else if (result[i] > next) {
shiftElements(result, next, i, Math.min(pos + 1, result.length));
break;
}
}
pos++;
}
return result;
}
private static void shiftElements(int[] arr, int val, int start, int end) {
int move = arr[start];
arr[start] = val;
for (int i = start + 1; i < end; i++) {
int temp = arr[i];
arr[i] = move;
move = temp;
}
}
Maybe you'll be more comfortable with the first version, but if you are somehow familiar with the Collections framework, then it's a good time to get acquainted with PriorytyQueue. In the nutshell, this collection is backed by an array and maintains its element in the same order as they were added, but when an element is being deleted collection retrieves the smallest one according to the natural order or based on the Comparator, which can be provided while instantiating the PriorytyQueue. It uses a sorting algorithm that is called a heapsort which allows removing a single element in O(log N) time.
The Second solution - PriorytyQueue
public static int[] getSmallestWithPriorityQueue(int[] arr, int limit) {
Queue<Integer> queue = new PriorityQueue<>();
populateQueue(queue, arr);
int[] result = new int[Math.min(limit, arr.length)];
for (int i = 0; i < result.length; i++) {
result[i] = queue.remove();
}
return result;
}
private static void populateQueue(Queue<Integer> queue, int[] arr) {
for (int next: arr) {
queue.add(next);
}
}
main & utility-method to generate an array
public static void main(String[] args) {
int[] source = generateArr(100, 10);
System.out.println("source : " + Arrays.toString(source));
int[] result1 = getSmallest(source, 3);
System.out.println("result(Arrays & Loops) : " + Arrays.toString(result1));
int[] result2 = getSmallestWithPriorityQueue(source, 3);
System.out.println("result(PriorityQueue) : " + Arrays.toString(result2));
}
public static int[] generateArr(int maxVal, int limit) {
Random random = new Random();
return IntStream.generate(() -> random.nextInt(maxVal + 1))
.limit(limit)
.toArray();
}
output
source : [61, 67, 78, 53, 74, 51, 50, 83, 59, 21]
result(Arrays & Loops) : [21, 50, 51]
result(PriorityQueue) : [21, 50, 51]
Randomized select allows to find k-th ranked element in linear time on average.
It alters the input order, so practically, it makes sense to just sort and return k-th element of the sorted array. Especially if there are several such calls on the given input array.

Integers in array Java

I have an array that contains [45,8,50,15,65,109,2]. i would like to check to see if the zero element of my array is greater than my first element.
if ( 45 > 8)
then i would like to add 45 to brand new sub array.
i would like to continue checking my array for anything that is bigger than 45 and add it to the new sub array.
The new sub array has to keep the numbers added in the way they where added.The result should be [45,50,65,109]
I thought by creating this was going in the right direction but im doing something wrong so please help.
int[] x = [45,8,50,15,65,109,2];
int[] sub = null;
for(int i = 0; i > x.length; i++) {
for(int k = 0; k > x.length; k++) {
if(x[i] > x[k]){
sub = i;
First thing first. Your question contains some errors.
you should write int[] x = {45,8,50,15,65,109,2}; instead of int[] x = [45,8,50,15,65,109,2]; You can not use [] to initialize array!
What does it mean for(int i = 0; i > x.length; i++). Your program must not run! Because, the value of i is less than x.langth. First condition check is false, so loop will not works!
Same for for(int k = 0; k > x.length; k++)
How do you want to store value in an array without index? You have to write sub[i] = x[i]; here, i means what index value you want to store where!
Finally, do you want to do sorting? If yes, then you need another variable named temp means temporary!
Try to clear the basic and after then try this code.Sorting Link
Best of Luck!
It is possible to filter the input array using Java 8 Stream API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x)
.filter(n -> n >= x[0])
.toArray();
System.out.println(Arrays.toString(sub));
Output:
[45, 50, 65, 109]
If you're trying to fetch everything greater than 0th element.
Use the following:
Plain old java code:
int[] x = {45,8,50,15,65,109,2};
int[] sub = new int[x.length];
int first = x[0];
sub[0]=first;
int index=1;
for(int i = 1; i < x.length; i++) {
if(x[i] > first){
sub[index]=x[i];
index++;
}}
Streams API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x).filter(number -> number>=
x[0]).toArray();
where stream() is converting array to a stream, filter is applying the required condition and then ending it with conversion into an Array again.

Java 2d array and Bucket sort

I am working on an assignment where we need to take a integer array and sort it using a Bucket Sort.
My issue comes when trying to increase to the next column, but only if there is an element already in the "bucket" already.
So, using my array below, 22 is the first element and will go in row 2 column 0, which is correct, but using i as the column is obviously not correct because it always increases the column and I eventually get an index out of bounds.
I can't wrap my head around how to correctly increase the index of the bucketArray column, only if there is an element in that position. I've tried using an additional for loop that handled the column but that didn't work either.
Any pointers in the right direction would be greatly appreciated! I'm sure also there are other ways to create a bucket sort but the assignment said to use a 2d array for each bucket so I was trying to get it to work that way.
public class BucketSort {
public static void main(String args[]) {
int intArray[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14};
int eachBucket[][] = new int[10][11];
int j;
double max = 81;
int min = 6;
int divider = (int)Math.ceil((max + 1) / 10);
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][i] = intArray[i];
}
}
}
Use the 11th element to track how many elements in the current bucket have been used, something like this
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][eachBucket[j][10]] = intArray[i];
eachBucket[j][10]++;
}
The problem with a fixed-sized second dimension is if you have more that n elements to put into any one bucket. Probably not a problem here.

How to get the sequence of numbers back after random number generation

Am in the middle of an encryption algorithm, I have written the code to randomly shuffle a series of numbers in java.
Here is the code:
public class permute6 {
public static void main(String args[])
{
Random rand = new Random();
int arr[] = {10,20,30,40,50,60,70,80};// Original Array
System.out.println("Original array is" );
for(int k = 0; k<arr.length;k++ )
System.out.print(arr[k] + "\t" );
System.out.println(" ");
int max = arr.length - 1;
int min = 0;
int rnum;
int larr = arr.length - 1;
int[] parr = new int[arr.length];// to store the permuted array
int flag = 0;// 'flag' to flag the recurring number
int plen = parr.length - 1;
for(int i = 0 ; i < arr.length ; i++)
{
rnum = (rand.nextInt((max-min)+1) + min);// roll for the
random number
parr[plen] = arr[rnum];
arr[rnum] = arr[larr];
larr--;// to reduce the size of the original array
plen--;// to make the parr to act like a stack
max--;
}
System.out.println("Permuted array is" );
for(int k = 0; k<arr.length;k++ )
System.out.print(parr[k] + "\t" );
System.out.println();
}
}
If the initial array is {10,20,30,40,50,60,70,80}
then one of the shuffled result is
50 20 30 10 60 80 70 40
Now if I transmit this array, then how to get back the original sequence at the destination side? What can be done to keep track of the sequence?
What is missing here....Any help is appreciated!!
You can submit two arrays to destination parr and temp;
parr: [50 20 30 10 60 80 70 40]
and
temp(It is basically difference of permuted array from original e.g. parr-arr):
like {50, 20, 30, 10, 60, 80, 70, 40} - {10,20,30,40,50,60,70,80}
temp = {40,0,0,-30,10,20,0,-40}
Now,
At destination again get difference of parr and temp "parr-temp"
{50, 20, 30, 10, 60, 80, 70, 40} - {40,0,0,-30,10,20,0,-40}
= {10,20,30,10-(-30),50,60,70,40-(-40)}
You will get your original sequence without sending original array at destination
Another solution came into mind related to previous one but it will avoid transferring two arrays to destination. Merge both temp and parr into a single array say newArr = {50,40,20,0,30,0,10,-30,60,10,80,20,70,0,40,-40}
and at destination just subtract each element from the next element and you will get your original array using only one array.

Java Arrays.sort resets results to all zeros

I am using Java Arrays.sort in order to sort elements of a two dimensional array:
int[][] RAM = new int[4][10000];
I fill the RAM array with integers and then call:
for (i=0;i<4;i++){
Arrays.sort(RAM[i]);
System.out.println(i);
}
This results in all elements of RAM[][] being filled with zeros. What am I doing wrong?
Did you actually fill the Array with numbers first?
And if you did, you are only printing out the First part of your 2D array. You need to print out all 40,000 entries. 10,000 for each array in array. So [0][0...9999], [1][0...9999] etc.
public static void show (int [][] list)
{
System.out.println ("- show: -");
for (int [] ia : list) {
for (int i : ia)
System.out.print (i + ", ");
System.out.println ();
}
System.out.println ("---");
}
static Random random = new Random ();
public static void main (String [] args)
{
int[][] RAM = new int[4][2];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 2; ++j)
{
RAM[i][j] = random.nextInt (20);
System.out.print (i*2 +j);
}
}
show (RAM);
for (int i=0; i<4; i++) {
Arrays.sort (RAM[i]);
}
show (RAM);
System.out.println ();
}
Result:
- show: -
8, 13,
12, 10,
16, 3,
7, 1,
---
- show: -
8, 13,
10, 12,
3, 16,
1, 7,
---
I think the reason is that you didn't set a value for all elements of your array. For the item you didn't initialize, the default value is 0. Thus when you sort the all items in the array, the 0s are swapped to the first part of your array. If you output the first parts of the array, all you see are zeros. I guess so.

Categories