Reputation: 693
I am trying to check whether an element of array has a successor.in other words, make the Ascending sublist to 0
and the rest to 1
. the first element of the inputArray
should be ignored
if yes then the both element should be 0
if not then 1
. For example: for the input
int[] arr = {1,8,1,9,10};
the output should be [1,1,1,0,0]
another example: for the input int[] arr = {1,2,3,9,100};
should the output be: [1,0,0,1,1]
This is my try, but it does not work as expected. Where am i making failur?
public class HelloWorld {
public static void main(String[] args) {
int[] arr = { 1, 8, 1, 9, 10 };
int[] listOutput;
for (int i = 1; i<arr.length - 1; i++) {
if (arr[i] - arr[i + 1] == -1) {
arr[i] = 0;
arr[i + 1] = 0;
} else {
arr[i] = 1;
}
}
System.out.println("Hello World");
for (int i = 0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Upvotes: 2
Views: 523
Reputation: 7068
public static void main(String[] args) {
int[] arr = { 1, 8, 1, 9, 10 };
// assume arr.length >= 2
boolean asc = arr[1] - arr[0] == 1;
for (int i = 1; i < arr.length - 1; i++) {
if (arr[i + 1] - arr[i] == 1) {
arr[i] = 0;
asc = true;
} else {
if (asc) {
asc = false;
arr[i] = 0;
}
else {
arr[i] = 1;
}
}
}
arr[arr.length - 1] = asc ? 0 : 1;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
This will replace each ascending (by 1) sublist of size greater than 1 with 0s, and will replace each remaining element with 1 (besides the first element which remains unchanged).
Upvotes: 1