Bit manipulation clarification in C - c

i'm learning bit manipulation and i am considering a problem and would like some clarification
If given something like 0000111111111111;
and i want 2 functions:
Assuming i am reading the indexes from right to left and indexes start at 1, i.e index 1-12 =1, index 13,14,15,16 = 0
If i want to make it so that i remove one zero starting from the left
am i correct in thinking that a right shift by 1 would achieve what i want?
If i want to add one zero to the left so it becomes 0001111111111111
how do i go about achieving this?

If i want to make it so that i remove one zero starting from the left
am i correct in thinking that a right shift by 1 would achieve what i
want?
Answer: No. If you right-shift, you are changing the number by shifting all bits by one to the right and the least significant bit (the one on the far right) falls off the end:
0000011111111111;
If i want to add one zero to the left so it becomes 0001111111111111
how do i go about achieving this?
Answer: you left-shift and add 1:
0000111111111111; original
0001111111111110; left-shift
0001111111111111; +1

Related

Single storage value that can be interpreted to mean different things

I want to see if there is a way to store a single value in one column in a database, but when read it could be interpreted as four columns in a database.
I have square, which has four sides. I would like to store a value that tells me what sides should have a dashed line. When this value is read I can easily decipher like the left and right side should be dashed, or just the top side, or all sides, or none.
I know I could have say 17 options I could store, but is there an easier way with a number? I will have four buttons in the interface showing which sides they want dotted and will store a value that way.
Is there a way to show me this in some pseudo-code in the storing and reinterpreting parts?
There are 16 possibilities for the sides--each side has two possibilities, and each decision is independent from the others, so you multiply the numbers together, getting 2*2*2*2=16.
You could just store an integer between 0 and 15. To get the choice for the left side, calculate n & 1 where n is the stored number. (The "&" symbol means "bitwise and" in many computer languages.) The result 1 means dashed, while 0 means solid. To get the right side, calculate n & 2, the top is n & 4, while the bottom is n & 8. Note that the "magic numbers" in those formulas are 2**0, 2**1, 2**2, and 2**3.
You can easily go the other way. If your choices expressed as 0 or 1 are a,b,c,d, then n = 1*a + 2*b + 4*c + 8*d. Note the same magic numbers as in the previous paragraph.
If you know the binary number system, those formulas are obvious. If you want to learn more, do a web search on "binary number".
Of course, another way to solve your problem is to store a string value rather than an integer. For example, you could store
"left=dashed, right=solid, top=solid, bottom=dashed"
and use the string-handling facilities of your language to parse the string. This is a more lengthy process than my first method, and uses more memory for the storage, but it has the advantage of being more transparent and easy to understand for anyone examining the data.
Your idea in a comment of using a short string like "1101" is a good one, and depending on the implementation it may even use less memory than my first solution. It shows the same amount of information as my first solution and less than my second. The implementation of your idea and the others depends on the language and on how you store the decision for each side in a variable. In Python, if n is the stored (string) value and the decisions for each side are Boolean variables a,b,c,d (True means dashed, False means solid), your code could be
a = (n[0] == '1')
b = (n[1] == '1')
c = (n[2] == '1')
d = (n[3] == '1')
There are shorter ways to do this in Python but they are less understandable to non-Python programmers.

Loop through array Breadth search fashioned

the title of the question might be a little bit missleading but I am not sure how to describe my problem.
I want to restructure the keys of an array such that the loop will jump with the following pattern:
Example 1:
keys from 1,2,3,4,5,6,7,8,9 will lead to 1,9,5,3,7,2,6,4,8
take the first element - 1
take the last element - 9
take the middle (1+9)/2 = 5
go to the first half and take the middle of 1 and 5 - 3
jump to the second half and take the middle of 5 and 9 - 7
jump back to the first half of the first half and take 2
jump back to the first half of the second half and take 6
jump back to the second half of the first half and take 4
jump back to the second half of the second half and take 8
Of course, this is an idealized example where everything is nicely dividable. If this is not the case you have to floor and ceil to get the new elements to divide.
Example 2:
key from 1,2,3,4,5,6,7,8,9,10 will lead to 1,10,5,6,3,8,2,7,4,9
With my small knowledge about algorithm and datastructures I tried to use recursion/divide and conquer but I did not manage to realize the jumps between the halfs.
So I think I have to add parameters like the length of the divided halfs an the positions but here I am lost for implementation.
The interesting question for me is: Is my thinking to complicated and is there a much easier solution? Or is this problem really this complex?
I am happy for any advise on literature ore code snippets to try it.
Thanks and best regards
Stephan
I'm not sure if you can implement this algorithm by a recursive or divide-and-conquer. But you can do this elegantly using a breadth-first search. Below is python pseudocode, where you have a queue whose elements are intervals.
#initialize queue Q with the whole interval
n = len(your_list)
# breadth first search
Q.push([0, n-1])
while Q not empty:
itv = q.pop_front()
process(itv) # print the middle element of interval itv, etc.
itv_1, itv_2 = divide_interval_into_halves(itv)
if len(itv_1) > 0:
Q.push(itv_1)
if len(itv_1) > 0:
Q.push(itv_2)
Hope it helps :)

Bitwise and of subsets of an array

Can anyone give a hint how to approach this problem?
Given an array A. Is there any subset of array A in which if we do AND of all elements of that subset then output should be in power of two.
I've thought of generating a power-set and solving but it will have a very bad complexity (2^n).
Thanks in Advance.
You can look at it from a different perspective: pick a power of two. Can we generate it?
This question is easy to answer. Take all items from the set in which the bit corresponding to the power of two is set. Calculate the AND of all of those. The result must by construction have the bit that we looked for set, but it may or may not have any other bits set. If it has other bits as well, then choosing some other (smaller - you can't choose any extra items because they don't have the target bit set) subset wouldn't work either, it could only have more wrong bits set because it would have fewer possibilities to unset bits.
Just do that for all possible powers of two, that's only as many as there are bits in the largest integer in the set.

Implementing A* algorithm

So I am implementing A* algorithm in C. Here's the procedure.
I am using Priority Queue [using array] for all the open nodes. Since I'll have duplicate distances, that is more than one node with same distance/Priority, hence while inserting a node in PQ, if the parent of the inserted node has the same priority, I still swap them both, so that my newest entered member remains on the top( or as high as possible),so that I keep following a particular direction. Also, on removing, when I swap the topmost element with the last one, then again, if the swapped last element has the same as one of its children, then it gets swapped to the bottom.(I am not sure if this will affect in any way).
Now the problem is say I have a 100*100 matrix, and I have obstacles from (0,20) to (15,20) of the 2D array , in which I am moving. Now for a starting position (2,2) and ending position (16,20) I get a straight path, i.e. firstly go all the way to right, then go down till 15 then move one right and I am done.
But, if I have starting as (2,2) and last as (12,78) i.e. the points are separated by the obstacles and the path has to go around it, I still go via (16,20) and my path after (16,20) is still straight, but my path upto (16,20) is zig zag, i.e. I go some distance straight down, then some right, then down then right and so on, ultimately reaching (16,20) and going straight after that.
Why this zig zag path for the first half of the distance, what can I do to make sure that my path is straight, as it is, when my destination is (16,20) and not (12,78).
Thanks.
void findPath(array[ROW][COLUMN],sourceX,sourceY,destX,destY) {
PQ pq[SIZE];
int x,y;
insert(pq,sourceX,sourceY);
while(!empty(pq)) {
remove(pq);
if(removedIsDestination)
break; //Path Found
insertAdjacent(pq,x,y,destX,destY);
}
}
void insert(PQ pq[SIZE],element){
++sizeOfPQ;
PQ[sizeOfPQ]==element
int i=sizeOfPQ;
while(i>0){
if(pq[i].priority <= pq[(i-1)/2].priority){
swapWithParent
i=(i-1)/2;
}
else
break;
}
}
You should change your scoring part. Right now you calculate absolute distance. Instead calculate min move distance. If you count each move as one then if you were at (x,y) and going to (dX,dY) that would be
distance moved + (max(x,dX) - min(x,dx) + max(y,dY) - min(y,dY))
A lower value is considered a higher score.
This heuristic is a guess at how many moves it would take if there was nothing in the way.
The nice thing about the heuristic is you can change it to get the results you want, for example if you prefer to move in a straight line as you suggest, then you can make this change:
= distance moved + (max(x,dX) - min(x,dx) + max(y,dY) - min(y,dY))
+ (1 if this is a turn from the last move)
This will cause you to "find" solutions which tend to go in the same direction.
If you want to FORCE as few turns as possible:
= distance moved + (max(x,dX) - min(x,dx) + max(y,dY) - min(y,dY))
+ (1 times the number of turns made)
This is what is nice about A* -- the heuristic will inform the search -- you will still always find a solution, but if there is more than one you can influence where you look first -- this makes it good for simulating AI behavior.
Doubt : How is the first one and second calculating way different from
each other?
The first one puts a lower priority on a move that is a turn. The second one puts a lower priority on a path with more turns. In some cases (eg, the first turn) the value will be the same, but over all the 2nd one will pick paths that have as few turns as possible, where the first one might not.
Also, 1 if this is a turn from the last move , for this,
say i have source at top left and destination at bottom right, now my
path normally would be, left,left,left...down,down,down.... Now, 1 if
this is a turn from the last move, according to this, when I change
from left to down, will I add 1?
Yes
Wont it make the total value more and the priority for down will decrease.
Yes, exactly. You want to not look at choices that have a turn in them first. This will make them lower priority and your algorithm will investigate other options with a higher priority -- exactly what you want.
Or 1 if this is a turn from the last move is when I move to a cell, that is not abutting the cell previously worked upon? Thnks –
No, I don't understand this question -- I don't think it makes sense in this context -- all moves have to abut the previous cell, diagonal moves are not allowed.
Though, I'd really appreciate if you could tell me one instance where the first and second methods will give different answers. If you could. Thanks alot. :) 
Not so easy without seeing the details of your algorithm but the following might work:
The red are blocks. The green is what I would expect the first one to do, it locally tries to find the least turn. The blue is the least turn solution. Note, how far the red areas are from each other and the details of how your algorithm influence if this will work. As I have it above -- having an extra turn only costs 1 in the heuristic. SO, if you want to be sure this will work change the heuristic like this:
= distance moved + (max(x,dX) - min(x,dx) + max(y,dY) - min(y,dY))
+ (25 times the number of turns made)
Where 25 is bigger than the distance to get past the 2nd turn in the green path. (Thus after the 2nd turn the blue path will be searched.)

generate random RGB color using rand() function

I need a function which will generate three numbers so I can use them as RGB pattern for my SVG.
While this is simple, I also need to make sure I'm not using the same color twice.
How exactly do I do that? Generate one number at a time with simple rand (seed time active) and then what? I don't want to exclude a number, but maybe the whole pattern?
I'm kind of lost here.
To be precise, by first calling of this function I will get for example 218 199 154 and by second I'll get 47 212 236 which definitely are two different colors. Any suggestions?
Also I think a struct with int r, int g, int b would be suitable for this?
Edit: Colors should be different to the human eye. Sorry for not mentioning this earlier.
You could use a set to store the generated colors.
First instanciate a new set.
Then, every time you generate a color, look if the value is present in your set.
If the record exists, skip it and retry for a new colour. If not, you can use it but dont forget to cache it in the Set after.
This may become not performant if you need to generate a big quantity of colour.
The cheapest way to do this would be to use a Bloom filter which is very small memory wise, but leads to occasional false positives (i.e., you will think you have used a colour, but you haven't). Basically, create three random numbers between 0-255, save them however you like, hash them as a triplet and place the hash in the filter.
Also, you might want to throw away the low bits of each channel since it's probably not easy to tell #FFFFF0 versus #FFFFF2.
Here is a simple way:
1.Generate a random integer.
2.Shift it 8 times to have 24 meaningful bits, store this integer value.
3.Use first 8 bits for R, second group of 8 bits for G,
and the remaining 8 bits for B value.
For every new random number, shift it 8 times, compare all the other integer values that you stored before, if none of them matches with the new one use it for the new color(step3).
The differentiation by human eye is an interesting topic, because perceptional thresholds vary from one to another person. To achieve it shift the integer 14 times, get the first 6 bits for R(pad two 0s to get 8 bits again), get the second 6 bits for G, and last 6 bits for B. If you think that 6 bits are not good for it, decrease it 5,4...
Simple Run with 4 significant bits for each channel:
My random integer is:
0101-1111-0000-1111-0000-1100-1101-0000
I shift(you can also use multiply or modulo) it to left 20 times:
0000-0000-0000-0000-0000-0101-1111-0000
store this value.
Then get first 4 bits for R second 4 bits for G and last 4 bits for B:
R: 0101
G: 1111
B: 0000
Pad them to make each of them 8 bits.
R: 0101-0000
G: 1111-0000
B: 0000-0000
Use those for your color components.
For each new random number after shifting it compare it with your stored integer values so far. If it is different, then store and use it for color.
One idea would be to use a bit vector to represent the set of colors generated. For 24-bit precision, the bit vector would be 224 bits long, which is 16,777,216 bits, or 2 MB. Certainly not a lot, these days, and it would be very fast to look up and insert colors.

Resources