Let’s consider a bidimensionnal array, declared as follow:
#include <stdbool.h>
bool array[N1][N2];
I have to know whether each line of this array have exactly one true value at the same position.
For example the following is ok:
{
{ 1, 0, 1, 0 },
{ 1, 0, 0, 1 },
{ 0, 0, 1, 1 }
}
Whereas this is incorrect:
{
{ 1, 0, 1, 0 },
{ 1, 0, 1, 0 },
{ 0, 0, 1, 1 }
}
I’ve tried this:
static uintmax_t hash(const bool *t, size_t n)
{
uintmax_t retv = 0U;
for (size_t i = 0; i < n; ++i)
if (t[i] == true)
retv |= 1 << i;
return retv;
}
static int is_valid(bool n)
{
return n != 0 && (n & (n - 1)) == 0;
}
bool check(bool t[N1][N2])
{
uintmax_t thash[N1];
for (size_t i = 0; i < N1; ++i)
thash[i] = hash(t[i], N2);
for (size_t i = 0; i < N1; ++i)
for (size_t j = 0; j < N1; ++j)
if (i != j && !is_valid(thash[i] & thash[j]))
return 0;
return 1;
}
But it works only with N1 <= sizeof(uintmax_t) * CHAR_BIT. Do you know a best way to solve it?
Why not just create another array that’s the size of N2 (number of columns), set it to all
true, thenandeach column in each row with that. In the end, check to see if your new array has exactly one set bit.