I'm having some trouble getting started with a lab of mine. The lab has the following instructions:
Given a value int input = 0b10010110 determine what sports an individual likes. Assume there will be no errors in this input. From left to right, each position represents the following: Football, Baseball, Volleyball, Swimming, Softball, Soccer, Hockey, Lacrosse.
If there is a 1 is in that position, then the person likes that sport. Based on the “binary” input given, output to the screen all of the sports that the user enjoys. For the given binary number, the user likes, football, swimming, soccer and hockey.
Do not make an array of characters.
Be sure to use an enumerated data type.
I'm not sure how I can compare each position of the string to tell whether it is a 1 or 0. One idea I have is to use an enumerated type where I set each sport to a ten digit number where only its appropriate position is 1
enum sport{
Football = 0010000000,
Baseball = 0001000000,
Volleyball = 0000100000,
... ,
Lacrosse = 0000000001
};
I would then shift left/ right on the given value "input" the appropriate amount of times to leave only the specified position with its original value and to set all other values to 0. For Football:
input << 2; input >> 9; input << 7;
So the new set value would be 0010000000. Then I'd be able to compare the number as a whole. I would have to that for each case, but I cannot think of a different way to do it.
Am I completely off? Is there a more functional way to check the value of each position using bit operations? Thanks for any assistance in advance.
Use bitwise AND operator &:
if (input & Football) {
// Football bit is set
} else {
// Football bit is not set
}
Also note that the 0b prefix is a compiler extension but is not standard C. And in your enum values, a number starting with the 0 prefix is in octal format (you have to fix this). I suggest you to use hexadecimal format for bit manipulation.
You could make things a bit more readable if you define you sport values by shifting a 1 to the left by the appropriate number of places; in fact, you could use a simple enumeration for the sport values, and use that to specify how many places to shift the bit.
Related
This is my Regular Expression ^[A-Z]{2}[0-9]{6}[A-Z]{1}?$
I am using this expression in angularjs ng-pattern-restrict . I can't type anything in the input field.
If i am use ^[A-Z]{0,2}[0-9]{0,6}[A-Z]{0,1}?$ : this expression then i can type three letters but can't type number.
If i will type two letters then only i can type six numbers.If i type three letters then i can't type numbers
I need The result like this: PP123456P Expression.
Can Anyone Help me
^[A-Z]{0,2}[0-9]{1,6}[A-Z]{1}?$
Should work, the reason you could type 3 letters is that the second group was allowed to be size 0-6 and then when you put in 3 letters it has matched the first 2 letter group, the numeric group with a 0 length match and finally the last Alpha. by changing it to 1-6 you force the entry to be between 1 and 6 numbers.
You seem to have a bit of redundancy in your regular expression and not quite sure what you were trying to do with [A-Z]{1}?, is this supposed to be an optional letter?
Although simplistic compared with the actual validation rules of National Insurance numbers you could use
^[A-Z]{2}[0-9]{6}[A-Z]$
Breaking that down...
^ Must match at the start of the string
[A-Z]{2} Exactly 2 letters in the range A-Z
[0-9][6] Exactly 6 digits in the range 0-9
[A-Z] Exactly 1 letter in the range A-Z
$ There must be nothing else following the previous matches
So I am doing a program on Hackerrank.
The problem is
You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings. Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number.
For example, assume your bird sightings are of types . There are two each of types and , and one sighting of type . Pick the lower of the two types seen twice: type .
Function Description
Complete the migratoryBirds function in the editor below. It should return the lowest type number of the most frequently sighted bird.
migratoryBirds has the following parameter(s):
arr: an array of integers representing types of birds sighted
Input Format
The first line contains an integer denoting , the number of birds sighted and reported in the array .
The second line describes as space-separated integers representing the type numbers of each bird sighted.
Constraints
It is guaranteed that each type is , , , , or .
Output Format
Print the type number of the most common bird; if two or more types of birds are equally common, choose the type with the smallest ID number.
This is my code. It is passing all but one of the test cases. Can you help?
x = []
for i in range (0,len(arr)):
x.append(arr.count(arr[i]))
for i in range(0,len(x)):
if x[i] == max(x):
out = i
return out
I don't see that your code passes any test cases, even with the indentation fixed. Your input size can be as large as 105, so that pretty much eliminates any O(n2) solutions that require traversing the entire list, which is unnecessary. The culprit here is arr.count(), which traverses the entire list for every element. You probably meant to traverse the list for every bird type, which results in 5 traversals of the input list:
x = []
for i in range(1, 6):
x.append(arr.count(i))
out = 0
best = x[0]
for i in range(len(x)):
if x[i] > best:
best = x[i]
out = i
return out + 1
The important restriction to note in this problem is that there are only 5 bird types (numbered 1-5), so we can initialize a counts array of length 6 with a dummy element at position 0 so indices map to counts neatly. Then, we can iterate through our input bird type list in one pass, updating our counter array. Lastly, take the max index of the counter array. The "smallest id for ties" restriction is automatically handled by the way max() works--it'll take the smallest index automatically. Here's the code:
counts = [-1, 0, 0, 0, 0, 0]
for bird in arr:
counts[bird] += 1
return counts.index(max(counts))
Note that the variable names are descriptive. This helps ensure that the purpose of each variable is clear and reduces bugs and erroneous assumptions about the program state.
In this post, #boisvert mentioned that if using string as the order field's value, it is best shown for a binary string, and then gave an algorithm to calculate the average of two binary strings as follows:
Avalue = 1+0*(1/2)+1*(1/4)+1*(1/8)
Bvalue = 1+1*(1/2)+0*(1/4)+0*(1/8)
average, new value = 1+0*(1/2)+1*(1/4)+1*(1/8)+1*(1/16) new string = "10111"
content order
--------------------
A '1011'
new! '10111'
B '1100'
C '1101'
I couldn't understand these very well, what's the value of the first item putting into the DB and the items inserting before/after it? How to calculate the average between '1011' and the new value '10111', or between '111' and '1000'?
Any help is much appreciated.
The binary strings are fractions, not integers; the decimal point is always at the beginning (or after the first digit, in #boisvert's answer; it doesn't make any difference as long as the position of the decimal point is fixed. Of course, it's actually a binary point since these are binary numbers.)
To find the average:
If the strings differ in length, put enough 0s at the end of the shorter string so that it is the same length as the longer string.
Add the two strings together, using binary addition, always putting the last carry at the beginning, even if it is ´0'. [See algorithm below].
Remove any 0s at the end.
Example 1: 1011 and 10111
Extend the first string with a 0: 10110 and 10111
Find the sum:
A: 10110
B: 10111
Carry: 101100
Sum: 101101
No trailing zeros, so the result is 101101
Example 2: 111 and 1000
1. 1110 1000
2. 10110
3. 1011
Starting off and insertion at the end:
The first item put into the database has the label 1. If at any point you need to add an item at the very beginning, use the first label with a 0 before it. Similarly, if you need to add an item at the end, use the first label with a 1 before it.
Binary addition:
Since the strings are the same length, this is easy; set Carry to 0, and scan both strings from back to front. (The output is also produced back-to-front.)
At each position:
* If the sum of Carry and the two digits is 1 or 3, output a 1, otherwise output a 0.
* If the sum of Carry and the two digits is 2 or 3, set Carry to 1, otherwise set it to 0.
When you've finished all the digits, output the value of Carry.
Practical implementation:
In practice, you wouldn't use binary strings; you'd use some fairly large base, the only requirement being that it is even. But the algorithms are the same. When constructing the representation of your numbers, you need to assign digits to characters in alphabetical order, so that the resulting strings can be sorted alphabetically without converting them to numbers; the database doesn't know how to convert to numbers, but it knows how to sort strings alphabetically.
I am using performance monitor to collect the counters data and save it to the DB. Here is the DB structure defined in the msdn http://msdn.microsoft.com/en-us/library/windows/desktop/aa371915(v=VS.85).aspx
Based on DB structure, here is the definition of the FirstValueA:
Combine this 32-bit value with the value of FirstValueB to create the
FirstValue member of PDH_RAW_COUNTER. FirstValueA contains the low
order bits.
And the FirstValueB:
Combine this 32-bit value with the value of FirstValueA to create the
FirstValue member of PDH_RAW_COUNTER. FirstValueB contains the high
order bits.
The fields FirstValueA and FirstValueB should be combined to create the FirstValue, and similarly the SecondValue.
How do you combine FirstValueA and FirstValueB to get the FirstValue in SQL Server?
So what they're saying is that you need to comingle the two, like this:
//for reference, this is 32 bits
12345678901234567890123456789012
000000000000000000000FirstValueA
000000000000000000000FirstValueB
What it says is we need to combine the two. It says that A is the low order, and B is the high order.
Let's refer to Wikipedia for http://en.wikipedia.org/wiki/Least_significant_bit and see that the low order is on the --> right, and the high order is on the <-- left.
low order -> right
high order <- left
A -> right
B <- left
So we're going to end up with (our previous example)
//for reference, this is 32 bits
12345678901234567890123456789012
000000000000000000000FirstValueA
000000000000000000000FirstValueB
becomes
//for reference, this is 32 bits
12345678901234567890123456789012
000000000000000000000FirstValueB000000000000000000000FirstValueA
Now, that doesn't work if the values look like this:
//for reference, this is 32 bits
12345678901234567890123456789012
1001101100110100101011010001010100101000010110000101010011101010
//the above string of 1's and 0's is more correct for the example
What you're given is not two binary strings, but two integers. So you have to multiply the left value by 2**32 and add it to the right value. (that's a 64 bit field by the way)
let's examine tho, why the low order bit is on the right and the high order is on the left:
Binary is written just like Arabic numerals. In Arabic numerals, the number:
123456
means one hundred twenty three thousand, four hundred fifty six. The one hundred thousand is the most significant part (given as we would shorten this to "just over one hundred thousand dollars" instead of "a lot over 6 dollars") and the six is the part we most freely drop. So we could say that the number were:
123 is the value that contains the high order bits, and 456 is the value that contains the low order bits. Here we would multiply by 10^3 to add them together (this is a mathematical fact, not a guess, so trust me on this) because it would look like this:
123
456
and so the same works for the binary:
//for reference, this is 32 bits
12345678901234567890123456789012
000000000000000000000FirstValueB
000000000000000000000FirstValueA
tl;dr:
Multiply B by 2^32 and add to A
Console.WriteLine("{0} {1} {2} : {3} {4}", p.CategoryName, p.InstanceName, p.CounterName, p.RawValue, p.CounterType.GetHashCode());
float FirstValue = p.NextValue();
Console.WriteLine("FirstValueA :{0}", (ulong)FirstValue & 4294967295);
Console.WriteLine("FirstValueB :{0}", (ulong)FirstValue >> 32);
Console.WriteLine("SecondValueA :{0}", p.NextSample().TimeStamp & 4294967295);
Console.WriteLine("SecondValueB :{0}", p.NextSample().TimeStamp >> 32);
I have made some c code for a program, which does some psycho-acoustics on sound data.
There is a piece of code which runs very slowly.
I think it would be best to use a look up table. How would one go about implementing it?
Any pointers or help would be appreciated! :)
Your values are not equidistant so it is not that easy. But its still possible: take your greatest common divisor of all your condition-values (thats here 50) and then make your table
byteout = lut[difference/50 + 12];
And in the lookup table you can just use your values in the posted order, where you duplicate the entries in case your stepping is 100.
Btw it just see, there is a mistake, all your negative cases are catched by your first <=0 (my example assumes that you want to omit the first case).
Firstly, take a look at where you want that first check against 0, as it makes all of your negative checks pointless.
Secondly, I would probably construct a lookup table as an array of 1300 elements, offset by 500 (your lowest negative value). Each element would be the result you want when you look up that number. If you are looking for something less than -500, don't check the array.
So it would look something like this:
table[0] = 0b0110; // -500 through -599
table[1] = 0b0110;
...
table[100] = 0b0101; // -400 through -499
table[101] = 0b0101;
...
Lookup would be:
if (value <= -600) {
return 0b0111;
}
else {
return table[value + 600];
}
It's a small enough number of values that the size of the array is not prohibitive. Initialize with a loop at the beginning of your program.
Binary search for the win.
Store all possible values in an array, and be sure to sort them.
Start in the middle and see if difference is less than that value. If so, move to the middle of what's left of your cursor and try again. If not, move to the right. Keep going until you find the value you want, and then use that.
Your array could be of structs that have the minimum value and the corresponding byteout value.
EDIT: To clear up possible misunderstandings, with "every possible value" I don't mean every number between -1400 and 1400, just values you check against in your original code.
Let's look at the first bit:
if (difference <= 0)
byteout = 0b0000;
else if (difference <= -600)
byteout = 0b0111;
Let's say you have a value of -601.
Is it <= 0? Yes, so byteout = 0b0000;
you never get to the -600. So effectively, ALL negative values are 0b0000. This may or may not be by design, but if it is you can get rid of all other negative values.
Otherwise, I would consider reducing this to a formula (with as few branches as possible) or going with #Ebomike's solution of a precomputed lookup table and binary search.