How to implement Excel Solver functionality in C#? [duplicate] - c#

This question already has answers here:
Recommended library for linear programming in .Net? [closed]
(3 answers)
Closed 5 years ago.
I have an application in C#, I need to do some optimization calculations, like Excel Solver Add-in does, one option is certainly to write my own solver implementation, but I'm kind of short of time, so I'm looking into libraries that already exist that can help me with this.
I've been trying the Microsoft Solver Foundation, which seems pretty neat and cool, the problem is that it doesn't seem to work with the kind of calculations that I need to do.
At the end of this question I'm adding the information about the calculations I need to perform and optimize.
So basically my question is if any of you know of any other library that I can use for this purpose, or any tutorial that can help to do my own solver, or any idea that gives me a lead to solve this issue.
Thanks.
Additional Info:
This is the data I need to calculate:
I have 7 variables, lets call them var1, var2,...,var7
The constraints for these variables are:
All of them need to be 0 <= varn <= 0.5 (where n is the number of the variable)
The sum of all the variables should be equal to 1
The objective is to maximize the target formula, which in Excel looks like this:
(MMULT(TRANSPOSE(L26:L32),M14:M20)) / (SQRT(MMULT(MMULT(TRANSPOSE(L26:L32),M4:S10),L26:L32)))
The range that you see in this formula, L26:L32, is actually the range with the variables from above, var1, var2,..., varn.
M14:M20 and M4:S10 are ranges with data that I get from different sources, there are more likely decimal values.
As I said before, I was using Microsoft Solver Foundation, I modeled pretty much everything with it, I created functions that handle the operations of the target formula, but when I tried to solve the model it always fail, I think it is because of the complexity of the operations.
In any case, I just wanted to show these data so you can have an idea about the kind of calculations that I need to implement.

Here are some commercial .NET libraries containing different kind of multivariate optimization functions which can be a replacement for Excel's solver:
Extreme Optimization Numerical Libraries
Centerspace NMath.Net library
Visual Numerics library
If you find a good non-commercial / open source library for this purpose, let me know.

Related

Why isn't string concatenation automatically converted to StringBuilder in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is String.Concat not optimized to StringBuilder.Append?
One day I was ranting about a particular Telerik control to a friend of mine. I told him that it took several seconds to generate a controls tree, and after profiling I found out that it is using a string concatenation in a loop instead of a StringBuilder. After rewriting it worked almost instantaneously.
So my friend heard that and seemed to be surprised that the C# compiler didn't do that conversion automatically like the Java compiler does. Reading many of Eric Lippert's answers I realize that this feature didn't make it because it wasn't deemed worthy enough. But if, hypothetically, costs were small to implement it, what rationale would stop one from doing it?
But if, hypothetically, costs were small to implement it, what rationale would stop one from doing it?
It sounds like you're proposing a bit of a tautology: if there is no reason to not do X, then is there a reason to not do X? No.
I see little value in knowing the answers to hypothetical, counterfactual questions. Perhaps a better question to ask would be a question about the real world:
Are there programming languages that use this optimization?
Yes. In JScript.NET, we detect string concatenations in loops and the compiler turns them into calls to a string builder.
That might then be followed up with:
What are some of the differences between JScript .NET and C# that justify the optimization in the one language but not in the other?
A core assumption of JScript.NET is that its programmers are mostly going to be JavaScript programmers, and many of them will have already built libraries that must run in any implementation of ECMAScript. Those programmers might not know the .NET framework well, and even if they do, they might not be able to use StringBuilder without making their library code non-portable. It is also reasonable to assume that JavaScript programmers may be either novice programmers, or programmers who came to programming via their line of business rather than a course of study in computer science.
C# programmers are far more likely to know the .NET framework well, to write libraries that work with the framework, and to be experienced programmers who understand why looped string concatenation is O(n2) in the naive implementation. They need this optimization generated by the compiler less because they can just do it themselves if they deem it necessary.
In short: compiler features are about spending our budget to add value for the customer; you get more "bang for buck" adding the feature to JScript.NET than you do adding it to C#.
The C# compiler does better than that.
a + b + c is compiled to String.Concat(a, b, c), which is faster than StringBuilder.
"a" + "b" is compiled directly to "ab" (useful for multi-line literals).
The only place to use StringBuilder is when concatenating repetitively inside a loop; the compiler cannot easily optimize that.

How do I parse a string and get formula? in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Evaluate C# string with math operators
So lets say I have a basic string with the value "1*2+4"
How would I go about parsing the information and then doing the calculation?
I am self teaching c# but my assumption is this is a common issue in programming but without using a library how would one do this?
My results so far have got me splitting the string up and putting them into an array of chars, but this is where I've stopped since I am trying to figure out how to compare chars to operators and chars to ints.
I am not sure if I am going the right way about this but would be great if someone could point me in the right direction.
Thank you for your help in advanced.
What you're looking for is the Shunting-yard algorithm.
You'll need at least two stacks; one for storing operators and one for operands. After you fill the stacks you can make a RPN and calculate the answer.
Well c# (or any other language) might provide you with various tools to help you, but the overall approach to the problem will always remain the same whatever the programming language be.
So yes, you do split up into operators & integers. You do recognize the characters one by one, but try to do it in the most efficient way of the language. Fosco's anser points to the right link. Use Ncalc Library than doing manual labor.
However, to complete what you started :
int.Parse(str)
int.TryParse(str, out num)
...are the functions you may consider to convert character strings into integers (which you got, by using split() function?) in C#. You can read about them here...(Parse, TryParse)
If you want to learn how the various existing libraries do it, you should learn about parsing, lexical and syntactic analysis, expression trees, compiler theory, etc. Also, go through the source-code of any of the multiple open-source libraries that do it.

Looking for a few good C# interview problems [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 11 years ago.
Improve this question
I do not want to ask candidates questions, but rather give them several problems to resolve. The reason for this is that I've seen people be excellent with theory, but when confronted by a real world c# issue, just couldn't hack it.
These c# problems should be simple enough that it won't take more than 1-20 minutes to resolve, yet complicated enough that I'd be able to weed out candidates that can't code.
Right now, I typically ask the applicants to reverse a string and remove duplicates from a List. This alone weeds out a large number of people.
Any other examples I could use?
Edit: I should have mentioned that this is for a standard c# gig, where they'll be writing business code rather than finding the most optimal way to implement a linked list.
I like picking simple problems that I actually had to solve at some point; it doesn't get more relevant to the job than that.
When I worked on VBScript I'd ask college candidates how to write a simplified version of DateDiff, since doing so was what I did my first real day of work at Microsoft. More advanced candidates I would ask how to build a device which tracks the relationship between 32 bit handles and an associated 64 bit pointer, which again I actually had to do when working on VBScript.
More recently I tend to ask questions about tree manipulation algorithms, since the compiler is all about tree manipulation. Or about how to codegen new operators using monads, since that's how LINQ works.
My point is not that you should use questions in these areas, my point is that surely you must have had problems that you had to solve in your day-to-day work. Ask the candidates about those problems -- then you'll learn how they solve a realistic problem, and they'll learn what sorts of problems they'd be solving if they came to work with you.
dont ask for knowledge of class libraries or obscure corners of the language (unsafe, dynamic, ..); smart people can pick these up or look them up.
I would ask to design a class hierarchy to represent something real world (vehicles, animals, ...). This usually flushes out the people who dont get objects. Make them do it with interfaces too. Also make them reverse a string - no harm in oldies but goldies
I agree with you, it is surprising how many people claim to be experienced and you find out that all that they did was read the box…
I don’t know if testing for C# is as valuable as it first seems… sure you could ask them to describe an example of when they needed to use inheritance, or why casting might have a performance problem, etc. But these are easy to study for. You would be surprised at how many interviewees give the example using “car” or “color” when giving their real world example of inheritance…. Guess they are in a book somewhere.
When looking at this problem it helps me when I compare experience in development to learning Spanish. A short time into the class everyone is conjugating verbs and can pass a test on this… but nobody speaks Spanish yet. You want the guy that claims to speak Spanish and can actually do it.
So I like to be more specific with the other technologies that will tell me if they have traveled the well-worn path of development. If they say they are an ASP.Net developer I ask them simple questions, but ones that are on the path
EXAMPLES: Give me an example of where the connection string could live? If you need to pass an ID from one page to another, what are your options? If a page takes 5 minutes to load, tell me how you would go about troubleshooting it. If I had a web page that had a single button on it, how would I center that button? Tell me the difference between storing variables in the viewstate verses session state?
You don’t have to know everything, but eighty percent of the people interviewing for a senior level position will get 10% of these types of questions right. (And on 70% of the phone interviews you will hear them Googling for the answers – good thing these aren’t the types of questions you can easily Google for.)
SQL Server is about the same. They say they would rate themselves an 8 or 9 in SQL Sever development, but then get 10% of questions. The questions again are to see if you have been on the well-worn path.
EXAMPLES: If you had a table of customers and a table of orders, how would you find the customers that had no orders? What is a clustered index? If I had a table of developers and a table of projects, how would I set it up so that projects could have multiple developers on it and developers could be on multiple projects?
How could you develop in SQL Server for “years” and not have hit these concepts? A high percentage of candidates get almost none of these answers right!! (I guess the SQL Server box isn’t as informative.)
So if you say you are a senior level guy and you can say “Soy un revelador de software” (I am a software developer), but can’t say “He hecho eso antes” (I have done that before), I don’t think you are the senior level person you are claiming to be.
Now this tells you if they have been on the well-worn path, but not if they are smart and have good problem solving skills. Having gone thru a ton of these types of interviews I can tell you that by the time the process is done you will be satisfied with having enough information to have a strong opinion on both of these issues. You might also see that by then giving them a problem set to solve is unnecessary.
Show them a small section of code or architecture diagram from one of your own projects and ask them to suggest how they would refactor it. Even if you don't wind up hiring them, you might get some interesting suggestions on ways to improve your code.
Building Eric's and other answers here, but answering as an only-ever-so-far-interviewee, what I would like in an interview is a kind of pair-programming 'test', where you sit down together facing the screen, and talk through a real-world problem.
I think there would be many advantages:
For the interviewee, being in front of a screen instead of facing the interviewer makes it easier to think about the problem rather than the interview.
For the interviewer, being with the interviewee while they look through the code and ask questions about the problem space would give a much greater insight into how the interviewee thinks, how they approach problems, and how they communicate and interact with others.
I would expect that it's more important and interesting to see a candidate thinking round the edges of your real-world problem, even if they don't completely solve it, than to have them get 10 out of 10 on come algorithmic test.
Something mildly algorithmic.
Write a method that returns true if a string is a palindrome, and false otherwise.
Re-implement the String.Substring(int, int) method.
Something about object-oriented design too.
Design a checkers game (ie, define the classes and some of the methods).
One question I was asked, and subsequently ask interviewees, is"Describe how you would make this phone into an application". Have them describe the classes, their properties, methods, interfaces, etc. Then question them on why they chose to implement them in that specific way. It gives you a good idea if they understand how to code, and gives you some insight into how they approach and solve problems.
Also, if you offer a suggestion of how they could have implemented it a different way, it may show you whether they are open to new ideas, criticism, or if they are a team player or not.
Fizz Buzz

Coding guidelines + Best Practices? [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 couldn't find any question that directly applies to my query so I am posting this as a new question. If there is any existing discussion that may help me, please point it out and close the question.
Question:
I am going to do a presentation on C# coding guidelines but it is not supposed to limit to coding standards.
So I have a rough idea but I think I need to address good programing practices. So the contents will be something like this.
Basic coding standards - Casing, Formatting etc.
Good practices - Usage of Hashset over other data structures, String vs String Builder, String's immutability and using them effectively etc
Really I would like to add more good practices (Especially to improve the performance.) So like to hear some more good practices to be used with C#. Any suggestions??? (No need of large descriptions :) Just the idea is sufficient.)
Coding Guidelines for CSharp 3.0 and 4.0
IDesign Coding Standards
Lance Hunt's C# Coding Standards
Brad Abrams' Internal Coding Guidelines
Unsurprisingly, I just found a SO question: C# Coding standard / Best practices
Here are a few tips:
Use FxCop for static analysis.
Use StyleCop for coding style validation.
Because of the different semantics of value types, supply them with an alternative color in the IDE (go to Tools / Options / Environment / Fonts and Colors / Display Items and supply User Types (Enums) and User Types (Value types) with a value like #DF7120 [223, 113, 32]).
Because exceptions tend to show bugs in your code, let the IDE break on all exceptions. (go to Debug / Exceptions... / Common Language Runtime Exceptions and check Throw).
Project settings: Disallow unsafe code.
Project settings: Threat warnings as errors.
Project settings: Check for arithmetic overflow/underflow.
Use variables for a single, well defined goal.
Don't use magic numbers.
Write short methods. A method should only contain one level of abstraction.
A method can never be too small (a method of 20 lines is considered pretty big).
A method should protect itself against bad input.
Consider making a type immutable.
Don't suppress warnings in your code with pragma warning disable.
Don't comment bad code: rewrite it.
Document explicitly in code why you are swallowing an exception.
Note the performance implications of concatenating strings.
Never use goto statements.
Fail early, fail fast.
I'm using Microsoft's Design Guidelines for Developing Class Libraries.
And I think it is quite good to start with.
Basic Coding Standards - Make sure it's consistent. Even if they don't follow the conventions set out in this document on msdn. I think consistency is really key here.
Unit Tests - You cannot go wrong here.
Security - Talk about ensuring that if you are passing sensitive data around that it's secure.
Performance - You know, I personally feel that getting the application right and then looking at performance is what I do. I do have it in the back of my mind when writing code, so it's little fine tunings that come in at the end.

How do you do maths (or math) with numbers bigger than MaxValue in C#? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Big integers in C#
I want to be able to process arbitrarily large numbers in C#.
I can live with just integers.
Are there established algorithms for this kind of thing?
Or is there a good 3rd-party library?
I might consider changing language if there really is no good way to do it in C#.
Thanks for any help / suggestions.
You might want to check the Big Num kind of libraries. In C# the most popular ones are: IntX and W3b.Sine, plus, they are both Open Source.
Someone has done a BigInteger class in C# at codeproject
C# BigInteger Class.
Worth checking out.
And a sample of the general algorithm can be found at : Re: Hi-prec math for visual studio c#? (It's the post at the bottom of the page with the code snippet)
As people have mentioned, there are various 3rd-party implementations of a BigInteger class. Also, C# 4.0 will be getting a native BigInteger class in the CLR.
If you just need very large numbers, you could use long (64-bit), or even decimal (128-bit floating point).
If you need values larger than 9223372036854775807 (long) or 79228162514264337593543950335 (decimal), then you need to ignore this answer.

Categories