How to get all sub arrays of specific length from array - java

If I have array like [1,2,3,4] and k = 3 then output should be
[1,2,3][2,3,4][1,3,4] which is in sorted order.
I can do it when k = 2 but can't think of a way to do it more generic for any value of k.
final int arr[] = new int[] { 1, 2, 3, 4 };
final int max = 2;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = 0; k < max; k = k + 2) {
System.out.println(i + "" + j);
}
}
}

As I said above try to convert array to ArrayList, sort it.
Imagine that now you have an original paper with list of your integer values.
You copy this paper, cross off one of the integer values in copy and put this paper into your folder (HashSet in the following code). Then copy original again and so on.
package Subarrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Subarrays {
public static void main(String[] arg) {
int arraySize = 0;
int initElementNumber = 0;
int initElementValue = 0;
Scanner scanner = new Scanner(System.in);
// Creates an array
System.out.println("Type the size of the array: ");
do {
try {
arraySize = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (arraySize == 0);
System.out.println("Type the number of element, which you want to initialize yourself: ");
do {
try {
initElementNumber = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (initElementNumber == 0);
System.out.println("Type value of the element: ");
do {
try {
initElementValue = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (initElementValue == 0);
Integer arr[] = new Integer[arraySize];
arr[initElementNumber] = initElementValue;
for (int i = 0; i < arr.length; i++) {
if (i != initElementNumber) {
arr[i] = i;
}
}
// Converts the array to arrayList
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
// Sorts the list
Collections.sort(list);
// Creates a clone of the list
ArrayList<Integer> listTemp = (ArrayList<Integer>) list.clone();
// Creates a set of the future lists
Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
// Iterates over the list and removes one element
for (int i = 0; i < list.size(); i++) {
listTemp.remove(i); // listTemp restructured here
// Adding listItem to set
set.add(listTemp);
// Creates new clone of the list
listTemp = (ArrayList<Integer>) list.clone();
}
// Writes content of the set to the console
for (List<Integer> list2 : set) {
System.out.print("List: ");
for (Integer integer2 : list2) {
System.out.print(" " + integer2 + " ");
}
System.out.println();
}
}
}
Result of the executing of the code will be:
Type the size of the array:
5
Type the number of element, which you want to initialize yourself:
2
Type value of the element:
8
List: 0 3 4 8
List: 0 1 4 8
List: 1 3 4 8
List: 0 1 3 8
List: 0 1 3 4
UPDATE:
I read your question more attentively and decided to rewrite the code for meeting the main requirement: find all sorted subarrays with size k in the array with size n.
package Subarrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Subarrays2 {
private static int ARRAY_SIZE = 0;
private static int SIZE_OF_SUBARRAYS = 0;
private static Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
// Creates an array
System.out.println("Type the size of the array: ");
do {
try {
ARRAY_SIZE = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (ARRAY_SIZE == 0);
System.out.println("Type the size of subarrays: ");
do {
try {
SIZE_OF_SUBARRAYS = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (SIZE_OF_SUBARRAYS == 0);
scanner.close();
Integer arr[] = new Integer[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = i;
}
// Converts the array to arrayList
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
// Sorts the list
Collections.sort(list);
recursion(list); // This method work until find all of the sorted lists
// with size SIZE_OF_SUBARRAYS in array with size ARRAY_SIZE
// Writes content of the set to the console
for (List<Integer> list2 : set) {
System.out.print("List: ");
for (Integer integer2 : list2) {
System.out.print(" " + integer2 + " ");
}
System.out.println();
}
}
private static void recursion(ArrayList<Integer> notSmallestCombination) {
ArrayList<Integer> listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
for (int i = 0; i < notSmallestCombination.size(); i++) {
listTemp.remove(i);
if (listTemp.size() == SIZE_OF_SUBARRAYS) {
for (int j = 0; j < notSmallestCombination.size(); j++) {
ArrayList<Integer> list2Temp = (ArrayList<Integer>) notSmallestCombination.clone();
list2Temp.remove(j);
set.add(list2Temp);
}
} else {
recursion(listTemp);
}
listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
}
}
}
And result is:
Type the size of the array:
5
Type the size of subarrays:
3
List: 0 3 4
List: 0 2 3
List: 0 1 2
List: 1 3 4
List: 1 2 3
List: 0 2 4
List: 0 1 3
List: 2 3 4
List: 1 2 4
List: 0 1 4

I found something on internet here https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
The code use a permutation function :
// Java program to print all combination of size r in an array of size n
import java.io.*;
class Permutation {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
static void combinationUtil(int arr[], int data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
for (int j=0; j<r; j++)
System.out.print(data[j]+" ");
System.out.println("");
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
static void printCombination(int arr[], int n, int r)
{
// A temporary array to store all combination one by one
int data[]=new int[r];
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
/*Driver function to check for above function*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.length;
printCombination(arr, n, r);
}
}
/* This code is contributed by Devesh Agrawal */
Once you have all the permutation you just have to build an array with it

Related

how can i get elements from array which makes sum equals to given value

how can i find lowest number of integers in the array that sums up the given number. The program should ask user to input array of integers (“Input Array”) and the required sum (“Required Sum”). The output (“Output”) should list the lowest number of integers from the input array that sums up the “Required Sum”.
here i create the function sum() and declare array with some elements when read sum from user 45 it gives me output 25,25 but when i input 59 and 60 nothing shows on output
public static void sum()
{
int arr[]={10,0,-1,20,25,30};
Scanner in=new Scanner(System.in);
int sum=in.nextInt();
int[] sub = new int[arr.length];
int temp = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = i, col = 0; j < arr.length; j++, col++)
{
//add the value of input array one by one
temp += arr[j];
sub[col] = arr[j];
//if addition is equal to sum then print it
if (temp == sum)
{
int total = 0;
for (int k = 0; k < sub.length; k++)
{
total += sub[k];
System.out.println(sub[k]);
//if total and sum are equal then leave the print
if (total == sum)
{
System.out.println();
break;
}
}
}
//if temp is greater than sum are equal then clear the sub array, set temp value and leave the loop for next
if (temp > sum)
{
temp = 0;
break;
}
}
}
}
Output Example:
Input Array : [10, 0, -1, 20, 25, 30]
Required Sum: 45
Output: [20, 25]
Required Sum: 59
Output: [10, -1, 20, 30]
Required Sum: 60
Output: [10, 20, 30]
import java.util.*;
public class Runner
{
public static void find(int[] A, int currSum, int index, int sum,int[] solution)
{
if (currSum == sum)
{
System.out.print("Output: [");
for (int i = 0; i < solution.length; i++)
{
if (solution[i] == 1)
{
if(A[i]!=0)
{
System.out.print(" " + A[i]);
}
}
}
System.out.print(" ]\n");
}
else if (index == A.length)
{
return;
}
else
{
solution[index] = 1;// select the element
currSum += A[index];
find(A, currSum, index + 1, sum, solution);
currSum -= A[index];
solution[index] = 0;// do not select the element
find(A, currSum, index + 1, sum, solution);
}
return;
}
public static void main(String args[])
{
Scanner in =new Scanner(System.in);
System.out.println("How many integer you have to insert: ");
int n=in.nextInt();
int []A=new int[n];
System.out.println("\nEnter elements in Array:\n ");
for(int i=0;i<A.length;i++)
{
A[i]=in.nextInt();
}
System.out.println("\nEnter required sum: ");
int sum=in.nextInt();
int[] solution = new int[A.length];
find(A, 0, 0, sum, solution);
}
}
Please find below program which I feel to be ideal for your scenario.
The Solution might not be optimal with memory and time consideration which you can optimize by based on your scenario.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Subset {
static public void main (String[] ab)
{
int s[] = {10, 0, -1, 20, 25, 30};
int sum = 45;
ArrayList<ArrayList<Integer>> lis = subsets(s,sum);
Iterator<ArrayList<Integer>> t1 = lis.iterator();
while (t1.hasNext()) {
List<Integer> t2= t1.next();
int count = 0;
Iterator<Integer> t3 = t2.iterator();
while (t3.hasNext()) {
count = count+ t3.next();
}
if(count ==sum)
System.out.println(t2);
}
}
public static ArrayList<ArrayList<Integer>> subsets(int[] S,int sum) {
if (S == null)
return null;
Arrays.sort(S);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < S.length; i++) {
ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
//get sets that are already in result
for (ArrayList<Integer> a : result) {
temp.add(new ArrayList<Integer>(a));
}
//add S[i] to existing sets
for (ArrayList<Integer> a : temp) {
a.add(S[i]);
}
//add S[i] only as a set
ArrayList<Integer> single = new ArrayList<Integer>();
single.add(S[i]);
temp.add(single);
result.addAll(temp);
}
//add empty set
result.add(new ArrayList<Integer>());
return result;
}
}
Hope this was helpful.
try this code using simple arrays
i created sets from user entered array and print all of them and sets with sum equal to user entered sum i`m showing solution and the element count foe better understanding.
import java.util.*;
public class Main{
public static void set(int[] temp,int sum){
int n=temp.length;
for (int i = 0; i < (1<<n); i++)
{ int sumc=0;
int count=0;
System.out.print("{ ");
// Print current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0) {
System.out.print(temp[j] + " ");
sumc=sumc+temp[j];
count++;
}
if(sum==sumc){
System.out.println("}"+" sum :"+sumc +" solution with "+count+" elements");
}else{
System.out.println("}");
}
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("enter size of array : ");
int n=sc.nextInt();
int[] a=new int[n];
int sum;
for(int i=0;i<n;i++)
{
System.out.print("enter "+i+" element value of array : ");
a[i]=sc.nextInt();
System.out.println();
}
System.out.println("enter sum : ");
sum=sc.nextInt();
set(a,sum);
}
}
output :
import java.util.*;
public class sum2
{
public static Stack<Integer> find(int A[],int currSum,int index,int sum,int solution[],Stack<Integer> s)
{
if(currSum==sum)
{
int len=s.size();
if(len<=s.size() )
{
s.clear();
}
for(int i=0;i<solution.length;i++)
{
if(solution[i]==1) {
if(A[i]!=0 )
{
s.push(A[i]);
}
}
}
len=s.size();
return s;
}
else if(index==A.length)
{
return s ;
}
else
{
solution[index]=1;
currSum+=A[index];
find(A,currSum,index+1,sum,solution,s);
currSum-=A[index];
solution[index]=0;
find(A,currSum,index+1,sum,solution,s);
return s;
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Array size");
int size=sc.nextInt();
int A[] =new int[size];
System.out.println("Enter elements");
for(int i=0;i<A.length;i++)
{
A[i]=sc.nextInt();
}
System.out.println("Enter sum");
int sum=sc.nextInt();
int solution[]=new int[A.length];
Stack<Integer> s=new Stack<Integer>();
Arrays.sort(A);
find(A,0,0,sum,solution,s);
System.out.print("Output:" +s);
}
}
It took almost 3 days

Find the minimum number of operations after which P becomes an identity permutation

Consider a Permutation P of length n .
Let us define an operation on P as follows:
P[i]=P[P[i]]; for every i from 1 to n
for example:
P[n] = {2, 3, 1};
After 1 operation:
P[1] becomes P[P[1]] = P[2]= 3;
P[2] becomes P[P[2]] = P[3]= 1;
P[3] becomes P[P[3]] = P[1]= 2;
So, P becomes [3, 1, 2] ;
You need to find the minimum number of operations to be performed after which P becomes an Identity Permutation.
Output -1 if not possible.
Input 1:
P = [2 , 1];
Output 1:
1
As it will become Identity Permutation after 1 operation only.
Input 2:
P = [2 , 3 , 1];
Output 2:
-1
As Identity Permutation is not possible by the given operation.
I've tried to solve this code as follows, but I'm not getting the right way to solve it.
Java:
import java.util.Scanner;
public class Permutation {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System. in );
System.out.println("Enter the number of Test Cases");
int t = s.nextInt();
for (int i = 0; i < t; i++) {
System.out.println("Enter the number n");
int n = s.nextInt();
int[] arr = new int[n + 1];
for (i = 1; i <= n; i++) {
arr[i] = s.nextInt();
}
int count = 0;
int[] arr1 = new int[n + 1];``
arr1 = arr;
do {
for (i = 1; i <= n; i++) {
arr1[i] = arr1[arr1[i]];
}
count++;
}
while ( arr != arr1 );
System.out.println(count);
}
}
}
In this code,I loop until n! tries or when find the permutation.If check is true,then I found and can write the count,if count reaches the n! which means all permutations are done and I couldn't find the identity permutation and I write -1.Loop boundary is like that.Let's look at the algorithm.
I copied orijinal array to another array to don't lose any information.And after each iteration when array is changed,I also kept it.
After arr1[i] = arr[arr[i]];,I sorted the arr1 and check whether sorted arr1 is equal previous arr1 or not,if they are equals then I found the permutation,break the loop make check boolean true and print result,else iterate one more time.
import java.util.Arrays;
import java.util.Scanner;
public class Permutation {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Test Cases");
int t = s.nextInt();
for(int i=0;i<t;i++)
{
System.out.println("Enter the number n");
int n = s.nextInt();
int[] arr=new int[n+1];
for(i=1;i<=n;i++){
arr[i]=s.nextInt();
}
int count=0;
int[] arr1=new int[n+1];
arr1 = Arrays.copyOf(arr, arr.length);
boolean check;
do {
for (i = 1; i <= n; i++) {
arr1[i] = arr[arr[i]];
}
arr = Arrays.copyOf(arr1, arr1.length);
count++;
int [] temp = Arrays.copyOf(arr1, arr1.length);
Arrays.sort(arr1);
check = false;
for(int m =1;m<=n;m++){
if(arr1[m]==temp[m])
check = true;
else{
check = false;
break;
}
}
}
while(count<fact(n) && check!=true);
if(count == fact(n))
System.out.println("-1");
else
System.out.println(count);
}
}
public static int fact(int n){
int temp = 1;
for(int i=1;i<=n;i++)
temp*=i;
return temp;
}
}

java methods multiplying elements with in an array using a loop

Define a Java method named weightedSum() that takes two integer arrays as its arguments. The
method uses a loop to multiply corresponding elements of the two arrays together (i.e., it multiplies the first argument of each array together, followed by multiplying the second element of each array together, and so on) and returns the sum of those products (which is also an integer). You may assume that both arrays are of equal length.
public int weightedSum(int [] a ,int [] b)
{
int value;
int sum ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
value = value +value ;
}
return value;
I am having trouble writing this method out for my assignment . I under stand it accepts to arrays but i am having trouble writing out the loop itself so that it multiplies each individual element of the array with its counterpart in the opposite array so pos [1] * pos [1] and then add the two values togather with pos [2] + pos[2] and to get the sum total for all the values
below are the changes needed in your code. Basically you never updated the variable sum after you compute the product of corresponding elements in the two arrays. Also you might wanna use long type to store the result of the sum & the product as the int value might overflow if the elements in the array are sufficiently large.
public long weightedSum(int [] a ,int [] b)
{
long value = 0;
long sum = 0 ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
sum = sum +value ;
}
return sum;
}
Try this:
public long dotProduct(int [] a, int [] b) {
if (a == null) throw new IllegalArgumentException("a array cannot be null");
if (b == null) throw new IllegalArgumentException("b array cannot be null");
if (a.length != b.length) throw new IllegalArgumentException("arrays must have equal lengths");
long sum = 0L;
for (int i = 0; i < a.length; i++) {
sum += a[i]*b[i];
}
return sum;
}
Most of the code looks correct, however the second line in the loop should not be changing the value variable, the sum variable should be updated with the value.
something like sum += value.
then return sum.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter n :");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer[] arr = new Integer[n];
System.out.println("Enter Elements :");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
//Ascending Array
Arrays.sort(arr);
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Descending Array
Arrays.sort(arr,Collections.reverseOrder());
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Product Of First Four Elements Of Array
int product=1;
for(int i=0;i<4;i++)
{
product=product*arr[i];
}
System.out.println("Product : "+product);
}
}
/* Output
Hello World
Enter n :
5
Enter Elements :
4
5
9
8
6
Elements Are :
4
5
6
8
9
Elements Are :
9
8
6
5
4
Product : 2160
*/
import java.util.*;
public class DemoNew
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter N : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Float[] r = new Float[n];
System.out.println("Enter Distances : ");
for(int i=0;i<n;i++)
{
r[i]=sc.nextFloat();
}
System.out.println("Distances : ");
for(int i=0;i<n;i++)
{
System.out.println(r[i]);
}
for(int i=0;i<r.length;i++)
{
if(r[i] == 0.0)
{
System.out.println("Invalid");
break;
}
else if(r[i] < 0)
{
System.out.println("Invalid");
break;
}
else
{
//Descending Array
Arrays.sort(r,Collections.reverseOrder());
System.out.println("Distances in Descending Order Are :");
for(int j=0;j<n;j++)
{
System.out.println(r[j]);
}
System.out.println("3 Max Distances Are :");
for(int k=0;k<3;k++)
{
System.out.println(r[k]);
}
List<Float> list = Arrays.asList(r);
System.out.println(list);
/* Float[] ar = new Float[r.length];
for(int m=0;m<r.length;m++)
{
ar[m]=r[m];
}
System.out.println("Final Ans :"); */
break;
}
}
}
}
Change to this:
value += a[i] * b [i];
// value = value + value;
Also initialize value to 0 before using it.
Also remove the sum variable.

Splitting an array at multiple points using an index point

I have come across many examples to split the given array or array list into two arrays or multiple arrays using an index point. I tried them and they are working perfectly. My question is, is it possible to split the array into multiple arrays of varying chunk size given the index point?
For example:
array[] = {10,1,2,3,10,4,5,10,6,7,10,8,10};
index_value = 10;
Then the output should be four arrays such as:
arr1[] = {1,2,3}
arr2[] = {4,5}
arr3[] = {6,7}
arr4[] = {8}
I was able to split them and display the results when the given array is static with no changes. But implementing the same for an array with random numbers and random size was hard. I need to store the split values in many sub arrays and not just printing the values.
For this solution, the index_value does not have to be at the start or end of the array:
int[] arr = new int[]{10,10,1,10,1,2,3,10,4,5,10,6,7,10,8,10,9,8,7,6,5,4,3,10,1,2,3,4,5,6,7,10,5,4,10,10};
int index_value = 10;
/** walk through the array and create the arraylist of arraylists */
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currAl = null;
for (int i=0; i < arr.length; i++) {
if (arr[i] == index_value) {
if (currAl != null && currAl.size() > 0)
al.add(currAl);
currAl = new ArrayList<Integer>();
} else {
if (currAl == null)
currAl = new ArrayList<Integer>();
currAl.add(arr[i]);
}
}
if (arr[arr.length-1]!= index_value && currAl.size() > 0) {
al.add(currAl);
}
/** print out the arraylist of arraylists */
for (int i=0; i < al.size(); i++) {
currAl = al.get(i);
for (int j=0; j < currAl.size(); j++) {
System.out.print(currAl.get(j) + " ");
}
System.out.println();
}
You can build your arrays by using the ArrayList class to fill in your values
array[] = {10,1,2,3,10,4,5,10,6,7,10,8,10};
index_value = 10;
ArrayList<ArrayList<int>> allLists = new ArrayList<ArrayList<int>>();
ArrayList<int> currentList;
for (int i = 0;i < array.length;i++)
{
//in case your array doesn't contain the index_value at index 0
//check for the null case
if (array[i] == index_value || currentList == null)
{
currentList = new ArrayList<int>();
allLists.add(currentList);
}
else
{
currentList.add(array[i]);
}
}
if (allLists.size() > 0 && allLists.get(allLists.size() - 1).size() == 0)
{
allLists.remove(allLists.size() - 1);
}
What you should have is an ArrayList that contains ArrayLists that contain the numbers you are interested in. If the index_value is repeated twice in a row, however, you will end up with empty lists (which can be removed later). This includes the final list, which I automatically remove if it is empty (since your example lists the index_value as being at both the start and the end.
If you would like the output to be in arrays, you can just call .toArray() on the ArrayList
You might try the following strategy: look for your marker boundaries, form an array from each segment as encountered, and put result in a Vector (for example).
package com.splitter;
import java.util.Vector;
public class Splitter {
/**
* #param args
*/
public static void main(String[] args) {
int[] array = {10, 1,2,3,10,4,5,10,6,7,10,8,10};
Vector <int[]> result;
result = split(array,10);
for (int i = 0; i < result.size(); i++) {
int[] split = result.get(i);
System.out.println("Array " + i);
for (int j=0; j<split.length; j++) {
System.out.println(split[j]);
}
}
}
private static Vector<int[]> split(int[] array, int value) {
Vector<int[]> result = new Vector<int[]>();
int loc = 0;
int start = 0;
boolean isInside = false;
while (loc < array.length) {
if (array[loc] == value) {
if (isInside) { // make array from start to here
// make an array from start+1 to loc-1
System.out.println(" .." + start + " " + loc + " v=" + array[loc] );
int[] split = new int[loc - start - 1];
for (int i = 0; i < split.length; i++) {
split[i] = array[start+1+i];
}
result.add(split);
isInside = true;
}
start = loc;
isInside = true;
}
loc++;
}
return result;
}
}
I tried in NetBeans, debug, and works well.
The values will be stored like in a ArrayList with more ArrayLists inside, like this:
arrayOfIntList.get(0) = > 1,2,3
arrayOfIntList.get(0).get(0) -> 1
arrayOfIntList.get(0).get(1) -> 2
arrayOfIntList.get(0).get(2) -> 3
arrayOfIntList.get(1) = > 4,5
arrayOfIntList.get(1).get(0) -> 4
arrayOfIntList.get(1).get(1) -> 5
arrayOfIntList.get(2) = > 6,7
arrayOfIntList.get(2).get(0) -> 6
arrayOfIntList.get(2).get(1) -> 7
arrayOfIntList.get(3) = > 8
arrayOfIntList.get(3).get(0) -> 8
import java.util.ArrayList;
public class Javaprueba {
public static void main(String[] args) {
int[] myarray = {10,1,2,3,10,4,5,10,6,7,10,8,10};
int splitterInt = 10;
int j = 0;
int k = 0;
ArrayList<Integer> tempArray = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> arrayOfIntList = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<myarray.length; i++){
if(myarray[i] != splitterInt){
tempArray.add(j, myarray[i]);
j++;
}else{
if(tempArray.size() > 0){
arrayOfIntList.add(k, tempArray);
k++;
tempArray = new ArrayList<Integer>();
j=0;
}
}
if(i == myarray.length-1 && tempArray.size()>0){
arrayOfIntList.add(k, tempArray);
}
}
}
}

Removing duplicate elements from Array in Core Java

Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/
Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/
First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.
is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.
The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.
import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}
Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}
public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}
Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}

Categories

Resources