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 <
Related
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;
}
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!
I have an array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
I'm trying to split it into a two-dimensional array with x amount of chunks, where all of the chunks have an equal length (in my case, 2), then assign each value of the original array to a corresponding index within the array. It would then increment the index of the chunk number and reset the index iterating through the individual arrays hit the length of one.
Problem is, the code I wrote to perform all that isn't outputting anything:
public class Debug
{
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
private static void chunkArray(int chunkSize)
{
int chunkNumIndex = 0;
int chunkIndex = 0;
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++)
{
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
while(chunkNumIndex < numOfChunks)
{
if (chunkIndex == chunkSize)
{
chunkNumIndex++;
chunkIndex = 0;
}
}
}
for(int i = 0; i < chunkNumIndex; i++)
{
for(int j = 0; j < chunkIndex; j++)
{
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
chunkArray(2);
}
}
Could anyone be of assistance in debugging my program?
The problem is that you have an unnecessary while(chunkNumIndex < numOfChunks) which makes no sense. The if statement is sufficient to iterate your variables correctly:
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
if (chunkIndex == chunkSize) {
chunkNumIndex++;
chunkIndex = 0;
}
}
Also, remember that the values of chunkNumIndex and chunkIndex are dynamic, so for the last for loops, use twoDimensionalArray.length and twoDimensionalArray[0].length instead:
for(int i = 0; i < twoDimensionalArray.length; i++) {
for(int j = 0; j < twoDimensionalArray[0].length; j++) {
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
}
You're making this unnecessarily hard, there is no need to keep counters for chunkIndex and chunkNumIndex, we can just div and mod i.
int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}
Something like this should already do the job.
I need to have an algorithm that changes values in one array if it is in the second array. The result is that the first array should not have any values that are in the second array.
The arrays are of random length (on average ranging from 0 to 15 integers each), and the content of each array is a list of sorted numbers, ranging from 0 to 90.
public void clearDuplicates(int[] A, int[] B){
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
A[i]++;
}
}
My current code does not clear all of the duplicates. On top of that it might be possible it will creat an index out of bounds, or the content can get above 90.
Although your question is not very clear, this might do the job. Assumptions:
The number of integers in A and B is smaller than 90.
The array A is not sorted afterwards (use Arrays.sort() if you wish to
fix that).
The array A might contain duplicates within itself afterwards.
public void clearDuplicates(int[] A, int[] B) {
// Initialize a set of numbers which are not in B to all numbers 0--90
final Set<Integer> notInB = new HashSet<>();
for (int i = 0; i <= 90; i++) {
notInB.add(i);
}
// Create a set of numbers which are in B. Since lookups in hash set are
// O(1), this will be much more efficient than manually searching over B
// each time. At the same time, remove elements which are in B from the
// set of elements not in B.
final Set<Integer> bSet = new HashSet<>();
for (final int b : B) {
bSet.add(b);
notInB.remove(b);
}
// Search and remove duplicates
for (int i = 0; i < A.length; i++) {
if (bSet.contains(A[i])) {
// Try to replace the duplicate by a number not in B
if (!notInB.isEmpty()) {
A[i] = notInB.iterator().next();
// Remove the added value from notInB
notInB.remove(A[i]);
}
// If not possible, return - there is no way to remove the
// duplicates with the given constraints
else {
return;
}
}
}
}
You can do it just by using int[ ] although it's a bit cumbersome. The only constraint is that there may not be duplicates within B itself.
public void clearDuplicates(int[] A, int[] B) {
//Number of duplicates
int duplicate = 0;
//First you need to find the number of duplicates
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++)
if (A[i] == B[j])
duplicate++;
}
//New A without duplicates
int[] newA = new int[A.length-duplicate];
//For indexing elements in the new A
int notDuplicate = 0;
//For knowing if it is or isn't a duplicate
boolean check;
//Filling the new A (without duplicates)
for (int i = 0; i < A.length; i++) {
check = true;
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
check = false;
notDuplicate--;//Adjusting the index
}
}
//Put this element in the new array
if(check)
newA[notDuplicate] = A[i];
notDuplicate++;//Adjusting the index
}
}
public class DuplicateRemove {
public static void main(String[] args) {
int[] A = { 1, 8, 3, 4, 5, 6 };
int[] B = { 1, 4 };
print(clear(A, B));
}
public static int[] clear(int[] A, int[] B) {
int a = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
a++;
for (int k = i; k < A.length - a; k++) {
A[k] = A[k + 1];
}
}
}
}
int[] C = new int[A.length - a];
for (int p = 0; p < C.length; p++)
C[p] = A[p];
return C;
}
public static void print(int[] A) {
for (int i = 0; i < A.length; i++)
System.out.println("Element: " + A[i]);
}
}
Here is an example.. I compiled and its working. For any question just let me know :)
maybe you should try the following code:
public void clear (int[] A, int[] B)
{
for (int i=0; i<A.length;i++)
{
for (int j=0; j<B.length; j++)
if(A[i]==B[j])
{
for (int k=i; k<A.length;k++)
A[k]=A[k+1];
j=B.length-1; //so that the cycle for will not be executed
}
}
}
I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}