I have a binary number, how can I group the same digits in pairs and split the number on single zero?
For example:
JavaScript
x
4
1
1100000001111011011 11
2
3
[[11, 00, 00, 00], [11, 11], [11], [11, 11]]
4
Advertisement
Answer
You could use an iter
of the string to compare the current character to the next one. If they are the same, add them to the current block; if they are different, the first one must be the odd zero, so add twice the one after that to the next block.
JavaScript
1
9
1
s = "110011000110011000001111111100"
2
res = [[]]
3
it = iter(s)
4
for c in it:
5
if next(it) == c:
6
res[-1].append(c+c)
7
else:
8
res.append([next(it)*2])
9
Or using regular expressions to (a) get blocks of repeated values, (b) split those into chunks:
JavaScript
1
3
1
import re
2
res = [re.findall(r"00|11", b) for b in re.findall(r"(?:00|11)+", s)]
3
Both ways, res
is [['11', '00', '11', '00'], ['11', '00', '11', '00', '00'], ['11', '11', '11', '11', '00']]