asked 169k views
1 vote
Compute the distance between the positions of the first and last zero element in the given array. for example, if the array is 3 0 1 0 4 9 5 0 6 your algorithm should yield 7 - 1 = 6. if the array contains a single zero, return 0. if it doesn't contain any zeroes, return a negative value.

Complete the following file:

Tester File:

Use the following file:

NumbersTester.java

public class NumbersTester

{

public static void main(String[] args)

{

double[] a = { 3, 0, 1, 0, 4 };

System.out.println(Numbers.zeroesDistance(a));

System.out.println("Expected: 2");

double[] b = { 0, 3, 0, 1, 0, 4 };

System.out.println(Numbers.zeroesDistance(b));

System.out.println("Expected: 4");

double[] c = { 3, 0, 1, 0, 2, 3, 0, 4 };

System.out.println(Numbers.zeroesDistance(c));

System.out.println("Expected: 5");

double[] d = { 0, 0, 0, 0, 0 };

System.out.println(Numbers.zeroesDistance(d));

System.out.println("Expected: 4");

double[] e = { 3, 1, 4 };

System.out.println(Numbers.zeroesDistance(e) < 0);

System.out.println("Expected: true");

double[] f = { };

System.out.println(Numbers.zeroesDistance(f) < 0);

System.out.println("Expected: true");

}

}

asked
User Leslye
by
7.6k points

1 Answer

3 votes

Final answer:

To calculate the distance between the first and last zero in an array, iterate through the array, store the positions of the first and last zero found, and subtract the first zero's position from the last zero's position. If no zeros are found, return -1, and if only one zero is found, return 0.

Step-by-step explanation:

To calculate the distance between the first and last zero elements in an array, you can iterate through the array to find the positions of the first and last zeroes. You can use two variables to store these positions, initializing them to -1 to indicate that they haven't been found yet. When the first zero is encountered, you set the first zero position variable, and with every zero you encounter, you update the last zero position variable. If no zeros are found, the initial value of -1 will indicate this. If only one zero is found, the positions of the first and last zero will be the same. The distance is then calculated by subtracting the position of the first zero from the position of the last zero. Here is a possible implementation of the 'zeroesDistance' method:

public static int zeroesDistance(double[] arr) {
int firstZero = -1;
int lastZero = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
if (firstZero == -1) {
firstZero = i;
}
lastZero = i;
}
}
if (firstZero == -1) {
return -1; // No zero found
}
if (firstZero == lastZero) {
return 0; // Only one zero found
}
return lastZero - firstZero;
}
This code will meet the requirements outlined in the student's question, yielding the correct distance or a negative value when zeros are absent from the array.

answered
User Selaron
by
8.0k points

No related questions found