I have to find an algorithm to solve this question :
You have an array with n integers in it. Make an algorithm that changes array so that there are no consecutive expressions in it and returns the amount of changes to be made.
For example in array [1,1,2,2,2] the smallest amount of changes is 2 to get it to [1,3,2,1,2].
[1,2,3,4,5] results output "0", [1,1,1,1,1] results output "2".
I have to change as less values as possible and my code does work as intended. On the other hand, I have the impression that it is not very efficient. What do you think ? Here it is :
import java.util.Arrays;
public static int untilNoConsecutive(int[] arr) {
int rounds = 0;
int arrSize = arr.length;
for (int i = 0; i < arrSize - 2; i++) {
if (arr[i] == arr[i + 1]) {
arr[i + 1]++;
if (arr[i + 1] == arr[i + 2])
arr[i + 1]++;
rounds++;
}
}
if (arr[arrSize - 2] == arr[arrSize - 1]) {
arr[arrSize - 1]++;
rounds++;
}
System.out.println(Arrays.toString(arr)); // for testing purpose
return rounds;
}
public static void main(String[] args) {
int arr[] = { 1, 1, 2, 1, 1 };
int arr2[] = { 1, 2, 3, 4, 5 };
int arr3[] = { 1, 1, 1, 1, 1 };
System.out.println(untilNoConsecutive(arr));
System.out.println(untilNoConsecutive(arr2));
System.out.println(untilNoConsecutive(arr3));
Thanks.
1 Answer 1
I'd avoid repeating the logic outside the loop. Just let the loop run until i < arrSize - 1
, and add the condition i + 2 < arrSize
to the inner if
.
If I'm not mistaken, if the inner if
condition is true, then the next loop unnecessarily checks the same values again, so I believe you could add i++
to that inner if
block.
Finally some style remarks:
- You should always use braces, even on one line blocks.
- I'm not really happy with the variable names:
arr
should probably be calledarray
or maybe something that doesn't represent the data format such asnumbers
.arrSize
could just be calledsize
orlen(gth)
.- And
rounds
should (based on the task description) bechanges
.
-
\$\begingroup\$ Okay, so I did what you said. Thank you very much! You were right about the inner if condition, I had not much to change to get this to work. I'm used to my teacher doing those one line blocks without the braces so that's why... I also changed this! Also thanks for those remarks about variable names. I will try to do so now. \$\endgroup\$lux– lux2022年01月22日 16:35:50 +00:00Commented Jan 22, 2022 at 16:35