i want make math operation with one button C# - c#

i want make math operation with one button and textbox , when type on textbox operation like 25+5+-10+7 and press on button show me result
i am trying do this but i can not.
in this code i make for each char in textbox and i want store 25 in firstvalue parameter and + in op parameter and 5 in secondvalue parameter
and make operation 25+5=30 and store it in firstvalue parameter and store +- in op , 10 in secondvalue and make operation ,store it in firstvalue ....and so on until length of string .
but i do not know where and how store second value
private void button1_Click(object sender, EventArgs e)
{
string allValue = textBox1.Text;
int firstValue=0;
int secondValue=0;
string first = string.Empty;
string op = string.Empty;
foreach (char item in allValue)
{
if (char.IsNumber(item))
{
first += item;
}
else if(item=='+' || item=='-' || item=='*' || item=='/')
{
firstValue = Int32.Parse(first);
op += item;
first = "";
switch (op)
{
case "+":
firstValue = firstValue + secondValue;
break;
case "-":
firstValue = firstValue - secondValue;
break;
case "+-":
firstValue = firstValue +- secondValue;
break;
case "*":
firstValue = firstValue * secondValue;
break;
case "/":
firstValue = firstValue / secondValue;
break;
}
}
}
MessageBox.Show(firstValue.ToString());
}

If you want to parse the string from beginning to end and do the calculations during the parsing, then you can't do the calculation between two values until you have both operands. That means that you have to wait until you find the second operator (or the end of the string) until you can do the calculation for the first operator.
When you parse the number, put that in the secondValue variable. If it's the first value then just move it to firstValue and continue to get another value, otherwise do the calculation with the two values that you have according to the previous operator.
To include the last calculation you can loop one step more than the last character in the string. That allows your loop to run one more time after the last value, and you can do that last calculation. It requires a few more checks though, so that you don't actually try to read from that position outside the string.
To handle negative values you should include that in the value, not using a +- operator. Otherwise you would also need --, *- and /- operators.
Example (not tested):
private void button1_Click(object sender, EventArgs e) {
string allValue = textBox1.Text;
int firstValue = 0;
int secondValue = 0;
string second = string.Empty;
string op = string.Empty;
for (int i = 0; i <= allValue.Length; i++) {
if (i < allValue.Length && (Char.IsNumber(allValue[i]) || (char == '-' && second.Length == 0))) {
second += allValue[i];
} else if (i == allValue.Length || "+-*/".indexOf(allValue[i]) != -1) {
secondValue = Int32.Parse(second);
if (op.Length > 0) {
switch (op) {
case "+": firstValue += secondValue; break;
case "-": firstValue -= secondValue; break;
case "*": firstValue *= secondValue; break;
case "/": firstValue /= secondValue; break;
}
} else {
firstValue = secondValue;
}
if (i < allValue.Length) {
op = allValue[i].ToString();
}
second = "";
} else {
// illegal formula
}
}
MessageBox.Show(firstValue.ToString());
}
Note: This calculates strictly from left to right and does not handle priority, e.g. 1+2*3 is evaluated as (1+2)*3, not the 1+(2*3) that is normally used.

You can use the NCalc library. You would use it like this:
NCalc.Expression e = new NCalc.Expression(textBox1.Text);
double value = e.Evaluate();
// Next, do something with your evaluated value.

Would this work for you? As mentioned in earlier answers this does not pay regard to the order of operations and there is a lot of other error checking that should likely be done.
using System.Text.RegularExpressions;
private void button1_Click(object sender, EventArgs e)
{
MatchCollection values = Regex.Matches(textBox1.Text, "[0-9]+");
MatchCollection operations = Regex.Matches(textBox1.Text, #"[\/\*\+-]");
if (values.Count == operations.Count + 1)
{
int total = int.Parse(values[0].Value);
if (operations.Count > 0)
{
for (int index = 1; index < values.Count; index++)
{
int value = int.Parse(values[index].Value);
switch (operations[index - 1].Value)
{
case "+":
total += value;
break;
case "-":
total -= value;
break;
case "/":
total /= value;
break;
case "*":
total *= value;
break;
}
}
}
MessageBox.Show(total.ToString());
}
}

Doing all the things from scratch is not easy. In my simplified answer I'll presume your operators are only +-*/ (including their precedence).
Reference: How to evaluate an infix expression in just one scan using stacks?
First you should parse the input string... My way would be
public enum TokenType
{
Operator,
Operand
}
public class Token
{
public string Value { get; set; }
public TokenType Type { get; set; }
public override string ToString()
{
return Type + " " + Value;
}
}
IEnumerable<Token> Parse(string input)
{
return Regex.Matches(input, #"(?<value>\d+)|(?<type>[\+\-\*\/\(\)])").Cast<Match>()
.Select(m => m.Groups["value"].Success
? new Token() { Value = m.Groups["value"].Value, Type = TokenType.Operand }
: new Token() { Value = m.Groups["type"].Value, Type = TokenType.Operator });
}
This Parse method will return all the operators and operands in your expression.
The next step would be to evaluate the expression using a stack
Token Exec(Stack<Token> operatorStack, Stack<Token> operandStack)
{
var op = operatorStack.Pop();
var t1 = operandStack.Pop();
var t2 = operandStack.Pop();
switch (op.Value)
{
case "+": return new Token() { Value = (int.Parse(t1.Value) + int.Parse(t2.Value)).ToString(), Type = TokenType.Operand };
case "-": return new Token() { Value = (int.Parse(t2.Value) - int.Parse(t1.Value)).ToString(), Type = TokenType.Operand };
case "*": return new Token() { Value = (int.Parse(t1.Value) * int.Parse(t2.Value)).ToString(), Type = TokenType.Operand };
case "/": return new Token() { Value = (int.Parse(t2.Value) / int.Parse(t1.Value)).ToString(), Type = TokenType.Operand };
}
return null;
}
int Eval(string input)
{
var tokens = Parse(input);
var operatorStack = new Stack<Token>();
var operandStack = new Stack<Token>();
var precedence = new Dictionary<string, int>() { { "+", 0 }, { "-", 0 }, { "*", 1 }, { "/", 1 } };
foreach (var token in tokens)
{
if (token.Type == TokenType.Operand) operandStack.Push(token);
if (token.Type == TokenType.Operator)
{
while (operatorStack.Count > 0 && precedence[operatorStack.Peek().Value] >= precedence[token.Value])
{
operandStack.Push(Exec(operatorStack, operandStack));
}
operatorStack.Push(token);
}
}
while(operatorStack.Count>0)
{
operandStack.Push(Exec(operatorStack, operandStack));
}
return int.Parse(operandStack.Pop().Value);
}
You can test your code now.
int r1 = Eval("25 - 5");
int r2 = Eval("25 - 5*2");
int r3 = Eval("25 - 5 + 3*2");
int r4 = Eval("25/5 + 7*3");
int r5 = Eval("25/5 + 7*3 + 2");
int r6 = Eval("25/5 + 7*3 * 2");

Related

Trying to detect which html tags are affecting an element in a string

I am trying to write a markup editor in c#, part of is is to detect which tags are affecting where the caret currently is.
Examples:
<b>Tes|ting</b><u><i>Testing</i>Testing</u> (caret '|' at index 6)
Answer: [b]
<b>Testing<u><i>Test|ing</i>Tes</b>ting</u> (caret '|' at index 20)
Answer: [b, u, i]
Here is the code I have currently, inside "GetTags()" I split the string into 2 queues representing what tags are in front and behind where the caret is. I played around with ways to pop the elements from both queues to try to solve the problem but I keep getting wrong results. I think im on the right track creating 2 data structures but I don't know if Queue<> is what I need.
public class Tag
{
public enum TagType
{
bold,
italic,
underline,
}
public TagType type;
public bool opening;
public Tag(TagType type, bool opening)
{
this.type = type;
this.opening = opening;
}
public static Tag GetTagFromString(string str)
{
switch (str)
{
case "<b>": return new Tag(TagType.bold, true);
case "</b>": return new Tag(TagType.bold, false);
case "<i>": return new Tag(TagType.italic, true);
case "</i>": return new Tag(TagType.italic, false);
case "<u>": return new Tag(TagType.underline, true);
case "</u>": return new Tag(TagType.underline, false);
}
return null;
}
public static List<TagType> GetTags(string str, int index)
{
Queue<Tag> backQueue = new Queue<Tag>();
Queue<Tag> forwardQueue = new Queue<Tag>();
// populate the back queue
int i = index;
while (true)
{
int lastOpening = str.LastIndexOf('<', i);
int lastClosing = str.LastIndexOf('>', i);
if (lastOpening != -1 && lastClosing != -1)
{
string tagStr = str.Substring(lastOpening, lastClosing - lastOpening + 1);
Tag tag = GetTagFromString(tagStr);
backQueue.Enqueue(tag);
i = lastOpening - 1;
if (i < 0)
break;
}
else
break;
}
// populate the front stack
i = index;
while (true)
{
int nextOpening = str.IndexOf('<', i);
int nextClosing = str.IndexOf('>', i);
if (nextOpening != -1 && nextClosing != -1)
{
string tagStr = str.Substring(nextOpening, nextClosing - nextOpening + 1);
Tag tag = GetTagFromString(tagStr);
forwardQueue.Enqueue(tag);
i = nextClosing + 1;
}
else
break;
}
List<TagType> tags = new List<TagType>();
// populate 'tags' list with the tags affecting the index here
return tags;
}
public override string ToString()
{
string str = "<";
if (!opening)
str += "/";
switch (type)
{
case TagType.bold:
str += "b";
break;
case TagType.italic:
str += "i";
break;
case TagType.underline:
str += "u";
break;
}
str += ">";
return str;
}
}
Would love any input on how I could solve this and would greatly appreciate any issues anyone has with the code that I've provided.

Easy ways to increment with number and letters after checking DB

Using C# and ASP.NET
Lnna is based on values that the user inputs.
I can get those values.
Lnnai is the full form.
Last value 'i' should be incremented through 0-9,a-z and then A-Z. What would be the easiest way to look in DB for values and increment?
var Lnna = L + nn + a;
var ichars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
var i = ?
Examining an ASCII table yeilds
0-9 48-57
A-Z 65-90
a-z 97-122
It is much easier to increment a number than a letter so I converted the last letter to its ASCII value and incremented that then cast it back to a char and then toString.
private void Form2_Load(object sender, EventArgs e)
{
string input = "Lnnnai";
bool foundInDatabase = false;
//set your value after db query
if (foundInDatabase)
{ }//your code here
else
{
string s = input.Substring(input.Length - 1, 1);
s = IncrementCharacter(s);
Debug.Print(s);
string newString = input.Remove(input.Length - 1, 1);
newString += s;
Debug.Print(newString);
}
}
private string IncrementCharacter(String character)
{
int code = Char.ConvertToUtf32(character,0);
switch (code)
{
case 57:
return "A";
case 90:
return "a";
default:
code += 1;
return ((char)code).ToString();
}
}
to use Debug.Print import System.Diagnostics
This is the method I used. It works perfectly.
int tl = items.ShelfId;
var ttl = await _context.Shelfs.FirstOrDefaultAsync(b => b.ShelfId == tl);
var l = ttl.Name;
int tnn = items.CategoryId;
var ttnn = await _context.Categories.FirstOrDefaultAsync(b => b.CategoryId == tnn);
var nn = ttnn.Subject;
string a = items.AuthorLastName.Substring(0, 1);
var lnna = l + nn + a;
var ichars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
var currenti = _context.Items.Count(i => i.LibraryItemNumber.Contains(lnna));
if (currenti > 0 && currenti < 62)
{
var i = ichars[currenti];
var LNNAI = lnna + i;
items.LibraryItemNumber = LNNAI;
}
else if (currenti == 0)
{
var i = ichars[0];
var LNNAI = lnna + i;
items.LibraryItemNumber = LNNAI;
}
else
{
items.LibraryItemNumber = "Exceed";
}

Stackoverflow exception from updating combobox in winforms/C#

I'm geting a StackOverflowException. Somehow, posting here seemed appropriate.
I'm using Windows Forms in a C# application. This application is intended to run on Linux, FreeBSD and Mac-OS, so I can't use WPF, so please don't suggest it.
My guess is that I'm missing a nuance of WinForms, but I cant seem to figure out what.
The ComboBox is generated by the GUI form builder in VS 2010.
The specific lines of code that are throwing the error are here:
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//I only have one of the following two at a time. Both overflow
cbx_material_num.SelectedIndex = 0;
cbx_material_num.Text = "0";
}
Since the code is somewhat complex, here's the whole function code. 'cbx_' indicates a combo box. 'txtb_' is a text box.
private void cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
{
string obj = cbx_material_obj.Text;
string num = cbx_material_num.Text;
int selnum = 0;
int n = 0;
//do we need to recreate the numbers array?
bool cur_num_is_valid = false;
cbx_material_num.Items.Clear();
if(obj != lastobj)
{
n = m_demo.get_object_modifiers(obj);
for(int i = 0; i <= n; i++)
{
string s = i.ToString();
if(s == num && i < n) cur_num_is_valid = true;
cbx_material_num.Items.Add(s);
}
}
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//Overflow here:
cbx_material_num.SelectedIndex = 0;
}
try
{
selnum = int.Parse(num);
}
catch(Exception)
{
MessageBox.Show("Error, second select menu after 'object modifiers' must be a number, not '"+num+"'.");
cbx_material_num.Text="0";
return;
}
if(selnum >= n)
{
txtb_material_param1.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
txtb_material_param4.Text = "0";
}
else
{
MaterialFace face;
MaterialParameter parameter;
int typeid;
object paramdata;
m_demo.get_object_modifiers_material(obj, selnum, out face, out parameter, out typeid, out paramdata);
cbx_material_face.Text = face.ToString();
cbx_material_paramtype.Text = parameter.ToString();
switch(typeid)
{
case 0:
txtb_material_param1.Text = ((float)paramdata).ToString();
cbx_material_datatype.Text = "float";
goto case -1;
case 1:
float[] parsf = ((float[])paramdata);
txtb_material_param1.Text = parsf[0].ToString();
txtb_material_param2.Text = parsf[1].ToString();
txtb_material_param3.Text = parsf[2].ToString();
txtb_material_param4.Text = parsf[3].ToString();
cbx_material_datatype.Text = "float[]";
break;
case 2:
txtb_material_param1.Text = ((int)paramdata).ToString();
cbx_material_datatype.Text = "int";
goto case -1;
case 3:
int[] parsi = ((int[])paramdata);
txtb_material_param1.Text = parsi[0].ToString();
txtb_material_param2.Text = parsi[1].ToString();
txtb_material_param3.Text = parsi[2].ToString();
txtb_material_param4.Text = parsi[3].ToString();
cbx_material_datatype.Text = "int[]";
break;
case -1: //can't actuall be returned, used to 'blank' the last three as '0'
txtb_material_param2.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
break;
case 4:
OpenTK.Graphics.Color4 paramc = ((OpenTK.Graphics.Color4)paramdata);
txtb_material_param1.Text = paramc.R.ToString();
txtb_material_param2.Text = paramc.G.ToString();
txtb_material_param3.Text = paramc.B.ToString();
txtb_material_param4.Text = paramc.A.ToString();
cbx_material_datatype.Text = "Color4";
break;
default: //5
Vector4 paramv = ((Vector4)paramdata);
txtb_material_param1.Text = paramv.X.ToString();
txtb_material_param2.Text = paramv.Y.ToString();
txtb_material_param3.Text = paramv.Z.ToString();
txtb_material_param4.Text = paramv.W.ToString();
cbx_material_datatype.Text = "Vector4";
break;
}
}
}
You need to check that the SelectedIndex isn't already 0 before you try to set it:
if (cbx_material_num.SelectedIndex != 0){
cbx_material_num.SelectedIndex = 0;
}
Otherwise you're re-firing the event every time through.
I think that whenever you set this cbx_material_num.SelectedIndex = 0; within the EventHandler you invoke your
cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
Each call invokes another eventHandler so the stack fills up after some time.
Basically, the fact that it is called SelectedIndexChanged doesn't mean that the value has to be different from the previous one but that the value is set through its setter.

Logic to decrease character values

I am working on a logic that decreases the value of an alphanumeric List<char>. For example, A10 becomes A9, BBA becomes BAZ, 123 becomes 122. And yes, if the value entered is the last one(like A or 0), then I should return -
An additional overhead is that there is a List<char> variable which is maintained by the user. It has characters which are to be skipped. For example, if the list contains A in it, the value GHB should become GGZ and not GHA.
The base of this logic is a very simple usage of decreasing the char but with these conditions, I am finding it very difficult.
My project is in Silverlight, the language is C#. Following is my code that I have been trying to do in the 3 methods:
List<char> lstGetDecrName(List<char> lstVal)//entry point of the value that returns decreased value
{
List<char> lstTmp = lstVal;
subCheckEmpty(ref lstTmp);
switch (lstTmp.Count)
{
case 0:
lstTmp.Add('-');
return lstTmp;
case 1:
if (lstTmp[0] == '-')
{
return lstTmp;
}
break;
case 2:
if (lstTmp[1] == '0')
{
if (lstTmp[0] == '1')
{
lstTmp.Clear();
lstTmp.Add('9');
return lstTmp;
}
if (lstTmp[0] == 'A')
{
lstTmp.Clear();
lstTmp.Add('-');
return lstTmp;
}
}
if (lstTmp[1] == 'A')
{
if (lstTmp[0] == 'A')
{
lstTmp.Clear();
lstTmp.Add('Z');
return lstTmp;
}
}
break;
}
return lstGetDecrValue(lstTmp,lstVal);
}
List<char> lstGetDecrValue(List<char> lstTmp,List<char> lstVal)
{
List<char> lstValue = new List<char>();
switch (lstTmp.Last())
{
case 'A':
lstValue = lstGetDecrTemp('Z', lstTmp, lstVal);
break;
case 'a':
lstValue = lstGetDecrTemp('z', lstTmp, lstVal);
break;
case '0':
lstValue = lstGetDecrTemp('9', lstTmp, lstVal);
break;
default:
char tmp = (char)(lstTmp.Last() - 1);
lstTmp.RemoveAt(lstTmp.Count - 1);
lstTmp.Add(tmp);
lstValue = lstTmp;
break;
}
return lstValue;
}
List<char> lstGetDecrTemp(char chrTemp, List<char> lstTmp, List<char> lstVal)//shifting places eg unit to ten,etc.
{
if (lstTmp.Count == 1)
{
lstTmp.Clear();
lstTmp.Add('-');
return lstTmp;
}
lstTmp.RemoveAt(lstTmp.Count - 1);
lstVal = lstGetDecrName(lstTmp);
lstVal.Insert(lstVal.Count, chrTemp);
return lstVal;
}
I seriously need help for this. Please help me out crack through this.
The problem you are trying to solve is actually how to decrement discreet sections of a sequence of characters, each with it's own counting system, where each section is separated by a change between Alpha and Numeric. The rest of the problem is easy once you identify this.
The skipping of unwanted characters is simply a matter of repeating the decrement if you get an unwanted character in the result.
One difficultly is the ambiguous definition of the sequences. e.g. what to do when you get down to say A00, what is next? "A" or "-". For the sake of argument I am assuming a practical implementation based loosely on Excel cell names (i.e. each section operates independently of the others).
The code below does 95% of what you wanted, however there is a bug in the exclusions code. e.g. "ABB" becomes "AAY". I feel the exclusions need to be applied at a higher level (e.g. repeat decrement until no character is in the exclusions list), but I don't have time to finish it now. Also it is resulting in a blank string when it counts down to nothing, rather than the "-" you wanted, but that is trivial to add at the end of the process.
Part 1 (divide the problem into sections):
public static string DecreaseName( string name, string exclusions )
{
if (string.IsNullOrEmpty(name))
{
return name;
}
// Split the problem into sections (reverse order)
List<StringBuilder> sections = new List<StringBuilder>();
StringBuilder result = new StringBuilder(name.Length);
bool isNumeric = char.IsNumber(name[0]);
StringBuilder sb = new StringBuilder();
sections.Add(sb);
foreach (char c in name)
{
// If we change between alpha and number, start new string.
if (char.IsNumber(c) != isNumeric)
{
isNumeric = char.IsNumber(c);
sb = new StringBuilder();
sections.Insert(0, sb);
}
sb.Append(c);
}
// Now process each section
bool cascadeToNext = true;
foreach (StringBuilder section in sections)
{
if (cascadeToNext)
{
result.Insert(0, DecrementString(section, exclusions, out cascadeToNext));
}
else
{
result.Insert(0, section);
}
}
return result.ToString().Replace(" ", "");
}
Part2 (decrement a given string):
private static string DecrementString(StringBuilder section, string exclusions, out bool cascadeToNext)
{
bool exclusionsExist = false;
do
{
exclusionsExist = false;
cascadeToNext = true;
// Process characters in reverse
for (int i = section.Length - 1; i >= 0 && cascadeToNext; i--)
{
char c = section[i];
switch (c)
{
case 'A':
c = (i > 0) ? 'Z' : ' ';
cascadeToNext = (i > 0);
break;
case 'a':
c = (i > 0) ? 'z' : ' ';
cascadeToNext = (i > 0);
break;
case '0':
c = (i > 0) ? '9' : ' ';
cascadeToNext = (i > 0);
break;
case ' ':
cascadeToNext = false;
break;
default:
c = (char)(((int)c) - 1);
if (i == 0 && c == '0')
{
c = ' ';
}
cascadeToNext = false;
break;
}
section[i] = c;
if (exclusions.Contains(c.ToString()))
{
exclusionsExist = true;
}
}
} while (exclusionsExist);
return section.ToString();
}
The dividing can of course be done more efficiently, just passing start and end indexes to the DecrementString, but this is easier to write & follow and not much slower in practical terms.
do a check if its a number if so then do a minus math of the number, if its a string then change it to char codes and then the char code minus 1
I couldn't stop thinking about this yesterday, so here's an idea. Note, this is just pseudo-code, and not tested, but I think the idea is valid and should work (with a few modifications).
The main point is to define your "alphabet" directly, and specify which characters in it are illegal and should be skipped, then use a list or array of positions in this alphabet to define the word you start with.
I can't spend any more time on this right now, but please let me know if you decide to use it and get it to work!
string[] alphabet = {a, b, c, d, e};
string[] illegal = {c, d};
public string ReduceString(string s){
// Create a list of the alphabet-positions for each letter:
int[] positionList = s.getCharsAsPosNrsInAlphabet();
int[] reducedPositionList = ReduceChar(positionList, positionList.length);
string result = "";
foreach(int pos in reducedPositionList){
result += alphabet[pos];
}
return result;
}
public string ReduceChar(string[] positionList, posToReduce){
int reducedCharPosition = ReduceToNextLegalChar(positionList[posToReduce]);
// put reduced char back in place:
positionList[posToReduce] = reducedCharPosition;
if(reducedCharPosition < 0){
if(posToReduce <= 0){
// Reached the end, reduced everything, return empty array!:
return new string[]();
}
// move to back of alphabet again (ie, like the 9 in "11 - 2 = 09"):
reducedCharPosition += alphabet.length;
// Recur and reduce next position (ie, like the 0 in "11 - 2 = 09"):
return ReduceChar(positionList, posToReduce-1);
}
return positionList;
}
public int ReduceToNextLegalChar(int pos){
int nextPos = pos--;
return (isLegalChar(nextPos) ? nextPos : ReduceToNextLegalChar(nextPos));
}
public boolean IsLegalChar(int pos){
return (! illegal.contains(alphabet[pos]));
}
enter code here
Without writing all your code for you, here's a suggestion as to how you can break this down:
char DecrementAlphaNumericChar(char input, out bool hadToWrap)
{
if (input == 'A')
{
hadToWrap = true;
return 'Z';
}
else if (input == '0')
{
hadToWrap = true;
return '9';
}
else if ((input > 'A' && input <= 'Z') || (input > '0' && input <= '9'))
{
hadToWrap = false;
return (char)((int)input - 1);
}
throw new ArgumentException(
"Characters must be digits or capital letters",
"input");
}
char DecrementAvoidingProhibited(
char input, List<char> prohibited, out bool hadToWrap)
{
var potential = DecrementAlphaNumericChar(input, out hadToWrap);
while (prohibited.Contains(potential))
{
bool temp;
potential = DecrementAlphaNumericChar(potential, out temp);
if (potential == input)
{
throw new ArgumentException(
"A whole class of characters was prohibited",
"prohibited");
}
hadToWrap |= temp;
}
return potential;
}
string DecrementString(string input, List<char> prohibited)
{
char[] chrs = input.ToCharArray();
for (int i = chrs.Length - 1; i >= 0; i--)
{
bool wrapped;
chrs[i] = DecrementAvoidingProhibited(
chrs[i], prohibited, out wrapped);
if (!wrapped)
return new string(chrs);
}
return "-";
}
The only issue here is that it will reduce e.g. A10 to A09 not A9. I actually prefer this myself, but it should be simple to write a final pass that removes the extra zeroes.
For a little more performance, replace the List<char>s with Hashset<char>s, they should allow a faster Contains lookup.
I found solution to my own answer with some other workarounds.
The calling function:
MyFunction()
{
//stuff I do before
strValue = lstGetDecrName(strValue.ToList());//decrease value here
if (strValue.Contains('-'))
{
strValue = "-";
}
//stuff I do after
}
In all there are 4 functions. 2 Main functions and 2 helper functions.
List<char> lstGetDecrName(List<char> lstVal)//entry point, returns decreased value
{
if (lstVal.Contains('-'))
{
return "-".ToList();
}
List<char> lstTmp = lstVal;
subCheckEmpty(ref lstTmp);
switch (lstTmp.Count)
{
case 0:
lstTmp.Add('-');
return lstTmp;
case 1:
if (lstTmp[0] == '-')
{
return lstTmp;
}
break;
case 2:
if (lstTmp[1] == '0')
{
if (lstTmp[0] == '1')
{
lstTmp.Clear();
lstTmp.Add('9');
return lstTmp;
}
if (lstTmp[0] == 'A')
{
lstTmp.Clear();
lstTmp.Add('-');
return lstTmp;
}
}
if (lstTmp[1] == 'A')
{
if (lstTmp[0] == 'A')
{
lstTmp.Clear();
lstTmp.Add('Z');
return lstTmp;
}
}
break;
}
List<char> lstValue = new List<char>();
switch (lstTmp.Last())
{
case 'A':
lstValue = lstGetDecrTemp('Z', lstTmp, lstVal);
break;
case 'a':
lstValue = lstGetDecrTemp('z', lstTmp, lstVal);
break;
case '0':
lstValue = lstGetDecrTemp('9', lstTmp, lstVal);
break;
default:
char tmp = (char)(lstTmp.Last() - 1);
lstTmp.RemoveAt(lstTmp.Count - 1);
lstTmp.Add(tmp);
subCheckEmpty(ref lstTmp);
lstValue = lstTmp;
break;
}
lstGetDecrSkipValue(lstValue);
return lstValue;
}
List<char> lstGetDecrSkipValue(List<char> lstValue)
{
bool blnSkip = false;
foreach (char tmpChar in lstValue)
{
if (lstChars.Contains(tmpChar))
{
blnSkip = true;
break;
}
}
if (blnSkip)
{
lstValue = lstGetDecrName(lstValue);
}
return lstValue;
}
void subCheckEmpty(ref List<char> lstTmp)
{
bool blnFirst = true;
int i = -1;
foreach (char tmpChar in lstTmp)
{
if (char.IsDigit(tmpChar) && blnFirst)
{
i = tmpChar == '0' ? lstTmp.IndexOf(tmpChar) : -1;
if (tmpChar == '0')
{
i = lstTmp.IndexOf(tmpChar);
}
blnFirst = false;
}
}
if (!blnFirst && i != -1)
{
lstTmp.RemoveAt(i);
subCheckEmpty(ref lstTmp);
}
}
List<char> lstGetDecrTemp(char chrTemp, List<char> lstTmp, List<char> lstVal)//shifting places eg unit to ten,etc.
{
if (lstTmp.Count == 1)
{
lstTmp.Clear();
lstTmp.Add('-');
return lstTmp;
}
lstTmp.RemoveAt(lstTmp.Count - 1);
lstVal = lstGetDecrName(lstTmp);
lstVal.Insert(lstVal.Count, chrTemp);
subCheckEmpty(ref lstVal);
return lstVal;
}

how to dynamically generate a formula and solive it by selecting multiple rows using linq

hi guys i have an array called tblCeMaintMatrix.ToArray()) with a result of :
[0]: { xValue = 0, Operator = 43 '+' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
i made a foreach loop to solve this however i encountered some errors. I think i confused the logic for this..
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
value = operate((a.Operator).ToString(),a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal value)
{
Decimal Value = 0;
if (a == "+")
{
Value = value + value;
}
if (a == "-")
{
Value= value - value;
}
if (a == "*")
{
Value = value * value;
}
if (a == "/")
{
Value = value / value;
}
return Value;
}
my problem is that
a) what is does is this :
0 + 0 = 0
1 + 1 = 2
12 - 12 = 0
instead of 0 + 1 -12.
b) it doesnt retain the value.
how can i modify this to solve the problem? thanks
Non-tested code, I wish it's correct..
decimal result = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
result = operate((a.Operator).ToString(),a.xValue.Value,result);
}
}
private decimal operate(String a, Decimal value, Decimal result)
{
switch (a)
{
case "+": result += value; break;
case "-": result -= value; break;
case "*": result *= value; break;
case "/": result /= value; break;
default: result = value; break;
}
return result;
}
EDIT to ignore the first operator, I think you need to set your first operator to empty, like:
[0]: { xValue = 0, Operator = '' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
and see the modified Operate method.
Right now you are only passing a single value to your operate method, and using it as both operands. You need to also pass the running total of your code to the function:
Decimal total = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
total = operate((a.Operator).ToString(),total, a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal left, Decimal right)
{
Decimal Value = 0;
if (a == "+")
{
Value = left + right;
}
if (a == "-")
{
Value= left - right;
}
if (a == "*")
{
Value = left * right;
}
if (a == "/")
{
Value = left / right;
}
return Value;
}
It's not clear what's your using value2 to represent in your original function.

Categories

Resources