There is a question as follows: Rearrange an array such that arr[i] = i , and if i is not present in the array, set it to -1.
Here is the solution of the question:
int main() {
int arr[] = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n;) {
if (arr[i] >= 0 && arr[i] != i)
arr[arr[i]] = (arr[arr[i]] + arr[i]) -
(arr[i] = arr[arr[i]]);
else
i++;
}
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
I am not getting what arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]) line means. Why are we assigning arr[i] a new value ?
Why don't we subtract directly?