Binary - Remove right-hand zeroes in a number - c#

I can't figure out how I can remove right-hand zeros in a given binary number like this:
00110000 -> 11
1000 -> 1
According to my example, I know I can perform a right-shift of 4 and 3 to remove the unwanted zeros but I don't know how could I calculate the number of bits needed for the right-shift.

This should work:
if (x != 0)
{
while (x % 2 == 0)
x = x >> 1;
}
It basically says keep bit shifting right whilst the number is even (doesn't have 1 as the right-most bit).
As mentioned in the comments by #Streamline, the loop alone won't work for a value of 0, so you have to check it's not 0 first.
No need to check every time round the loop for this though because if x != 0 then x >> n will never be 0 given the other looping condition that we stop when x % 2 != 0
If you need to know the number of bit-shifts, you can add a counter to the loop.
If you don't want to change the value of x, you can assign it to a temporary variable and use that instead.

Related

What's the proper way to generate 6 characters alphanumeric code in which sum of all characters equals 9? (Voucher code generator)

My first idea was to make an array/list that has values assigned to each character.
So for example:
array[0] =' 0'
array[10] = 'A'
[...]
Then code would pick a random number y between [0,x] for slot 1.
For next slot [0,(x-y)] etc. When y <= 0 then fill rest of the slots with '0'.
Would that be enough for a simple voucher code generator? (It's not my decision to make encryption with this rule)
I am worried that sum of 9 is quite low for 6 character code, letters won't be used at all since they all have value over 9.
To prevent situation like this:
540000, 630000, 180000
Should I make chance of '0' to appear more?
What do you guys think about it?
Maybe you could also suggest some other way of doing this.
#Edit
Examples:
112320 = 1+1+2+3+2+0 = 9 Valid code, sum equals 9
000900 = 0+0+0+9+0+0 = 9 Valid code, sum equals 9
003015 = 0+0+3+0+1+5 = 9 Valid code, sum equals 9
A0012B = 10+0+0+1+2+11 = 24 Invalid code
Let's say that the function Rand(n) creates a random integer number that can go from 0 up to n (n included), then you can do the following:
Sum = 0;
A[0] = Rand(9);
Sum += A[0];
A[1] = Rand(9 - Sum);
Sum += A[1];
A[2] = Rand(9 - Sum);
Sum += A[2];
...
I just wrote this down very quickly, I didn't check the boundaries, but such an algorithm should do the trick.

How to get odd or even numbers in C# with a user input?

I am very new to C# and have been set a task to make a program that asks for a user input of a number and then says if that number is odd or even. How can I do that?
You need to figure how to check if a number is odd or even. How can do, you ask?
You may not have learned this yet, but modulus is the simplest way to do it. It uses the character % and it basically acts as a division, but instead of telling what value each parts of the division equals, it tells you what is left from the division. Coming from that, you know that if the number divided by % 2 is 0, your number is even because there is nothing left. 4 / 2 = 2 vs 4 % 2 = 0
My example here is not the shortest or fastest, but is easier to understand for a beginner
Console.WriteLine("Enter your number : ");
string number = Console.ReadLine();
Int32.Parse(number);
if(number % 2 == 0)
{
Console.WriteLine("Your number is even.");
}
else
{
Console.WriteLine("Your number is odd.");
}
Have a look at the remainder (modulus) operator.
An example:
int userInput = // get your input
bool isEven = userInput % 2 == 0;
An even number will have a remainder of 0 when divided by 2.
In one line
Console.WriteLine(int.Parse(Console.ReadLine()) % 2 == 0 ? "even":"odd");

Getting the nearest value that returns true on a bool

If I wanted to get the nearest value to a number, but that value also has to return true on a bool called IsMultipleOf7 which returns true on numbers that are multiples of 7.
For example, I have a int x = 523. So the nearest multiple of 7 is 525, so my bool would return true 525.
How can I get that number?
This function will return the closest multiple of 7 or the number itself if it is a multiple of 7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
And here's a usage example:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
Live demo is also available here
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
int x = 523;
int result = ((x / 7) + 1) * 7;
You may need a more complex formula, if your number is dividable by 7 and should stay the same number. Or maybe you have simplified your problem too much?
There are two ways I can think of. The first is the brute force method I commented about. If you start with the number x, test it. If it works, hooray! If not, try adding one to x and test. Then subtract one from x and test. Then do this with two, and three, testing up and down at the same time. Once your test returns true, you have located (one of) the closest number(s) that work. This method is a general one and will work with any test function.
Because we know you are using IsMultipleOf7 as the test, a smarter method could be possible. Imagine the time it would take if your test was instead IsMultipleOf999999999! So many numbers might have to tested before hitting the closest. Instead, some math can be used. First, compute x modulo 7 (for IsMultipleOf7), written x % 7 in C(++). This value tells you how far x is from the largest multiple of 7 LESS than x. If this value is 0, x is a multiple of 7. If the value is 1, 2 or 3, x minus the value is the closest multiple. If the value is 4, 5 or 6, x plus the difference to make 7 (7 - value) is the closest multiple.
Some pseudo-code:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
x=7*Math.Round(((float)x)/7.0)
^Simplest solution right there ;)
No need for all of this looping and stuff.
divide by 7, if the decimals are less than 0.5 then the nearest denominator is floored, else ceiling. Round() does that for you, then just multiply your new int by 7 to create a number evenly divisible by 7 (since it was an int being multiplied by 7). It will get the closest value above or below. No need for bool at all. Make sure you cast float onto x so that it can be divided by 7 without causing flooring with integer logic.

Append a digit to an integer and make sure sum of each digits ends with 1

What is the algorithm in c# to do this?
Example 1:
Given n = 972, function will then append 3 to make 9723, because 9 + 7 + 2 + 3 = 21 (ends with 1). Function should return 3.
Example 2:
Given n = 33, function will then append 5 to make 335, because 3 + 3 + 5 = 11 (ends with 1). Function should return 5.
Algorithms are language independent. Asking for "an algorithm in C#" doesn't make much sense.
Asking for the algorithm (as though there is only one) is similarly misguided.
So, let's do this step by step.
First, we note that only the last digit of the result is meaningful. So, we'll sum up our existing digits, and then ignore all but the last one. A good way to do this is to take the sum modulo 10.
So, we have the sum of the existing digits, and we want to add another digit to that, so that the sum of the two ends in 1.
For the vast majority of cases, that will mean sum + newDigit = 11. Rearranging gives newDigit = 11 - sum
We can then take this modulo 10 (again) in order to reduce it to a single digit.
Finally, we multiply the original number by 10, and add our new digit to it.
The algorithm in general:
(10 - (sum of digits mod 10) + 1) mod 10
The answer of the above expression is your needed digit.
sum of digits mod 10 gives you the current remainder, when you subtract this from 10 you get the needed value for a remainder of 0. When you add 1 you get the needed value to get a remainder of 1. The last mod 10 gives you the answer as a 1 digit number.
So in C# something like this:
static int getNewValue(string s)
{
int sum = 0;
foreach (char c in s)
{
sum += Convert.ToInt32(c.ToString());
}
int newDigit = (10 - (sum % 10) + 1) % 10;
return newDigit;
}
Another alternative using mod once only
int sum = 0;
foreach (char c in s)
sum += Convert.ToInt32(c.ToString());
int diff = 0;
while (sum % 10 != 1)
{
sum++;
diff++;
}
if (diff > 0)
s += diff.ToString();
Well, it's easier in C++.
std::string s = boost::lexical_cast<string>( i );
i = i * 10 + 9 - std::accumulate( s.begin(), s.end(), 8 - '0' * s.size() ) % 10;
Addicted to code golf…

How to find the most common int in a 2d array of ints?

OK, so I'm just starting to think how to implement a new graphical plugin for Paint.NET and I will need to know how to find the most common integer in a 2d array of integers. Is there a built-in to C# way to do this? Or, does anyone have a slick way to do it?
The array will look something like this:
300 300 300 300 300 300 300
0 150 300 300 300 300 300
0 0 150 300 300 300 300
0 0 0 0 300 300 300
0 0 0 0 150 300 300
0 0 0 0 0 150 300
0 0 0 0 0 0 300
I would need to know that 300 is the most common number in the array. If there is no "most common" then just return the center number (the array dimintions will always be odd x odd) 0.
I'll be implementing this using a "brute force" algorithm unless you experts can come up with something faster.
Any help would be very much appreciated.
Thanks!
EDIT: More info...
The values will almost always be VERY diverse (more diverse than my example array). The values will be in the range of 0-360. The size of the array will be 5x5 to about 17x17 depending on speed of the algorithm. The result will be calculate once for each pixel in a large image... so faster is better. ;)
It's at least O(n*m) any way you slice it -- you are going to have to look at each cell at least once. The place to economize is in where you accumulate the counts of each value before looking for the most common; if your integers vary over a relatively small range (they are uint16, let's say), then you might be able to simply use a flat array instead of a map.
I guess you could also keep a running count x,y of the current top and second-closest candidate for "most common" and early-out as soon as you've less than (n*m)-(x-y) cells left to look at, since at that point there's no way the runner-up could outpace the top candidate.
Integer ops like this are pretty fast; even for a megapixel image the brute force algorithm should only take a couple milliseconds.
I notice you've edited your original question to say that the pixels value from 0..255 -- in that case, definitely go with a simple flat array; that's small enough to easily fit into the l1 dcache and a lookup in a flat array is trez quick.
[edit] : Dealing with the "no most common number" case is very simple once you've built the histogram array: all have you to do is walk through it to find the "most" and "second most" common numbers; if they're equally frequent, then by definition there is no one most common.
const int numLevels = 360; // you said each cell contains a number [0..360)
int levelFrequencyCounts[numLevels]; // assume this has been populated such that levelFrequencyCounts[i] = number of cells containing "i"
int mostCommon = 0, runnerUp = 0;
for (int i = 1 ; i < numLevels ; ++i)
{
if ( levelFrequencyCounts[i] > levelFrequencyCounts[mostCommon] )
{
runnnerUp = mostCommon;
mostCommon = i;
}
}
if ( levelFrequencyCounts[mostCommon] != levelFrequencyCounts[runnerUp] )
{
return mostCommon;
}
else
{
return CenterOfInputData; // (something like InputData[n/2][m/2])
}
how would I do something like this in C#?
Something like this:
Dictionary<int, int> d = new Dictionary<int, int>();
foreach (int value in matrix)
{
if (!d.ContainsKey(value))
d.Add(value, 1);
else
d[value] = d[value] + 1;
}
KeyValuePair<int, int> biggest = null;
foreach (KeyValuePair<int, int> found in d)
{
if ((biggest == null) || (biggest.Value < found.Value))
biggest = found;
}
Take a look at the LocalHistogramEffect code in Paint.NET, notably LocalHistorgramEffect.RenderRect.
I walks the input image, maintaining a histogram of intensities for each source pixel withing 'r' pixels of the destination pixel. As the output pixels are traversed, it adds the leading edge to the histogram and subtracts the trailing edge. It handles all the edge cases well, and is quite fast. It's the basis for the Median, Unfocus, Outline, and Remove Noise effects.
Adapting this to support Hue instead of RGB intensity would be rather trivial.
The performance is quite good, and for your purposes it operates in O(r^2+wr+nw), where r is the radius, w is the width of the image, and n is the number of levels in the histogram.
-tjackson
One option is LINQ - a bit inefficient, but OK for non-huge arrays:
var max = (from cell in data.Cast<int>()
group cell by cell into grp
select new { Key = grp.Key, Count = grp.Count() } into agg
orderby agg.Count descending
select agg).First();
Console.WriteLine(max.Key + ": " + max.Count);
Or with a jagged array:
var max = (from row in data
from cell in row
group cell by cell into grp
select new {Key = grp.Key, Count = grp.Count()} into agg
orderby agg.Count descending
select agg).First();
Console.WriteLine(max.Key + ": " + max.Count);
In reality, I would probably use a dictionary/count. This example without LINQ, just "because":
Dictionary<int, int> counts = new Dictionary<int, int>();
foreach (int value in data)
{
int count;
counts.TryGetValue(value, out count);
counts[value] = count + 1;
}
int maxCount = -1, maxValue = 0;
foreach (KeyValuePair<int, int> pair in counts)
{
if (pair.Value > maxCount)
{
maxCount = pair.Value;
maxValue = pair.Key;
}
}
Console.WriteLine(maxCount + ": " + maxValue);
Your image:
300+ 300+ 300+ 300 300 300 300
0+ 150+ 300+ 300 300 300 300
0+ 0+ 150+ 300 300 300 300
0 0 0 0 300 300 300
0 0 0 0 150 300 300
0 0 0 0 0 150 300
0 0 0 0 0 0 300
Marked (+) numbers are your window. w,h is your window dimensions. Apply bucket sorting (as other people suggested since your value ranges are quite limited). Don't cut your evaluation halfway as Crashworks suggests. Don't throw your result yet. This is the first step.
300- 300- 300- 300 300 300 300
0. 150. 300. 300 300 300 300
0. 0. 150. 300 300 300 300
0+ 0+ 0+ 0 300 300 300
0 0 0 0 150 300 300
0 0 0 0 0 150 300
0 0 0 0 0 0 300
Shift your window. Instead of adding, subtract the buckets in the last row/column you passed and add the new buckets. This way you examine each pixel 2(w+h) times i.e. when it crosses the window boundary, instead of w*h times, i.e. while that pixel is in the window, in a naive implementation.
In other words, You need to move your window like this:
| ^->| ^
| | | |
| | | |
V->| V->|
I assume you are trying to implement a nonlinear convolution filter.
Corrections welcome.
If speed is your primary concern, do not use a dictionary. Stick with an array of bytes. Try this:
// stores hit counts (0-360)
short[] hitCounts = new short[361];
// iterate through 2d array and increment hit counts
for (int i = 0; i < toEvaluate.Length; i++)
{
for (int j = 0; j < toEvaluate[i].Length; j++)
hitCounts[toEvaluate[i][j]]++;
}
int greatestHitCount = 0; // the hit count of the current greatest value
int greatest = -1; // the current greatest valeu
// iterate through values (0-360) and evalute hit counts
for (int i = 0; i < hitCounts.Length; i++)
{
// the hit count of hitCounts[i] is higher than the current greatest hit count value
if (hitCounts[i] > greatestHitCount)
{
greatestHitCount = vals[i]; // store the new hit count
greatest = i; // store the greatest value
}
// there is already a value with the same hit count (which is the greatest)
else if (hitCounts[i] == greatestHitCount)
greatest = -1; // there are more than one value, we can't use this if it ends up being the greatest
}
if (greatest >= 0) // no greatest value found
return greatest;
// figure out the middle x and y value
int x = (toEvaluate.Length - 1) / 2 + 1;
int y = (toEvaluate[x].Length - 1) / 2 + 1;
// return the value at the center of the 2d array as the value
return toEvaluate[x][y];
When speed becomes a concern over readability, you end up with necessarily ugly code. The above could definitely benefit from refactoring (hence overdoing the comments), but it should run fast. If it isn't fast enough, you can gain even more optimizations by moving it to unmanaged code.
Michael beat me to the post, but I'd do likewise, something like this:
int MaxValueIn2dArray(int[,] matrix)
{
var d = new int[360];
int MaxValue = 0;
for (int x = 0; x <= matrix.GetUpperBound(0); x++)
{
for (int y = 0; y <= matrix.GetUpperBound(1); y++)
{
d[matrix[x, y]]++;
}
}
foreach (int value in d)
{
if (value > MaxValue) MaxValue = value;
}
return MaxValue;
}
It would need to be optimized for your particular needs.
All I'll offer is for any algorithm that checks every cell (which is pretty much what you'd expect to do) do two extra things:
1.) Make sure the routine exits when the count for the currently most common value > (M x N / 2). If something has >50% coverage on your grid then it's the most common value, no need to continue. If your routine only needs to be right MOST of the time then you could lower the percentage and treat it as a heuristic. You could even run some analysis that spits out something like if coverage is >37.6% then 99.9% of the time it'll be the most common value and then use that percentage.
2.) If there is any way you can determine in which side, corner or general location (outer edges, middle, etc.) the most common values are likely to be, you could then scan in that order which together with optimization 1 above could shave off a lot of your scanning. For instance in your example the top right is heavy on the common value. If this was determinable by some heuristic you could scan from the top right to the bottom left in some fashion. If the pattern of scanning needed is complex, pre-generate it.

Categories