How to receive arrays parameters and return? - java

public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {5, 6, 7, 8, 9};
System.out.println("same data are " + compareArray(arr1, arr2));
}
public static int compareArray(int[] arr1, int[] arr2) {
// TODO Auto-generated method stub
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
i = compareArray(arr1, arr2);
}
}
}
return compareArray(arr1, arr2);
}
this question is : receives two arrays as parameters and returns the number of matching data.
how do i output "same data are 2"?

You can solve this using a Set as well. Add the elements of arr1 (or you can add elements of arr2 according to your choice) into a Set and check whether the Set contains elements of arr2. If yes, increment the count.
public static int compareArray(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for(int i : arr1)
set.add(i);
int count = 0;
for(int i : arr2) {
if(set.contains(i))
count++;
}
return count;
}
In your logic, just use a count variable as shown below:
public static int compareArray(int[] arr1, int[] arr2) {
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
count++;
}
}
}
return count;
}

No need to call compareArray method recursively. Instead you can modify your method to:
public static int compareArray(int[] arr1, int[] arr2) {
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
count++;
}
}
}
return count;
}

Related

Index out of bounds Java merge sort?

I am working on a merge sort algorithm. Below is what i have written so far. The problem is when I try and run it to see if it is working I get the index out of bounds error on the if statement I marked with a comment.
Why am I getting index out of bounds on the line I commented next to?
I know what the error means but am unable to decipher why its out of bounds.
public class MergeSort {
public static int mergeSort(int[] list1, int[] list2) {
int[] list3 = new int[list1.length + list2.length];
int smallest1 = list1[0];
int smallest2 = list2[0];
int position1 = 0;
int position2 = 0;
for (int i = 0; i<list1.length + list2.length; i++) {
for (int j =0; j<= list1.length; j++) {
if (list1[j] < smallest1) { //here index out of bouds
smallest1 = list1[j];
System.out.print(list1[j]+"smallest value");
position1 = j;
}
}
for (int l =0; l<= list2.length; l++) {
if (list2[l] < smallest2) {
smallest2 = list2[l];
System.out.print(list2[l]+"smallest value");
position2 = l;
}
}
if (smallest1< smallest2) {
list3[i] = smallest1;
} else if (smallest2< smallest1) {
list3[i] = smallest2;
}
}
//print the array
for (int l =0; l<= list2.length; l++) {
System.out.print("new array 3" + list3[l]);
}
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list1 = {17, 22, 35, 42, 60};
int[] list2 = {9, 14, 66};
int[] list3;
mergeSort(list1, list2);
}
}
Indexes run from 0, this means when list1.length = 5 then the index can be 0 through 4
change
for (int j =0; j<= list1.length; j++)
to
for (int j =0; j < list1.length; j++)
This is because your for loop condition is <=. Try to use <

Need to find and store the duplicate numbers in a array in another array but dont know how to put the duplicate's in another array

I have found out the duplicate numbers in the array "a" but could not store the duplicate ones in another array "b". Any help much appreciated!
Here is my code:
public static void main(String[] args) {
int[] a = {1,2,3,3,5,6,1,7,7};
int[] b={};
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i]==(a[j])){
System.out.println(a[j]);
}
}
}
Because the length of result is not know, I would like to use a ArrayList instead of an array :
int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7};
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j] && !b.contains(a[j])) {
b.add(a[j]);
System.out.println(a[j]);
}
}
}
System.out.println(b);//result : [1, 3, 7]
You can try finding duplicates in an array using collections framework too:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
int[] a = {1,2,3,3,5,6,1,7,7};
Set<Integer> set=new HashSet<Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i:a) {
if(!set.add(i)) {
list.add(i);
}
}
int[] b=new int[list.size()];
for (int i=0;i<list.size();i++) {
b[i] =list.get(i);
}
}
}
Here I have used the fact that sets do not allow duplicate and if set.add returns false, that means that element is already available in the set
We cannot change the size of Array once it is initialized. Here we do not know how many duplicates item will be in the Array.
EDIT -- This might be a better solution, my earlier solution was throwing ArrayIndexOutOfBoundException as indicated by #YCF_L --
import java.util.Arrays;
public class T {
public static void main(String[] args) {
//int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7}; //Set-1, provided by #YCF_L
int[] a = {1,1,3,3,5,6,1,7,7}; //Set-2, provided by OP
int[] b = {};
for (int i=0, k=0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i] == a[j]){
System.out.println(a[j]);
k = k+1;
int[] p = new int[k];
for(int x=0; x < b.length; x++) {
p[x] = b[x];
}
p[k-1] = a[i];
b = p;
}
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(removeDuplicates(b)));
}
public static int[] removeDuplicates(int[] a) {
boolean[] bArr = new boolean[1000];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (!bArr[a[i]]) {
bArr[a[i]] = true;
j++;
}
}
int[] b = new int[j];
int c = 0;
for (int i = 0; i < bArr.length; i++) {
if (bArr[i]) {
b[c++] = i;
}
}
return b;
}
}
Output with Set-1 :
[1, 3, 7]
[1, 3, 7]
Output with Set-2 :
[1, 1, 1, 3, 7]
[1, 3, 7]

Algorithm for combinations of integer in an array

I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-‌​2,-3,4,5},{1,-2,3,-4‌​,5}, {1,-2,3,4,-5}...‌​. or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5},‌ ​{1,-2,-3,4,-5}, {1,2,‌​-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!

Swapping two elements in an array

I'm doing mooc.fi, my code works but it won't submit.
errors I'm getting
the method swap does not work correctly with parameter 4, 7, 8, 6 index1=0 index2=3
the result was 4, 7, 8, 6 but it should have been 6, 7, 8, 4
and
the method sort does not work correctly with parameter 10, 20, 6, -1, 13, 11
the result was 10, 20, 6, -1, 13, 11 but it should have been -1, 6, 10, 11, 13, 20
I know the errors are connected but I'm not too sure what to do to fix this, any help is appreciated! thank you!
My Code:
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int start = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < start) {
start = array[i];
}
}
return start;
}
public static int indexOfTheSmallest(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == smallest(array)) {
return i;
}
}
return 0;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int minIndex = index;
for (int i = index; i < array.length; i++) {
if (array[i] < array[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
public static void swap(int[] array, int index1, int index2) {
int hold = 0;
for (int i = 0; i < array.length; i++) {
hold = array[index1];
array[index1] = array[index2];
array[index2] = hold;
}
}
public static void sort(int[] array) {
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
swap(array, i, indexOfTheSmallestStartingFrom(array, i));
System.out.println(Arrays.toString(array));
}
}
public static void main(String[] args) {
int[] values = {8, 5, 3, 7, 9, 6, 1, 2, 4};
sort(values);
}
}
This algorithm is designed very badly. both smallest and indexOfSmallest use a loop, this will degrade geometrically.
The swap should not be scanning the entire array as you only want to swap two elements, not all of them!
You're effectively doing a whack version of a bubble-sort, but in a really convoluted way with too many loops. This will start to perform horribly with any decent sized list.
A much simpler version can be found here
You do not need a loop for the swap method. As you only want to change the two element once and not n-times (which results in not swapping them at all if n is an even number).
public int[] swapArrayElement(int arr[], int a, int b) {
int index1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == a || arr[i] == b) {
index1 = i;
if (arr[i] == a) {
for (int k = index1; k < arr.length; k++) {
if (arr[k] == b) {
arr[k] = arr[index1];
arr[index1] = b;
}
}
return arr;
} else if (arr[i] == b) {
{
for (int k = index1; k < arr.length; k++) {
if (arr[k] == a) {
arr[k] = arr[index1];
arr[index1] = a;
}
}
}
return arr;
}
}
}
return arr;
}

How can I remove this occurrence in my arraylist instead of just checking if it occurs

The code below if passed set1 = {1, 2, 4, 5, 4, 5} and set2 = {4,5,4} since 4,5,4 occurs consecutively in set1, I want that instead of the following method returning true or false, it removes the consecutive occurrence that is {4, 5, 4} from set1 so set1 = {1,2,5}.
public static boolean contains(ArrayList<Integer> set1, ArrayList<Integer> set2) {
OUTER:
for (int i = 0; i < set1.size() - set2.size(); i++) {
for (int j = 0; j < set2.size(); j++) {
if (!set1.get(i + j).equals(set2.get(j)))
continue OUTER;
return true;
}
return false;
}
First, I renamed your contains to indexOf and modified it to use the List interface and return an int representing the matching index
public static int indexOf(List<Integer> set1, List<Integer> set2) {
OUTER: for (int i = 0; i < set1.size() - set2.size(); i++) {
for (int j = 0; j < set2.size(); j++) {
if (!set1.get(i + j).equals(set2.get(j)))
continue OUTER;
return i;
}
}
return -1;
}
Then a method to call remove() for all of the matching elements like,
public static void removeLinearMatch(List<Integer> al, List<Integer> bl) {
int size = (bl != null) ? bl.size() : 0;
int index = indexOf(al, bl);
while (index > 0 && size > 0) {
al.remove(index);
size--;
}
}
Finally to test,
public static void main(String[] args) {
List<Integer> al = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 4, 5));
List<Integer> bl = new ArrayList<>(Arrays.asList(4, 5, 4));
removeLinearMatch(al, bl);
System.out.println(al);
}
And I get the requested output of
[1, 2, 5]
You could also achieve this by adding another loop:
public static boolean remove(ArrayList<Integer> set1, ArrayList<Integer> set2) {
OUTER: for (int i = 0; i <= set1.size() - set2.size(); i++) {
for (int j = 0; j < set2.size(); j++) {
if( !set1.get(i + j).equals(set2.get(j))) continue OUTER;
}
for (int j = 0; j < set2.size(); j++){
set1.remove(i + set2.size()-1 - j);
}
return true;
}
return false;
}
Returns true if the first set has been modified, false if not.

Categories

Resources