Invert bitwise shift operator / power of two - c#

I have the following simple equation in my C# program to convert a number to a resulting value:
sectorSize = 1 << sectorShift;
Is there some sort of inverse operation that will allow me to go the other way as well?
sectorShift = ???
I know that you can implement a loop, but that's a little bit of an overkill. I've never had to do this before, so I have no idea and I can't find anything online about it. The equation I need only needs to produce valid results when sectorSize is a power of two; the rest of the domain can go to hell for all I care.

Here are five ways to do that in C. Translating them to correct C# is left as an exercise. Be extremely careful.
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
Frankly, I would personally always go with the loop. It is not clear to me why you believe that simple and obviously correct code is "overkill".

Logarithms. But since you don't want to do that, use a loop and/or lookup table.

Related

Optimizing output parameters

I'm trying to solve a problem statement using C# as programming language.
In the problem system for an input (double/decimal) say Hi, the output generated is a form of dataset containing number of parameters (Fi, Pi and Ti). I somehow have to filter out only those entries in the data set which would satisfy the following conditions.
Fi > Fmin, where Fmin is some constant
Pi > Pmin, where Pmin is some constant
Ti < Tmax, where Tmax is some constant
Is there an efficient algorithm I could use in such cases where I could zero in on an optimal set of values for Hi for which the output parameter values are well within the constraints. Also I thought using Genetic Algorithms in this case makes sense but somehow I'm not able to formulate and fit the problem specific to Genetic Algorithms.
Any pointers/ suggestions are truly appreciated.
you can use Linq query
var result = DataSet.Where(x=>x.Fi> Fmin && x.Pi>Pmin && Ti < Tmax);
Well, it's hard for me to guess. I don't know the properties of the function for Fi etc.
An log-Barrier Method could be something interesting here. Or the SQP Method. But it has to be differntiable.
Otherwise simulated annealing could be interesting.
But these are just some guesses. It really depends on the problem.
I doubt that a Genetic Algorithm makes sense, seeing as you have only one input variable (Hi) that determines the outputs (Fi, Pi, Ti). The power of a Genetic Algorithm is that it blends good solutions into new solutions. If your solution is only one number, blending two good solutions will probably mean that you're finding some Hi inbetween (such as the average -> 0.5Hi1 + 0.5Hi2 or some other linear combination aHi1 + (1-a)Hi2 with a between 0 and 1).
I would recommend looking into Multi-start Local Search heuristics, such as link. This is a pretty solid heuristic that allows you to explore the solution space for Hi.
In their simplest form, such heuristics calculate the performance for N random values of Hi, and then search for further improvements in the area of the best performing Hi values out of those N initial values.
This sort of stuff is also pretty straight-forward to code, assuming that you have a way to obtain the Fi, Ti, and Pi values from your Hi input, and that you have some way to figure out which of your solutions perform 'best' (for instance through a fitness function as mentioned in the comments).

Retrieving the highest number in an array recursively in C#?

How can I retrieve the highest number in an array recursively in C#?
Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.
Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.
Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:
What you're looking for
What you've found so far
The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.
The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.
So what do you need to know in order to find the highest value in an array recursively?
The contents of the Array.
The highest number you've found so far.
Have you already looked at this part of the Array? (Why look through it again?)
That would produce a method signature that looks like:
public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);
Once you're inside the array, you've got to do the following:
Iterate through the array
Stop when you find a value that is higher than the highestNumberFound
Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
When there are no more 'higher' numbers, then return the highest number found.
I realize it sounds trite, but learning this stuff on your own will make you a better programmer.
If you want to be a professional programmer, you have got to learn this stuff on your own.
If you don't want to be a professional programmer, then drop the course and do something you love.
Here's just a hint (taking int[] as an example):
public int FindMax(int[] array, int indexSoFar, int maxSoFar)
Think about:
The start conditions
The termination conditions
How you move through the array recursively
Reason of EDIT: Didnt want to spoil the answere.
Greetings.

Generating and then using a taylor polynomial in C#

I've written a simple graphing implementation in C#, and I can graph things by comparing each pixel to the position on the graph it represents and plugging that position into the function I have to see if it is on the curve. That's all well and good.
The problem I'm having is USING a generated taylor polynomial. For example, I am able to create the nth taylor polynomial of a transcendent function f centered at c by doing
summation of this from 0 to to n with the counter variable being k = ((kth derivative of f(c)) * (x-c)^k)/k!
I am not sure how to do math markup on stackoverflow nor am I too competent with doing that on the web, but I hope that is understandable. The left side could be written as sigma _k=0 ^n or something like that with _ representing the section under sigma and the ^ representing the part above...
So I end up generating a Taylor polynomial of the 6th degree for cos(x) centered at 0(maclaurin, I know) that looks something like
"1 - x^2/2! + x^4/4! - x^6/6!"
This can be done through simple string manipulation in C#. I can just loop through and add the next term to the string.
I really can't comprehend how I would actually be able to use the string as a function to compare to graph positions to see if that graph position is actually on this graph to therefore graph it. So essentially: How would I use a string as an actual mathematical function in C#, or is there a better way of doing this.
Really sorry if it's confusing...really trying my best to explain it in a way that people can help.
You need a parser of string -> function. See MathParser for an example, that probably does everything you mentioned you need.
From a general perspective, anytime you want to convert a string into something that does work, you have to implement a parser, which will interpret the string and perform the actions dictated by it. For mathematical formulas, an expression tree may be of use to maintain order of operations and grouping. There are probably some math expression libraries available that will do this, or you can roll your own. This is not a trivial task, but it's certainly possible.
Once you have the expression tree, to figure out if a value f(x) for a given x is graphable, just evaluate it. For an f(x) graph, you can test x first to see if it falls in the visible domain of the graphing area. If it does, evaluate f(x) and if the point (x,f(x)) is graphable then draw the point.

Is there any plugin for VS or program to show type and value etc... of a C# code selection?

What I want to do is be told the type, value (if there is one at compile-time) and other information (I do not know what I need now) of a selection of an expression.
For example, if I have an expression like
int i = unchecked((short)0xFF);
selecting 0xFF will give me (Int32, 255), while selecting ((short)0xFF) will give me (Int16, 255), and selecting i will give me (Int32, 255).
Reason why I want such a feature is to be able to verify my assumptions. It's pretty easy to assume that 0xFF is a byte but it is actually an int. I could of course refer to the C# Language Specifications all the time, but I think it's inefficient to have to refer to it everytime I want to check something out. I could also use something like ANTLR but the learning curve is high.
I do intend to read the entire specs and learn ANTLR and about compilers, but that's for later. Right now I wish to have tools to help me get the job done quickly and accurately.
Another case in point:
int? i = 0x10;
int? j = null;
int x;
x = (i >> 4) ?? -1;//x=1
x = (j >> 4) ?? -1;//x=-1
It may seem easy to you or even natural for the bottom two lines in the code above. (Maybe one should avoid code like these, but that's another story) However, what msdn says about the null-coalescing operator is lacking information to tell me that the above code ((i>>4)??) is legal (yet it is, and it is). I had to dig into grammar in the specs to know what's happening:
null-coalescing-expression
conditional-or-expression
conditional-and-expression
exclusive-or-expression
and-expression
equality-expression
relational-expression
shift-expression
shift-expression right-shift additive-expression
... (and more)
Only after reading so much can I get a satisfactory confirmation that it is valid code and does what I think it does. There should be a much simpler way for the average programmer to verify (not about validity, but whether it behaves as thought or not, and also to satisfy my curiosity) such code without having to dive into that canonical manual. It doesn't necessary have to be a VS plugin. Any alternative that is intuitive to use will do just as well.
Well, I'm not aware of any add-ins that do what you describe - however, there is a trick you can use figure out the type of an expression (but not the compile-time value):
Assign the expression to a var variable, and hover your mouse over the keyword var.
So for example, when you write:
var i = unchecked((short)0xFF);
and then hover your mouse over the keyword var, you get a tooltip that says something like:
Struct System.Int16
Represents a 16-bit signed integer.
This is definitely a bit awkward - since you have to potentially change code to make it work. But in a pinch, it let's you get the compiler to figure out the type of an expression for you.
Keep in mind, this approach doesn't really help you once you start throwing casts into the picture. For instance:
object a = 0xFF;
var z = (string)a; // compiles but fails at runtime!
In the example above, the IDE will dutifully report that the type of var z is System.String - but this is, of course, entirely wrong.
Your question is a little vague on what you are looking for, so I don't know if "improved" intellisense solves it, but I would try the Productivity Power Tools.

All valid combinations of points, in the most (speed) effective way

I know there are quite some questions out there on generating combinations of elements, but I think this one has a certain twist to be worth a new question:
For a pet proejct of mine I've to pre-compute a lot of state to improve the runtime behavior of the application later. One of the steps I struggle with is this:
Given N tuples of two integers (lets call them points from here on, although they aren't in my use case. They roughly are X/Y related, though) I need to compute all valid combinations for a given rule.
The rule might be something like
"Every point included excludes every other point with the same X coordinate"
"Every point included excludes every other point with an odd X coordinate"
I hope and expect that this fact leads to an improvement in the selection process, but my math skills are just being resurrected as I type and I'm unable to come up with an elegant algorithm.
The set of points (N) starts small, but outgrows 64 soon (for the "use long as bitmask" solutions)
I'm doing this in C#, but solutions in any language should be fine if it explains the underlying idea
Thanks.
Update in response to Vlad's answer:
Maybe my idea to generalize the question was a bad one. My rules above were invented on the fly and just placeholders. One realistic rule would look like this:
"Every point included excludes every other point in the triagle above the chosen point"
By that rule and by choosing (2,1) I'd exclude
(2,2) - directly above
(1,3) (2,3) (3,3) - next line
and so on
So the rules are fixed, not general. They are unfortunately more complex than the X/Y samples I initially gave.
How about "the x coordinate of every point included is the exact sum of some subset of the y coordinates of the other included points". If you can come up with a fast algorithm for that simply-stated constraint problem then you will become very famous indeed.
My point being that the problem as stated is so vague as to admit NP-complete or NP-hard problems. Constraint optimization problems are incredibly hard; if you cannot put extremely tight bounds on the problem then it very rapidly becomes not analyzable by machines in polynomial time.
For some special rule types your task seems to be simple. For example, for your example rule #1 you need to choose a subset of all possible values of X, and than for each value from the subset assign an arbitrary Y.
For generic rules I doubt that it's possible to build an efficient algorithm without any AI.
My understanding of the problem is: Given a method bool property( Point x ) const, find all points the set for which property() is true. Is that reasonable?
The brute-force approach is to run all the points through property(), and store the ones which return true. The time complexity of this would be O( N ) where (a) N is the total number of points, and (b) the property() method is O( 1 ). I guess you are looking for improvements from O( N ). Is that right?
For certain kind of properties, it is possible to improve from O( N ) provided suitable data structure is used to store the points and suitable pre-computation (e.g. sorting) is done. However, this may not be true for any arbitrary property.

Categories

Resources