2-dimensional array in Java - java

Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?

The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){

You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}

I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}

I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}

Related

Showing java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 in some test cases?

Code:
static void exchangeColumns(int matrix[][])
{
int i;
int n = matrix[0].length;
for (i=0;i<n;i++){
int temp = matrix[i][0];
matrix[i][0] = matrix[i][n-1];
matrix[i][n-1] = temp;
}
}
You are using a wrong way to iterate the multi-dimensional array. Please use the following way to iterate through your array.
for (int i = 0; i < matrix.length; ++i) {
for(int j = 0; j < matrix[i].length; ++j) {
System.out.println(matrix[i][j]); // Here you can place your logic by accessing the array elements
}
}

What is wrong in my bubble sort using ArrayList?

What is wrong in my bubble sort in ArrayList? It was not sorted . I am a beginner.
public static ArrayList < Integer > bubbleSort(ArrayList < Integer > ar) {
for (int i = 0; i < ar.size() - 1; i++) {
int indexMax = i;
for (int j = 1; j < ar.size(); j++) {
if (ar.get(indexMax) > ar.get(j)) {
indexMax = j;
}
}
if (indexMax != i) {
int temp = ar.get(i);
ar.set(i, ar.get(indexMax));
ar.set(indexMax, temp);
}
}
return ar;
}
Are you sure you should start from 2nd element (j=1) every time?
Try j=i. i.e.,
public static ArrayList<Integer> bubbleSort (ArrayList<Integer> ar) {
for (int i = 0; i < ar.size() - 1; i++) {
int indexMax = i;
for (int j = i; j < ar.size(); j++) {
if (ar.get(indexMax) > ar.get(j)) {
indexMax = j;
}
}
if (indexMax != i) {
int temp = ar.get(i);
ar.set(i, ar.get(indexMax));
ar.set(indexMax, temp);
}
}
return ar;
}
P.S this will sort your array in ascending order.
Your swapping code block looked like it was outside of loop, so the only one swap occurred for one iteration of main loop.
You are also doing unnecessary comparing of elements, starting your inner loop with precondition j = 1. You should start it from i, as after some iterations of outer loop range from 0 to i will be already sorted.
I think you can use a simpler approach.
for (int i = 0; i < ar.size() - 1; i++) {
for (int j = i; j < ar.size(); j++) {
if (ar.get(j) < ar.get(i)) {
Integer temp = ar.get(j);
ar.set(j, ar.get(i));
ar.set(i, temp);
}
}
}
As you can see, swapping takes place inside of the inner loop, and it also skips already sorted part of collection.
You can do sorting like this:
for(int out=inputArray.size()-1; out>0; out--){
for(int j=1; j<=out; j++){
if(inputArray[j-1]<inputArray[j]){
//Swap the elements
int temp = inputArray[j];
inputArray[j]=inputArray[j-1];
inputArray[j-1]=temp;
}
}
}
return inputArray;
Can you try that?
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}

Making a nested for loop into a single for loop

I had an assignment to create an array of random number from 10-100.
Then I need to sout all the numbers not listed in the array.
I did the assignment with a nested for loops, to cross reference the arrays, then I changed all the found numbers in the array into -1. Finally I printed out the elements in the array that were not -1.
My professor told me that is it possible for me to do this assignment with only one for loop and there is no need to do a nested for loop. and make the computer run 10,000 times instead of just 100.
Is that possible? If so how?
Thank you.
package assignment.pkg1;
import java.util.Random;
public class Assignment1 {
static Random ran = new Random();
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
InversingArray(arr);
}
public static void InversingArray(int[] randomArray) {
int[] fullArray = new int[100];
for (int i = 0; i < 100; i++) {
fullArray[i] = i;
}
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
System.out.println("These numbers are not in randomArray: ");
for (int i = 0; i < 100; i++) {
if (fullArray[i] != -1) {
System.out.println(fullArray[i]);
}
}
}
In your code you create an array to hold the possible values. If you think about it, the array index will always be equal to the number stored in the array.
fullArray[i] = i;
This is redundant.
What you are being asked to do is determine which numbers have been used: a boolean test. This means that you should have an array of boolean that is initially false (the default value of booleans in java) and is flipped to true when an equal integer is flipped to true.
Something like
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
// ba starts with all false values
boolean ba[] == new boolean[90]; // note that the instructor said 10-100
for(int i=0; i<90; i++) {
ba[arr[i]] = true;
// lets assume arr[0] == 45
// ba[arr[0]] is the same as ba[45]
// ba[45] = true; will set that bucket of the boolean array to true
}
System.out.println("These numbers are not in randomArray: ");
for (int k = 0; k < 10; k++) {
System.out.println(k);
}
for (int j = 0; j < 90; j++) {
if (!ba[j]) { // shorthand for ba[j]==false
System.out.println(j+10); // The array starts at a base of 10
}
}
Be aware (probably the point of the exercise) that you are working with an array [0..90] that represents the numbers [10..100].
The nested loop currently looks like this:
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
But we know, that fullArray[i] is always the same as i.
So you can rewrite it to:
for (int j = 1; j < 100; j++) {
int i = randomArray[j];
fullArray[i] = -1;
}
Or even shorter:
for (int j = 1; j < 100; j++) {
fullArray[randomArray[j]] = -1;
}

How to dynamically control the for-loop nested level?

I am implementing some algorithm, in which the number of loop nested levels is determined by the input.
For example, if the input is 2-dimensional, then there two nested for-loops, as below:
for(int i=0; i<N; i++) {
for(int j=i+1; j<N; j++) {
if(table[i][j] == -1) {
for(int c=0; c<C; c++) {
int ii = table[i][c];
int jj = table[j][c];
sort(ii, jj);
if((T[ii][jj] != -1 && T[ii][jj] < l)) {
T[i][j] = l;
break;
}
}
}
}
}
If the input is 3-dimensional, then it would be something like below:
for(int i=0; i<N; i++) {
for(int j=i+1; j<N; j++) {
for(int k=j+1; k<N; k++) {
if(table[i][j][k] == -1) {
for(int c=0; c<C; c++) {
int ii = table[i][c];
int jj = table[j][c];
int kk = table[k][c];
sort(ii, jj, kk);
if((T[ii][jj][kk] != -1 && T[ii][jj][kk] < l)) {
T[i][j][k] = l;
break;
}
}
}
}
}
If there are only these two case, then I can write two versions of nested for-loops. But the dimensions of input could be any value between 2 and N. In this case, how to control the nested loop level dynamically, or is there any alternative to go around of this?
The only real way to do this is to use recursion.
You write a method containing a single for loop, each time around the loop if it needs to go deeper then the method calls itself with the right settings for that nested loop to be run.
Recursion is already been explained here. However, there is another solution as well. Using only one big loop containing a tiny inner loop.
int n = ...;
int dim = ...;
// Raise n to the power of dim: powN = n^dim
long powN = 1;
for (int i = 0; i < dim; ++i) powN *= n;
int[] indices = new int[dim];
for (long i = 0; i < powN; ++i)
{
// Calculate the indices
long bigI = i;
for (int k = 0; k < dim; ++k)
{
indices[k] = bigI % n;
bigI /= n;
}
// Now all your indices are stored in indices[]
}
I was suggesting something like this :
public static void recursiveLoop(int N, int level, int a){
if (level<0)
return;
for (int i=a; i<N; i++){
System.out.println("Level is : "+ level+ " i: "+i );
recursiveLoop(N,level-1,i+1);
}
}
You may explain what you really want to do.
If the Outer for loops are doing nothing but controlling a count, then your Nested for loops are simply a more complicated way of iterating by a count that could be handled by a Single for loop.
like:
for (x = 0; x < 8; x++) {
for (y = 0; y < 10; y++) {
for (z = 0; z < 5; z++) {
DoYourStuffs();
}
}
}
Is equivalent to:
for (x = 0; x < 8*10*5; x++) {
DoYourStuffs();
}

java.lang.ArrayIndexOutOfBoundsException Error

How do I fix this error and what does it mean?
java.lang.ArrayIndexOutOfBoundsException: 5
at Sort.sort(Sort.java:29)
at Sort.<init>(Sort.java:13)
at SortedArray.<init>(SortedArray.java:23)
Here is the code:
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
Scanner input = new Scanner(System.in);
int [] Array;
Sort sortedArray;
int sizeOfArray;
public SortedArray()
{
System.out.print("Enter the number of values to put in the array: ");
sizeOfArray = input.nextInt();
Array = new int [sizeOfArray];
System.out.println("");
for(int i = 0; i < sizeOfArray; i++)
{
Random r = new Random();
Array[i] = r.nextInt(100) + 1;
System.out.println(Array[i]);
}
sortedArray = new Sort(Array, sizeOfArray);
sortedArray.display();
}
}
public class Sort
{
int[] array;
int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
array = new int [sizeOfArray];
for( int i = 0; i < sizeOfArray; i++)
{
array[i] = oldArray[i];
}
sort();
}
public void display()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
I get the error when I run the program and enter the value. The program is supposed to sort the numbers from greatest to least. I'm not sure what is wrong.
First, what it means: you have an array and are trying to acces an index that is outside its range (below 0 or bigger or equal than the length of the array).
The probable cause is:
for (int j = 0; j < sizeOfArray; i++)
Notice that you check that j does not get too big but you are increasing i.
The Problem is that the inner loop also incrementsi which isn't correct in this situation!
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; j++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
Your problem is on this line
for (int j = 0; j < sizeOfArray; i++)
it should be
for (int j = 0; j < sizeOfArray; j++)

Categories

Resources