How is it possible to iterate over all subsets of a set represented by bits? [closed] - bit-manipulation

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I was going though this article and it explains
It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don’t mind visiting them in reverse order (if this is problematic, put them in a list as they’re generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just i = (i - 1) & superset.
I'm not able to understand it despite re-reading several times. Could someone explain with some example?

If we have some set represented as a bitmask, for example if we have the universe:
U = { A, B, C, D, E, F, G }
Then the consonants S = { B, C, D, F, G } could be represented as 0b1101110 (read from the right, the least significant bit corresponds to A), and we can iterate through subsets of this set with:
i = (i - 1) & S
Because subtracting 1 will borrow through any trailing zeroes and unset the lowest set bit, then & S clears up any bits that became set this way but are not in S. For example:
i0 = 0b1101110 (the whole S)
i1 = i0 - 1 & S = 0b1101110 - 1 & S = 0b1101101 & S = 0b1101100
So the next subset is { C, D, F, G }, dropping B for now. Then the next is
i1 = 0b1101100
i2 = i1 - 1 & S = 0b1101100 - 1 & S = 0b1101011 & S = 0b1101010
Which represents { B, D, F, G }.
By the way it can be done forwards without storing the whole thing in a list:
i = ((i | ~S) + 1) & S
Here we need an extra | ~S to set the "in between"-bits to make the + 1 carry through them, otherwise it's the same idea.

Related

Java8 - how to determine if each element in a sorted list is one less that previous? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed yesterday.
Improve this question
I have a list of ints that is sorted in order of highest > lowest:
I want to determine if each list element is one less than the previous, how can I do so, ideally using streams?
This would pass:
10
9
8
7
This would fail:
10
8
7
6
You can use IntStream to process the list sequentially and compare the previous index value if it is one more than the current one
public static void main(String[] args) {
List<Integer> sequentList = Arrays.asList(10, 9, 8, 7);
List<Integer> nonSequentList = Arrays.asList(10, 8, 7, 6);
System.out.println(isInSequence(sequentList));
System.out.println(isInSequence(nonSequentList));
}
private static boolean isInSequence(List<Integer> sequentList) {
return IntStream.range(1, sequentList.size())
.allMatch(i -> (sequentList.get(i - 1) - sequentList.get(i)) == 1);
}
There are multiple solutions to solve the problem, streams are hardly the ideal one in this case, both in terms of efficiency or readability:
Using streams:
One example could be:
private boolean isContiguousListWithStreams(List<Integer> sortedDescInput) {
return IntStream.range(1, sortedDescInput.size())
.noneMatch(i -> sortedDescInput.get(i - 1) - sortedDescInput.get(i) != 1);
}
Using For loop:
In this simple scenario, streams might just answer it as readable and efficient, but just to point out that in many complex scenarios, a simple for loop can be just what's needed and it can be as efficient and readable (if not more).
private boolean isContiguousListWithLoop(List<Integer> sortedDescInput) {
for (int i = 1; i < sortedDescInput.size(); i++) {
if (sortedDescInput.get(i - 1) - sortedDescInput.get(i) != 1) {
return false;
}
}
return true;
}
Using neither:
Since it was established that the input list is sorted in descending order, neither streams nor for loops are actually needed, a simple first - last + 1 == length formula will do:
private boolean isContiguousList(List<Integer> sortedDescInput) {
return sortedDescInput.size() < 2
|| sortedDescInput.get(0) - sortedDescInput.get(sortedDescInput.size() - 1) + 1 == sortedDescInput.size();
}
Please note that the efficiency of any of these solutions will depend on the underlying implementation of the list (e.g. Array lists are efficient to access based on an index, unlike linked lists).

Checking equality/inequality of multiple variables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's say we have four variables: int a, b, c, d;. I need to check if excatly two of them are equal.
So for example: 1 1 9 5 is true, but 3 9 8 4 and 3 3 3 1 are false.
Of course writing an if statement for this would take a lot of time, won't be easily readable and it would be easy to make a mistake writing it.
What is the best way to write such statement?
There are several ways to do this.
One involves explicitly checking all the conditions. Since you have 4 variables, you only 6 conditions to check. These can easily be counted.
int n = (a == b) + (a == c) + (a == d) + (b == c) + (b == d) + (c == d);
Then check if n is 1. This works because a boolean value will be converted into an int (value 1 for true, 0 for false).
Another possibility is to store them all in a container (like a vector), sort it, then count the number of adjacent identical values.

use of: index & 0x01 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set.
index & 0x01
will be 1 if and only if index is odd.
If we have to deduce a general rule, we can say that for any non-negative number x,
x % y == (x & (y - 1))
provided that y is a positive power of 2.
This is a common hack in competitive coding. It is used because the competitive programmers think that bit-wise AND works faster than modulo.
In modern compilers, there is no performance difference at all. Read this thread.
There is no special reason in writing it as 0x01 instead of 1. Both compile to give the same assembly! Almost everyone (who uses this hack),= uses 1, because we have to type 3 characters extra in 0x01. :P
Here in this case, index & 0x1 is equivalent to index % 2 which is simply a condition to check if the number is odd. (Array indexes in C++ are always positive, unless you are going out of bound.)
As the other answers pointed out, while this is a well known pattern (see also this Q&A about that mask), it can be considered a premature optimization.
I'd like to suggest the following alternative to the posted code, which I find more readable. Your mileage may vary.
// Give a meaningful name.
constexpr auto is_odd = [] (auto x) -> bool {
return x % 2;
}
// Use it to simplify the condition.
if ( (arr[index] < 0) == is_odd(index) ) {
// Do something
}

Allocating memory of a variable with the size of a 2D vector [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Here's my code, I have a 2D vector and I need to take the size of its row and column to a new variable known as visited ,but throwing an error
int main() {
vector<vector<char>>a;
int n= a.size();
int m = a[0].size();
bool vertices= new bool [n][m];
}
Getting this error
Line 5: Char 33: error: array size is not a constant expression
> bool vertices= new bool [n][m];
> ^ Line 5: Char 33: note: read of non-const variable 'm' is not allowed in a constant expression Line 4:
> Char 9: note: declared here
> int m = a[0].size();
> ^ 1 error generated.
Unable to resolve
The original code tries to determine the number of hits required by summing the widths of the three blocks (w = w1 + w2 + w3;) and repeatedly dividing that by the strength S until the remaining width w becomes zero. If the strength S is 1 (and therefore w1, w2 and w3 are all 1 and their sum is 3), that will loop forever, causing the time limit for the code to be exceeded.
Also, it is not clear how the problem could be solved by division. Rather, the problem as stated involves subtraction, not division.
Since there are only three bricks in the stack (and S is at least the width of the largest brick), there are only three cases to consider:
if (s >= w1 + w2 + w3)
hits = 1;
else if (s >= w1 + w2 || s >= w3 + w2)
hits = 2;
else
hits = 3;
A general solution to handle an arbitrarily sized pile of bricks is out of scope for the problem, so does not need to be considered.
When s == 1, the instruction w = w/s; won’t modify w. You program will loop forever because the condition to terminate the loop is when w == 0.
This explains the time exceeded that you reported.
Note that w=w/s; won’t give you the right answer anyway. Have you understood the question ? Read again.
A side remark is that you should check that the entered values respect the constrains, and reject the input if not.

Solve an equation containing three unknown prime numbers [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I was recently asked a question in an interview & have been unable to crack it, after my own efforts have failed & Google not showing any results , I am posting it here so that anyone else may also try their hand on it .
Given the equation:
a (a + b) = c - 120
where a,b & c are unequal prime numbers, find a, b & c.
I know I must use some property of the prime numbers to reduce the problem to a simpler one, but I can't think of one. Any suggestions/solutions will be appreciated.
The best I could come up with is that :
There may be multiple solutions to it. My first approach was a brute force search for 3 prime numbers that solved this equations. (I know , totally useless)
The second approach was a refinement of the first, to modify the equation to a (a + b) - 120 = c. So now we reduce our brute force variables to just a & b & check if the LHS is prime no for the selected a & b. (If c were to be large, finding out whether the LHS is a prime would take away the advantage gained by reducing the variables from 3 to 2.)
So you see, I am not really going anywhere.
all primes are odd, except 2 - (1)
all primes are positive - (2)
odd - even = odd (3)
(1), (2) => c > 120 and c is odd - (4)
odd * odd = odd - (5)
(3), (4), (5) => c-120 is odd => a(a+b) is odd - (6)
even + odd = odd - (7)
(6) => a is odd, a+b is odd (8)
(7), (8) => b is even => b = 2
So, we have a^2 + 2a = c-120
I couldn't go any further
Let's stipulate that c > 120. That implies c != 2. So the RHS is odd.
Therefore the LHS has to be odd, so a (a + b) has to be odd. So a is odd, and a+b is odd. This only works out if b is even, and b is prime, so b = 2.
So we have a(a+2) = c - 120.
So a^2 + 2a + (120-c) = 0
Using the quadratic formula, solving for a, we get
[-2 +- sqrt(2^2 - 4 * 1 * (120 - c))] / 2
= -1 +- sqrt(1 - (120-c))
= -1 + sqrt(c - 119)
So we need a prime number c, so that c - 119 is a perfect square.
This is a quick calculation with a table of primes.
The smallest one I can find is c = 263, so a = 11, b = 2
It looks like c=443, a=17, b=2 also works.
There don't appear to be any other c values below 1000.
Possibly there are many, many others.