Question:
You have an array of positive and negative integers, print all subsetsum which is equal to zero.
I have implemented only a simple test case here and the exception I get is ArrayIndexOutOfBoundsException.
Please help why the value is not incremented.
package app;
public class Array1
{
public static void subset(int p[])
{
int u = 0;
int s[] = new int[p.length];
if (p[0] < 0)
for (int i=0;i<p.length;i++)
{
for (int j = 0; j < p.length; j++) {
int k = p[i] + p[j];
if (k == 0)
{
System.out.println(p[i]);
System.out.println(p[j]);
s[u] = p[i];
u++; // Why u value is not incremented?
System.out.println(s[u]);
s[u] = p[j];
u++; // Why u value is not incremented?
System.out.println(s[u]);
}
}
}
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
public static void main(String s[])
{
subset(new int[] {-1, -2, -3, -4, 4, 3, 2, 1});
}
}
The problem is, int s[]=new int[p.length]; as the number of pairs can be more that (input array length itself) is the reason you get ArrayIndexOutOfBoundsException.
You can use a dynamic list for this purpose:
List<Integer> s = new ArrayList<Integer>();
// s.add(<elem>); // no need for variable u - increment :)
Related
supposed to return true if the first half of an array is equal to the second but it keeps return false... I tried debugging but still doesn't work... Help!
public class Main {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 1, 2, 3};
System.out.println(sda(arr));
}//main
public static boolean sda(int[] arr) {
int[] arr2 = new int[arr.length];
int[] arr3 = new int[arr.length];
for(int i = 0; i < (arr2.length/2); i++) {
arr2[i] = arr[i];
}
for(int i = arr.length - 1; i > (arr.length/2) - 1; i--) {
arr3[i] = arr[i];
}
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j] != arr2[j]) return false;
}
return true;
}
}
any suggestions?
Emmm... Well, a good resolve method is to debug on the value of arr2 and arr3. Then you'll find this:
int arr2[] = {1, 2, 3, 0, 0, 0};
int arr3[] = {0, 0, 0, 1, 2, 3};
Come on! Do it and resolve it.
If I break down the current code:
First arr2 and arr3 are assigned an empty array of 6 items.
Next arr2 is assigned values (1,2,3) in the first 3 elements of the array.
Then arr3 is assigned (1,2,3) in the final 3 elements of the array.
If I add the below code snipper under the 2nd for-loop:
System.out.println("arr2: ");
for(int i : arr2){
System.out.println(i);
}
System.out.println("arr3: ");
for(int i : arr3){
System.out.println(i);
}
You will see that that the two arays are different.
arr2:
1
2
3
0
0
0
arr3:
0
0
0
1
2
3
To make the result return true, you could adjust where the arr2 values are placed or adjust where the arr3 values are placed within the array.
An alternative solution would be to change the evaluation of the two array values in the final for-loop to be:
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j + (arr.length/2)] != arr2[j]) return false;
}
This way the evaluation of the two loops will be for the first 3 values of arr2 against the final 3 values of arr3.
In summary, I have changed the sda method to below:
public static boolean sda(int[] arr) {
int[] arr2 = new int[arr.length];
int[] arr3 = new int[arr.length];
for(int i = 0; i < (arr2.length/2); i++) {
arr2[i] = arr[i];
}
for(int i = arr.length - 1; i > (arr.length/2) - 1; i--) {
arr3[i] = arr[i];
}
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j + (arr.length/2)] != arr2[j]) return false;
}
return true;
}
public static boolean sda(int[] arr) {
for(int i=0, j=arr.length/2; i<arr.length/2 || j<arr.length; i++, j++)
if(arr[i]!=arr[j])
return false;
return true;
}
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'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]);
}
}
}
}
I am working on a problem and am having a hard time getting it to output the right information.
What I am trying to do is find every occurrence of a target value and put it into a new array and output the indexes of the target values. If no target value is found it returns an empty array. outputs {}
Right now I am getting an error.
findAll():
[I#349b688e
[I#46ed5d9d
java.lang.ArrayIndexOutOfBoundsException
The outputs should be:
outputs {0, 5}
outputs {}
public class FindIndex(){
public FindIndex() {
int a[] = {7, 8, 9, 9, 8, 7};
System.out.println("findAll(): ");
System.out.println(findAll(a, 7));
System.out.print(findAll(a, 2));
}
public int[] findAll(int a[], int num) {
int indexNum = 0;
int arrSize = 0;
// find all occurrence of the target number
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
arrSize++;
}
}
// create new array
int newArray[] = new int[arrSize];
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
newArray[indexNum] = i;
}
}
return newArray;
}
public void print(int a[]) {
System.out.print("{");
int i;
for(i = 0; i < a.length - 1; i++) {
System.out.print(a[i] + ", ");
}
if(a.length > 0) {
System.out.print(a[i]);
}
System.out.print("}\n");
}
}
You are never incrementing indexNum, it always remains at 0 and the array keeps on writing the values at this same index.
I think you should have this expression there:
newArray[indexNum++] = i;
For your printing problem, what you're actually printing out ther are the addresses of the arrays returned, not the contents.
What you can do is the following:
System.out.println(Arrays.toString(findAll(a, 7)));
System.out.print(Arrays.toString(findAll(a, 2)));
This will give you the following output:
[5, 0]
[]
Calling findAll(a, 2) gets zero size newArray that's why you get ArrayIndexOutOfBoundsException.
You should check if (arrSize > 0) before doing array with indexes and access it.
I was working with the code and got it to work but it is giving me added zeros in the new array. The output of the top sould be 0, 5 How do I get ride of these added zeros?
int a[] = {7, 8, 9, 9, 8, 7};
int array2[];
// print the occurrence of a target index value
System.out.println("findAll(): ");
array2 = copy(findAll(a, 7));
array2 = copy(findAll(a, 2));
public int[] findAll(int a[], int target) {
int index;
int found = 0;
// find all occurrence of the target number
for(int i = 0; i < a.length; i++) {
if(a[i] == target) {
found = target;
i++;
}
}
// create new array
int newArray[] = new int[found];
for(int i = 0; i < newArray.length; i++) {
if(a[i] == target) {
newArray[i] = i;
i++;
}
}
return newArray;
}
public int[] copy(int newArray[]) {
System.out.print("{");
int i;
for(i = 0; i < newArray.length - 1; i++) {
if (newArray.length == 0) {
System.out.print( " " );
} else {
System.out.print(newArray[i] + ", ");
}
}
System.out.print("}\n");
return newArray;
}
output:
findAll():
{0, 0, 0, 0, 0, 5, }
{}
private double[] myNumbers = {10, 2, 5, 3, 6, 4};
private double[][] result;
private double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
//System.out.println(result[0] +" "+ result[1]);
return result;
}
I'm trying to sort the one dimensional array in to a matrix, where numbers between 4 - 8 are in one, and all other numbers are in the other.
1) You're not initializing result[][]. You will get a NullPointerException.
Either loop through myNumbers, count the number of values for each category, and create result[][], or push your values into an ArrayList<Double>[2] and use List.toArray() to convert back to an array.
2) result[][] is declared outside your method. While technically valid, it's generally poor form if there is not a specific reason for doing so. Since you're already returning double[][] you might want to declare a double[][] inside your function to work with and return.
I'm not following exactly what you want, but this should allow your code to work.
class OneDimToTwoDim {
public static void main(String[] args) {
// declare myNumbers one dimensional array
double[] myNumbers = {10, 2, 5, 3, 6, 4};
// display two dimensional array
for (int x = 0; x < myNumbers.length; x++) {
System.out.print("[" + myNumbers[x] + "] "); // Display the string.
}
// pass in myNumbers argument for derp parameter, and return a two dimensional array called resultNumbers
double[][] resultNumbers = OneDimToTwoDim.divideNumbers(myNumbers);
System.out.println(); // Display the string.
System.out.println(); // Display the string.
for (int x = 0; x < resultNumbers.length; x++) {
for (int y = 0; y < resultNumbers[x].length; y++) {
System.out.print("[" + resultNumbers[x][y] + "] "); // Display the string.
}
System.out.println(); // Display the string.
}
}
private static double[][] divideNumbers(double[] derp) {
// declare result to be returned
double[][] result = new double[2][derp.length];
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
return result;
}
}
Your result array isn't initialized. Are you getting null pointer exceptions? Is that the problem?
private static double[] myNumbers = {10, 2, 5, 3, 6, 4};
private static double[][] result = new double[2][myNumbers.length];
private static double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
result[0] = Arrays.copyOfRange(result[0],0,k);
result[1] = Arrays.copyOfRange(result[1],0,j);
return result;
}