Finding Second duplicate element in an array in java - arrays

Hi Everyone, i am new to the programming world, can you please help me in finding second duplicate element in an array. i have tried but its not working.
public class FindSecondDuplicate {
public static void main(String[] args) {
int[] intArray = { 6,4,2,3,4,6,8};
int count=0;
Set<Integer> set=new LinkedHashSet<>();
for(int no:intArray)
{
if(set.add(no)==false)
{
count=count+1;
if(count==2)
{
System.out.println(no);
break;
}
}
else
{
set.add(no);
}
}
}
}

I think what you are trying to do can be accomplished using
public static void main(String[] args) {
int[] intArray = {6, 4, 2, 3, 4, 6, 8};
int count = 0;
Map<Integer, Integer> repeatCounter = new HashMap<>();
for (int i : intArray) {
if (repeatCounter.containsKey(i)) {
int repeatedNTimes = repeatCounter.get(i);
repeatCounter.put(i, repeatedNTimes + 1);
}else{
repeatCounter.put(i, 1);
}
}
for (int i : intArray) {
if (repeatCounter.get(i) == 2) {
count++;
if (count == 2) {
System.out.println(i);
break;
}
}
}
}

Find 2nd/3rd or any duplicate with Set Interface
public static void main(String[] args){
int[] array = {3, 12, 9, 3, 8, 3, 12, 4, 7, 8};
int find_duplicate = 3;
// Add all duplicates to set
Set<Integer> storeDuplicates = new LinkedHashSet<>();
for (int i = 0; i < array.length-1; i++){
for (int j = i+1; j < array.length; j++){
if (array[i] == array[j]){
storeDuplicates.add(array[i]);
}
}
}
// Traverse set for find the 2nd/3rd/any other duplicate
int count = 0;
for (int i : storeDuplicates){
count++;
if (count == find_duplicate) System.out.println(find_duplicate+" duplicate is : "+i);
}
}

Related

Calling array method in main class

How can i call runningSum method in main with new array of intigers so it return result?
class Main {
public static void main(String[] args) {
}
public int[] runningSum(int[] nums) {
int[] result = new int[nums.length];
result[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] + nums[i];
}
return result;
}
}
I have no idea how to call it.
Add static modifier to your runningSum method. example
public static void main(String[] args) {
int[] myNum = {10, 20, 30, 40};
int[] result = runningSum(myNum);
for (int item : result){
System.out.println(item);
}
}
public static int[] runningSum(int[] nums) {
int[] result = new int[nums.length];
result[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] + nums[i];
}
return result;
}

Array challenge

public class Testfor
{
public static int ArrayChallenge(int[] arr)
{
int[] temp = new int[arr.length - 1];
int diff = 0;
for (int i = 0; i < arr.length - 1; i++)
{
diff = Math.abs(arr[i] - arr[i + 1]);
temp[i] = diff;
}
arr = temp;
for (int i:arr)
{
System.out.println(i);
}
if (arr.length > 1)
{
ArrayChallenge(arr);
}
else
{
diff = arr[0];
System.out.println("diff" + diff);
}
return diff;
}
public static void main(String[] args)
{
// keep this function call here
//Scanner s = new Scanner(System.in);
System.out.println("answer:" + ArrayChallenge(new int[] { 5, 7, 16, 1, 2 }));
}
}
Here the input is an array of integers finally the array should be reduced to the size of one element by finding the absolute difference between two elements.
I am using recursion to solve this but I am getting 1 as the answer can someone please someone help to solve it?
input:[5,7,16,1,2]
[2,9,15,1]
[7,6,14]
[1,8]
[7]--->the array should reduce in the following manner to get an answer and finally should return the last element
output:7
Just preserve the return value
public class Testfor
{
public static int ArrayChallenge(int[] arr)
{
int[] temp = new int[arr.length - 1];
int diff = 0;
for (int i = 0; i < arr.length - 1; i++)
{
diff = Math.abs(arr[i] - arr[i + 1]);
temp[i] = diff;
}
arr = temp;
for (int i:arr)
{
System.out.println(i);
}
if (arr.length > 1)
{
diff = ArrayChallenge(arr);
}
else
{
diff = arr[0];
System.out.println("diff" + diff);
}
return diff;
}
public static void main(String[] args)
{
// keep this function call here
//Scanner s = new Scanner(System.in);
System.out.println("answer:" + ArrayChallenge(new int[] { 5, 7, 16, 1, 2 }));
}
}

Setting output in one array

I need quick help how to put 3 line of output code in one string.
With this code i get answer:
Duplicate Element : 12
Duplicate Element : 0
Duplicate Element : 43
but I want them to be in one array.
public class As1 {
public static void main(String[] args) {
int []array= {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
for (int i = 0; i < array.length-1; i++)
{
for (int j = i+1; j < array.length; j++)
{
if ((array[i] == array[j]) && (i != j))
{
System.out.println("Duplicate Element : "+array[j]);
}
}
}
}
}
I know I can use array.toString[], but I get error.
I want my output to be like this
Duplicate Element : 12, 0, 43.
U can always make one-time print with boolean flag like first:
public static void main(String[] args) {
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
boolean first = true;
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if ((array[i] == array[j]) && (i != j)) {
if(first) {
System.out.print("Duplicate Element:");
first = false;
}
System.out.print(" " + array[j]);
}
}
}
}
Or you can create a new array that has all the duplicates and print them afterwards:
public static void main(String[] args) {
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int[] duplicates = new int[array.length/2]; //maximum duplicates is half of size the given integer array
int k = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if ((array[i] == array[j]) && (i != j)) {
duplicates[k] = array[i];
k++;
}
}
}
System.out.print("Duplicate Element:");
for(int i = 0; i < k; i++) {
System.out.print(" " + duplicates[i]);
}
}

Counting Number of Unique Numbers in int Array

Trying to get number of unique(non duplicated) numbers of an array via a static method.
For example the array is {1,1,2,4,5,5,7,78,89}
the output would be 7.
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = {1, 2, 4, 5, 10, 30, 20, 1};
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list){
int count= 0;
int fin =list.length;
Arrays.sort(list);
for (int i = 0; i<=list.length; i++){
if(list[i]==list[i-1])
count++;
}
return fin-count;
}
}
Put everything in a set and return the size of the set.
import java.util.HashSet;
import java.util.Set;
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = { 1, 2, 4, 5, 10, 30, 20, 1 };
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list) {
// java.util.Set
// "A collection that contains no duplicate elements."
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < list.length; i++) {
set.add(list[i]);
}
return set.size();
}
}

Java merge same numbers via multiplication in an array with Recursive

I wanna write a method that merges the same values within an array via multiplication. I wanna do it with recursive.
Any sequence of numbers should be merged, if there are similar numbers withing it.
So for example if I have the numbers 1, 2, 5, 5, 4, it should become "1 2 25 4" or 5, 5, 5, 6 becomes ”125 6”.
Can anyone help?
This approach utilizes divide and conquer, and should run in O(n log n).
package edu.gwu.seas.cs6212.hw3;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;
public class Tester {
public static void main(String [] args){
System.out.println("Merging 1, 2, 5, 5, 4: ");
int [] originalArray = {1, 2, 5, 5, 4};
int [] mergedArray = mergeSequences(originalArray);
StringBuilder sb = new StringBuilder();
for(int element : mergedArray){
sb.append(element);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1); //Remove final comma
System.out.println(sb.toString());
sb.delete(0, sb.length());
System.out.println("Merging 5, 5, 5, 6: ");
int [] originalArray2 = {5, 5, 5, 6};
int [] mergedArray2 = mergeSequences(originalArray2);
for(int element : mergedArray2){
sb.append(element);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1); //Remove final comma
System.out.println(sb.toString());
}
private static int [] mergeSequences(int [] originalArray){
Map<Integer,Integer> indiciesMap = mergeDivideAndConquer(originalArray, 0, originalArray.length -1, new TreeMap<Integer,Integer>());
int indexCounter = 0;
List<Integer> mergedList = new ArrayList<Integer>();
Iterator<Entry<Integer, Integer>> it = indiciesMap.entrySet().iterator();
if(it.hasNext()){
while(it.hasNext()){
Entry<Integer,Integer> firstEntry = it.next();
int firstSequenceBeginIndex = firstEntry.getKey();
int firstSequenceEndIndex = firstEntry.getValue();
while(indexCounter < firstSequenceBeginIndex){
mergedList.add(originalArray[indexCounter]);
indexCounter++;
}
//Now we've reached first entry
int multiplicativeSum = 1;
while(indexCounter <= firstSequenceEndIndex){
multiplicativeSum *= originalArray[indexCounter];
indexCounter++;
}
mergedList.add(multiplicativeSum);
}
//Add remaining elements
while(indexCounter < originalArray.length){
mergedList.add(originalArray[indexCounter++]);
}
} else{
for(int element : originalArray){
mergedList.add(element);
}
}
return mergedList.stream().mapToInt(i -> i).toArray();
}
private static Map<Integer,Integer> findCrossingArray(final int [] originalArray, final int i, final int midpoint,
final int j, Map<Integer,Integer> indiciesMap){
int leftIndexOfSequence = -1;
for(int leftCounter = midpoint; leftCounter >= i; leftCounter--){
if(originalArray[leftCounter] == originalArray[midpoint]){
leftIndexOfSequence = leftCounter;
} else{
break;
}
}
int rightIndexOfSequence = midpoint;
for(int rightCounter = midpoint + 1; rightCounter <= j; rightCounter++){
if(originalArray[rightCounter] == originalArray[midpoint]){
rightIndexOfSequence = rightCounter;
} else{
break;
}
}
if(leftIndexOfSequence != -1 && leftIndexOfSequence != rightIndexOfSequence){
indiciesMap.put(leftIndexOfSequence, rightIndexOfSequence);
}
return indiciesMap;
}
private static Map<Integer,Integer> mergeDivideAndConquer(final int [] originalArray, final int i, final int j, Map<Integer,Integer> indiciesMap){
//Base case
if(j == i){
return indiciesMap;
}
//Divide recursively into smaller subproblems
int midpoint = Math.floorDiv((i + j),2);
Map<Integer,Integer> left = mergeDivideAndConquer(originalArray, i, midpoint, indiciesMap);
Map<Integer,Integer> right = mergeDivideAndConquer(originalArray, midpoint + 1, j, indiciesMap);
//Combine subsolutions
return findCrossingArray(originalArray, i, midpoint, j, indiciesMap);
}
}

Resources