In an array of only 1's and 0's how would you count no. of 1s and 0s without comparing and then modify it to array of 3s and 5s.
My approach is to use cumulative array such that cumulative[i]=array[i]+cumulative[i-1]. No of one=cumulative[n] number of zeroes =n-cumulative[n];
Is this approach correct ? Or suggest some other approach ?
Can we convert it into array's of 3's and 5's without comparing?
I think you can do this without using comparisons by relying on the fact that 0
is treated as False
in most languages and 1
is treated as True
.
Example: C, Python.
So, instead of comparing whether the value is 0 or 1, just use it as the conditional directly, and you should be able to do the job without comparison. You can use the same to count the occurances of 1
, and 0
.
In Python, this will translate into the following code
>>> original_list = [0, 1, 1, 1, 0, 1, 0]
>>> altered_list = [3 if item else 5 for item in original_list]
>>> print altered_list
[5, 3, 3, 3, 5, 3, 5]
You approach is correct. I also don't think it can be improved much - after all you need to iterate over all array elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With