Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count no. of 1s and 0s without comparing

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?

like image 582
NEW USER Avatar asked Apr 17 '15 08:04

NEW USER


2 Answers

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]
like image 69
Anshul Goyal Avatar answered Sep 19 '22 05:09

Anshul Goyal


You approach is correct. I also don't think it can be improved much - after all you need to iterate over all array elements.

like image 43
Ivaylo Strandjev Avatar answered Sep 20 '22 05:09

Ivaylo Strandjev