Counting Number of Unique Numbers in int Array - arrays

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

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

Finding Second duplicate element in an array in java

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

avoid Negative Array Size Exception with try, catch and throw

The following Java code:
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}
}
The first two instances of SomeClass, which have size 5 and 3, will be created without a problem. However, when the constructor SomeClass is called with an argument of -2, a run time error is generated: NegativeArraySizeException.
how can i modify the above code so that it behaves more robustly by using try, catch and throw. The main method should catch this exception and print a warning message then continue execution of the loop.
im a java newbie so would appreciate any help.
thanks
make the class constructor throw the error and catch it in the main class , like this :
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) throws NegativeArraySizeException{
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
try {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
catch (NegativeArraySizeException err) {
System.out.println(err.toString());
}
}
}
}
the output would be

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

How can I store the results of permutation in a 2D array?

I need help writing this code to get the permutation of numbers.
I need to store all the permutations in a 2D array.
After output of the permutation, I then need to process 30 percent of the permutations in one method an the the rest in another method.
My code:
public class Permutation {
* #param args the command line arguments
*/
void printArray(int []a) {
for (int i = 0; i< a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("");
}
void permute(int []a,int k ) {
if(k==a.length)
printArray(a);
else
for (int i = k; i< a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3,4,5,6};
p.permute(a, 2);
}
}
This is my solution instead of a 2d array use an ArrayList
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* #author David
*/
public class Permutations {
public static int[] a;
public final int SIZE = 6;
public final int NUMPERM;
public final ArrayList<int[]> newlist;
public Permutations()
{
a = new int[SIZE];
for(int x = 0; x < SIZE; x++)
a[x] = x+1;
NUMPERM = Factorial(a.length);
newlist = new ArrayList<>(NUMPERM);
}
public void permute()
{
permutation(a,0,a.length);
}
private void permutation(int array[],int start, int end)
{
newlist.add(saveArray(array));
if (start<end)
{
int i,j;
for(i=end-2; i>=start; i--)
{
for(j=i+1; j<end; j++)
{
Swap(array,i,j);
permutation(array,i+1,end);
}
Rotate_Left(array,i,end);
}
}
}
private int[] saveArray(int[] array)
{
int[] newarray = new int[array.length];
System.arraycopy(array, 0, newarray, 0, array.length);
return newarray;
}
public void Print()
{ //just to prove the list works
System.out.println("the current size of newlist is : " + newlist.size());
int[] array = new int[a.length];
for(int x = 0; x < newlist.size(); x++)
{
array = newlist.get(x);
System.out.println(Arrays.toString(array));
}
}
private void Swap(int array[],int i,int j)
{
int t;
t = array[i];
array[i] = array[j];
array[j] = t;
}
private void Rotate_Left(int array[],int start,int end)
{
int tmp = array[start];
for (int i=start; i < end-1; i++)
{
array[i] = array[i+1];
}
array[end-1] = tmp;
}
private int Factorial(int a)
{
int fact = 1;
for(int x = a; x > 0; x++)
fact *= a;
return fact;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Permutations newperm = new Permutations();
newperm.permute();
newperm.Print();
}
}
then all you have to do is send the list to the other functions and only use what you need from it.

Resources