How to jump over a specific number in a loop - java

Didn't know how to call my Thread.
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[j] = numbers[j];
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++){
int k = i;
while(thisTuple[k] <= 0){
k++;
}
newTuple[i] = thisTuple[k];
}
this.tuple = newTuple;
}
This is my code snippet to create a new NaturalNumberTuple.
So this is the Array I want to use: int[] tT2 = {1,2,4,-4,5,4,4};
I only want to use natural numbers greater than 0 and my problem isn't to cut out the negative number but it is that my console is giving me this: Tuple(Numbers:1,2,4,5,5,4).
The problem is if I jump over that value which is negative with my while loop to get the higher (k) I will have to pass the same (k) in my for loop which I don't want to because I already got it in my Array. I hope you understand my problem.
Sorry for the bad english..
Edit: Can't use any methods from java itself like System.arrayCopy

You have an error in the first loop. Fixing it makes the second loop much simpler :
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; // changed thisTuple[j] to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++) {
newTuple[i] = thisTuple[i];
}
this.tuple = newTuple;
}
Of course, the second loop can be replaced with a call to System.arrayCopy.

I would change your while loop to an if that simply restarts the for loop. Say from this:
while(thisTuple[k] <= 0){
k++;
}
To something like this:
if (thisTuple[k] <= 0)
continue;
This stops you from adding the same number twice when you encounter a negative or zero number.

This code will solve you issue. The code is checked in the following link Tuple Exampple
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; //Change to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < count; i++){
newTuple[i] = thisTuple[i];
}

Related

Program which counts minimum of a two dimensional int array

I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}

I cant figure out this array

Im doing some personal work, and I am using this array that I thought of, but I cant figure out whats the array is after the code stops running.
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
}
}
I am pretty sure that it ends at [2][1] but I am not 100% sure of it
Just tried this code:
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
System.out.print(numarray[j][i]+" ");
}
System.out.println("");
}
and got this result:
0 1
2 3
4 5
The 'cnt' is incremented by 1 for each iteration. That's why you have 0,1,2,3,4,5.
Also learn how to use debugger in an IDE, you can then explore the value of i, j, cnt by yourself.
why don't you try this?
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
System.out.println(String.format("array[%d[%d]=%d",j,i,numarray[j][i]));
cnt++;
}
}
you can iterate the array after code finish
for(int i = 0; i < 2; i++) {
for(int j = 0; j< 3; j++) {
System.out.print(numarray[i][j]+" ");
}
System.out.println();
}
summary: cnt is incremented by 1 for each iteration in the inner for loop.
cnt is being incremented by 1 i.e. cnt++ is same as cnt = cnt + 1;
so count values increment from 0 i.e. 0,1,2,3,4,5... Also note, the value of cnt is assigned to the array being created, where you have numarray[j][i] = cnt;
You can simply printout the value using System.out.println(cnt);

Arrays in for loops

I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20

ArrayIndexOutOfBounds in sorting

I've written my sorting problem as follows, but i am getting an ArrayIndexOutOfBounds exception.
which i'm not able to figure it out. plz help.
System.out.println("Enter the total no of digits to sort:- ");
n = Integer.parseInt(br.readLine());
x = new int[n];
System.out.println("Enter the elements:- ");
for(i = 0; i < n; i++)
x[i] = Integer.parseInt(br.readLine());
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(x[j] > x[j+1]) //ascending order
{
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
Since j goes up to n, j+1 is out of bound. You need to change it to
for(j=0;j<n-1;j++)
Doing so would make sure that x[j+1] is within bounds.
Error is here:
if(x[j] > x[j+1]) {
....
Because j+1 is equal ton
Make this change:
for(j=0;j + 1<n;j++) {
...

Removing and replacing arrays

Basically, I am given an array of numbers and I have to count all the negative numbers.
Then make a new array that contains all of the positive numbers from the previous with the length of the array being firstarray-numberOfNegatives
Here is my code:
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length-1; i++)
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
I am getting the wrong result: negative numbers are replaced with 0s
At first write i < numbers.length; or i <= numbers.length-1; instead of i < numbers.length-1;
And then fix code.
Also note that you can have zeros in your 'numbers' array, so in if() in first for() you should write <=0 instead of <0
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] > 0) numbers2[count] = numbers[i];
count++;
System.out.println(numbers2[count-1]);
}
Firstly: you have an off-by-one error in your first for loop. Walk through some small example arrays in your head or on paper and you'll see.
Secondly: I think you are using your two index counters backwards in the second section. The count is supposed to be used in your new array, and i in your old one.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++) //
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) numbers2[count++] = numbers[i]; //
}
numbers = numbers2;
}
Run through a debugger and watch this line...
That -1 is suspicious
for(int i = 0; i < numbers.length-1; i++)
:)
Need to reverse your index variables in the second pass. Also the first loop had a length-1 instead of length. The second loop should go over the full length of the original array not the resulting array.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++)
if (numbers[i] < 0)
numberOfNegative++;
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) {
numbers2[count] = numbers[i];
System.out.println(numbers2[count]);
count++;
}
}
numbers = numbers2;
}
In
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
You are iterating as many times as numbers2 has positions, however, you increase i at every pass (in the for loop) regardless of whether you fund a positive number or not. Your output arrray would therefore have the first numbers2.length positive integers of numbers interleaved with a bunch of 0s!

Categories