Let say I've an std:array<int>
such as:
0 1 1 1 0 1 1 0
I'd like to use std (if possible) to do this in c++11:
- sum adjacent 1's
- erase the summed value
- transform 0 to 1
So getting this result for the example above:
1 3 1 2 1
Thanks
Let say I've an std:array<int>
such as:
0 1 1 1 0 1 1 0
I'd like to use std (if possible) to do this in c++11:
So getting this result for the example above:
1 3 1 2 1
Thanks
You could apply this logic with a single pass through the input values, while creating the result vector:
As to std::array
: as this is a fixed size data type, and the size of the result is unknown beforehand, I would use vectors instead. But I added the code to convert the array to a vector. If your requirements don't insist on array
, you could of course have your input represented by a std::vector
from the very start:
#include <iostream>
#include <array>
#include <vector>
std::vector<int> convert(std::vector<int> bin) {
std::vector<int> v;
int prevBit = 0;
for (auto bit : bin) {
if (bit & prevBit) {
v.back()++;
} else {
v.push_back(1);
}
prevBit = bit;
}
return v;
}
// Example run:
int main() {
std::array<int, 8> arr = {0, 1, 1, 1, 0, 1, 1, 0};
// Convert array to vector
std::vector<int> vec(std::begin(arr), std::end(arr));
// Apply conversion
std::vector<int> result = convert(vec);
// Output the result
for (auto val : result) {
std::cout << val << " ";
}
std::cout << std::endl;
}