Refer to a specific index of an array depending on user input - c#

Trying to make a program where it takes in an equation from user and outputs the answer. Having to develop all code for it to work, and wondering how I could refer to either array index value either side of a specific index?
Example:
User input: X = 5 + 5 * 6
Wanting to be able to locate the ***** and retrieve the value of the 5 & 6 either side of it. Tried multiple things and tried searching here too, cannot find a answer.
Thankyou in advance to anyone who takes the time to help!

One way to do it is to use regular expressions. I would remove all whitespaces first to make it easier. For example:
string input = "X = 5 + 5 * 6";
Regex r = new Regex(#"(\d+)\*(\d+)");
Match m = r.Match(input.Replace(" ", ""));
var a = m.Groups[1].Value; // a = 5
var b = m.Groups[2].Value; // b = 6
Explanation of this regex can be found here: https://regex101.com/r/k7rthI/1
You would have to improve the regex to handle decimals and many other cases when the equation gets more complex. It is a long dark rabbit hole to go down if you get more complex than what you have. So you might be better off finding a math library you can use. No reason to reinvent the wheel.

Related

C# Modularised Conversion utility program mimic of google search when converting measurements

The task that i have is to create a replica of a search engine that converts measurements. The user enters "4cm to inches" and the program makes the appropriate calculations to give the answer in inches. Now this program must be able to convert through a range of different measurements and dimensions eg Volume and area also. So far i have been able to make it convert strictly from cm to inches using properties of strings ie Substring, IndexOf, Convert.Toint16 and i want it to continue doing so but i'm struggling modularising it so that it can do a range of different calculations efficiently. This is what i have so far...
Toconvert = Console.ReadLine();
Cmpos = Toconvert.IndexOf("cm");
Inchespos = Toconvert.IndexOf("inches");
CmUnits = Toconvert.Substring(Cmpos, 2);
InchesUnits = Toconvert.Substring(Inchespos, 6);
number2convert = Convert.ToInt16(Toconvert.Substring(0, Cmpos));
Inches = number2convert / 2.54;
Console.WriteLine("{0}{1} is {2:F2} {3}", number2convert, CmUnits, Inches, InchesUnits);
Console.ReadLine();
This is very problematic/limiting and has me perplexed. Every route ive taken ive encountered an error of some sort.
All i want it to do is read whats been input by the user, and outputs the appropriate value from what the computer has.
Learn Regex, it will be your friend, especially for something like this.
Here's a query that will help for your particular case:
([0-9]+[.]?[0-9]*)[\s]*([\w]+)[\s]+[\w]+[\s]+([\w]+)
Loosely translated: Look for numbers (4), then a space or not, then a word (cm), then space, then a word (to), then space, then a word (inches).
Regex offers "groups" (the items in parentheses). for 4cm to inches in the above Regex, the groups are 4, cm and inches...all the useful bits.
This is an example of it in use. There's also very good explanations for each step of the Regex (Click on the "Explain" tab).
Here's a C# example:
var reg = new System.Text.RegularExpressions.Regex(#"([0-9]+[.]?[0-9]*)[\s]*([\w]+)[\s]+[\w]+[\s]+([\w]+)");
var match = reg.Match("4cm to inches");
double numberToConvert = double.Parse(match.Groups[1].Value);
string fromUnits = match.Groups[2].Value;
string toUnits = match.Groups[3].Value;

Microsoft ml.net Concatenate 2 columns as a label

I've been wondering if it was possible to concatenate 2 columns of the datatype string into the label column.
What I tried was:
pipeline.Add(new ColumnConcatenator("Label", "string1", "string2"));
But that just spits out a V2(text, 2). And a Label must be of type R4-R8.
The reason I need this is because I only have 2 input variables and I want to use regression to determine which is the best.
Thanks !
ColumnConcatenator is currently taking your two columns and producing a new vector typed column of width two. It's taking a and b and up-converting to a vector [a, b].
I think you're asking how to produce a new Label equal to a + b where a & b are strings. Eg: var a = "Hello"; var b = "World"; var c = a + c; // c is HelloWorld.
There is no way currently in ML.NET to accomplish the second method (normal string concat). You may want to combine your strings before the ML.NET code. It's something we'll look into for future versions of ML.NET, and you're invited to submit an issue requesting it: https://github.com/dotnet/machinelearning/issues/new.
Update:
We have added the expression transform which can be used to concatenate strings (among many other things).
Usage:
pipeline.Append(ML.Transforms.Expression("Label", "(x, y) : concat(x, \"-\", y)", "LabelColOne", "LabelColTwo"))
For input of LabelColOne="Cat" and LabelColTwo="Dog", it join them together with a "-" to produce Label="Cat-Dog".

How to get random number with each number has its own probability [duplicate]

This question already has answers here:
how to implement non uniform probability distribution?
(3 answers)
Closed 9 years ago.
For example, I want to get random number from set S = {0, 1, 2, 3}. But instead of each number has same probability to shown (which is 25%), now I have different probability for each number, let say {50%, 30%, 20%, 10%}.
How do I code this? In Java or C# (I prefer C#).
The Alias Method is by far my favorite for doing this.
http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/
I haven't reviewed this code but it is a top google result.
Here is another much better explanation
http://pandasthumb.org/archives/2012/08/lab-notes-the-a.html
I actually use this question for interviews quite often since if you have never seen it before it can be pretty puzzling.
If the above is too much for you to implement there is a simpler one loop through the input solution.
Using PHP since it is easier to just show the code.
function getNumberFromDistribution($dist) {
$totalProbability = 0;
$randomNumber = mt_rand(0, mt_getrandmax()) / mt_getrandmax(); //uniform random number between 0-1
foreach($dist as $number => $chance) {
if (($totalProbability += $chance) <= $randomNumber) {
return $number;
}
}
return null; //only reachable on bad input
}
If the set is small you can build an array that contains the right number of each value you need to get your distribution eg. 1 1 1 2 2 3 would provide 3 times the likelihood of getting a 1 as it does of getting a 3. You would then use the length of the array to determine the random number that you use as an index.

entering a string to be used as a formula , in c#

I've found the shunting yard algorithm, but it feels like case is a little bit different.
What if the formula your entering has variables that you want to use in another formula
you enter
cout<<"enter string"<<endl;
cin>>f;
and you enter f as
3 * (X*X) + 2*X + 7
and you use that string and parse it to find the root, for example.
While it is hard to understand what you are looking for, it hints at the ability to evaluate strings as formulas. If your looking for an Eval like solution, take a look at nCalc. Stealing from their webpage:
Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
It also allows you to use parameters, like
e.Parameters["X"] = 10;
and then use X as part of your string to evaluate.
It let's you convert a string representing a formula into it's final value. If you are not asking about interpreting strings at formulas then I am at a loss for what you are asking. I recommend revising your question to better articulate the inputs and outputs of your proposed functionality.
One solution that comes to my mind is, may be you can create a valid C# code from that string at runtime and make it compile, and make it execute. For example your code cam become in memory like
using namespace FormulaCalculator
{
public class Calculator
{
public static object Calculate()
{
return 3 * (X*X) + 2*X + 7 ; //where X is replaced value at runtime.
}
}
}
Compile this with CodeDome in in-memory assembly and run. Here an example Example
object resultOfFormula = FormulaCalculator.Calculator.Calculate()

C# Find the Next X and Previous Numbers in a sequence

I have a list of numbers, {1,2,3,4,...,End} where End is specified. I want to display the X closest numbers around a given number Find within the list. If x is odd I want the extra digit to go on the greater than side.
Example (Base Case)
End: 6
X: 2
Find: 3
The result should be: {2,3,4}
Another Example (Bound Case):
End: 6
X: 4
Find: 5
The result should be: {2,3,4,5,6}
Yet Another Example (Odd Case):
End: 6
X: 3
Find: 3
The result should be: {2,3,4,5}
I'm assuming it would be easier to simply find a start and stop value, rather than actually generating the list, but I don't really care one way or another.
I'm using C# 4.0 if that matters.
Edit: I can think of a way to do it, but it involves way too many if, else if cases.
if (Find == 1)
{
Start = Find;
Stop = (Find + X < End ? Find + X : End);
}
else if (Find == 2)
{
if (X == 1)
{
Start = Find;
End = (Find + 1 < End ? Find + 1 : End);
}
...
}
You can hopefully see where this is going. I assuming I'm going to have to use a (X % 2 == 0) for odd/even checking. Then some bound thats like less = Find - X/2 and more = Find + X/2. I just can't figure out the path of least if cases.
Edit II: I should also clarify that I don't actually create a list of {1,2,3,4...End}, but maybe I need to just start at Find-X/2.
I realise that you are learning, and out of respect from this I will not provide you with the full solution. I will however do my best to nudge you in the right direction.
From looking at your attempted solution, I think you need to figure out the algorithm you need before trying to code up something that may or may not solve your problem. As you say yourself, writing one if statement for every possible permutation on the input is not a manageble solution. You need to find an algorithm that is general enough that you can use it for any input you get, and still get the right results out.
Basically, there are two questions you need to answer before you'll be able to code up a working solution.
How do I find the lower bound of the list I want to return?
How do I find the upper bound of the list I want to return?
Considering the example base case, you know that the given parameter X contains a number that tells you how many numbers around Find you should display. Therefore you need to divide X equally on both sides of Find.
Thus:
If I get an input X = 4 and Find = 3, the lower bound will be 3 - 4/2 or Find - X/2.
The higher bound will be 3 + 4/2 or Find + X/2.
Start by writing a program that runs and works for the base case. Once that is done, sit down and figure out how you would find the higher and lower bounds for a more complicated case.
Good luck!
You can look at Extension methods. skip and take.
x.Skip(3).Take(4);
this will help u in what u r trying to do

Categories