Same algorithm works once, errors the second - c#

Well this questions is probably gonna be closed before I get an answer... I am trying to program a very simple calculator and this works flawlessly:
private void button1_Click(object sender, EventArgs e)
{
string[] input = rtbInput.Text.Split(' ');
rtbInput.Text += " = " + CalculateNumber(input).ToString();
}
long CalculateNumber(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
//LOOK FOR PARENTHASIS, LAST INDEX, SEARCH FROM THERE UNTIL FIRST INDEX, RUN THIS AGAIN FOR THAT.
//THEN REPLACE "5 + (3 + 3)" with 5 + 6. So calculate 3 + 3 = 6 and replace ( until ) with answer.
if (rtbInput.Text.Contains("(") && rtbInput.Text.Contains(")"))
{
int c = 0;
int startNum;
int len;
string s = "No";
}
int i = 0;
while (i < (input.Length - 1))
{
switch (input[i])
{
case "+":
curValue += long.Parse(input[i + 1]);
break;
case "-":
curValue -= long.Parse(input[i + 1]);
break;
case "*":
curValue = curValue * long.Parse(input[i + 1]);
break;
case "/":
curValue = curValue / long.Parse(input[i + 1]);
break;
}
i++;
}
return curValue;
}
this works superbly. But when trying to add capability to calculate Parenthasis "(3 * 3) = 9" and i implement this code:
long CalculateNumber(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
//LOOK FOR PARENTHASIS, LAST INDEX, SEARCH FROM THERE UNTIL FIRST INDEX, RUN THIS AGAIN FOR THAT.
//THEN REPLACE "5 + (3 + 3)" with 5 + 6. So calculate 3 + 3 = 6 and replace ( until ) with answer.
if (rtbInput.Text.Contains("(") && rtbInput.Text.Contains(")"))
{
int c = 0;
int startNum;
int len;
string s = "No";
//while there are still parenthasis in the input, do this
if (c < rtbInput.Text.Split('(').Count() - 1) //REPLACE WITH WHILE
{
startNum = rtbInput.Text.LastIndexOf('(') + 1;
len = rtbInput.Text.IndexOf(')', startNum);// - startNum;
s = rtbInput.Text.Substring(startNum, len);
this.Name = s;
//NOW REPLACE THIS WITH THE RETURN OF CalculateParenthasis.Split(' ')
rtbInput.Text = rtbInput.Text.Replace("(" + s + ")", CalculateParenthasis(s.Split(' ')).ToString());
}
long CalculateParenthasis(string[] input)
{
long curValue = 0;
curValue = long.Parse(input[0]);
button1.Text += curValue.ToString();
int i = 0;
while (i < (input.Length - 1))
{
switch (input[i])
{
case "+":
curValue += long.Parse(input[i + 1]);
break;
case "-":
curValue -= long.Parse(input[i + 1]);
break;
case "*":
curValue = curValue * long.Parse(input[i + 1]);
break;
case "/":
curValue = curValue / long.Parse(input[i + 1]);
break;
}
i++;
}
return curValue;
}
As you can see the CalculateParenthasis() function works exactly the same as CalculateNumber() but takes the number between the parenthasis, but this errors at the switch statement saying the input string was the wrong format? WTH? I barely don't know how to even ask this question, seems like something tiny and easy being wrong but I just can't see it.

Based on my test, I reproduced the problem you meet.
However, I find it is very hard for us to complete it because of its complexity.
Therefore, I recommend that you use Reverse Poland algorithm to make the calculator.
I make a code example to make it and you can refer to it.
Code:
public class Example
{
public static Stack<string> operStack = new Stack<string>();
public static Stack<string> numStack = new Stack<string>();
static bool IsNumber(string s)
{
return Regex.IsMatch(s, #"\d+");
}
static bool IsSiZe(string s)
{
string ts = "+-*/";
return ts.IndexOf(s) > -1;
}
static int Level(string s)
{
int i = 0;
switch (s)
{
case ",":
i = 0;
break;
case "(":
case ")":
case "#":
i = 1;
break;
case "+":
case "-":
i = 2;
break;
case "*":
case "/":
i = 3;
break;
}
return i;
}
public static void Calc(Stack<string> numStack, Stack<string> operStack)
{
int rightnum = int.Parse(numStack.Pop());
int leftnum = int.Parse(numStack.Pop());
string oper = operStack.Pop();
switch (oper)
{
case "+":
numStack.Push((leftnum + rightnum).ToString());
break;
case "-":
numStack.Push((leftnum - rightnum).ToString());
break;
case "*":
numStack.Push((leftnum * rightnum).ToString());
break;
case "/":
numStack.Push((leftnum / rightnum).ToString());
break;
}
}
public static void ToNiBoLan(string exp)
{
operStack.Push("#"); //Push into the stack for comparsion
string token = "";
for (int i = 0; i < exp.Length; i++)
{
if (IsNumber(exp[i].ToString())) //If it is number
{
token += exp[i].ToString();
}
else if (exp[i].ToString() == "(")
{
operStack.Push(exp[i].ToString());
if (IsNumber(token))
numStack.Push(token);
token = "";
}
else if (IsSiZe(exp[i].ToString()))
{
if (IsNumber(token))
numStack.Push(token);
token = "";
int item = Level(exp[i].ToString()).CompareTo(Level(operStack.Peek())); //Comparison operator precedence
if (item > 0) //If the priority is higher than the top of the stack, the operator is pushed onto the stack
{
operStack.Push(exp[i].ToString());
}
else //If the operator is less than or equal to the top of the stack, calculate and push the operator onto the stack
{
Calc(numStack, operStack);
operStack.Push(exp[i].ToString());
}
}
else if (exp[i].ToString() == ")")
{
if (IsNumber(token))
numStack.Push(token);
token = "";
while (operStack.Peek() != "(")
{
Calc(numStack, operStack);
}
token = numStack.Pop(); //Take out the numbers for the next calculation
operStack.Pop(); //Eligible left parenthesis popped
}
else //End of traversal
{
if (IsNumber(token))
numStack.Push(token);
token = "";
while (numStack.Count > 1)
{
Calc(numStack, operStack);
}
}
}
}
}
Use it in winforms:
private void button1_Click(object sender, EventArgs e)
{
//For comparison, add "#" at the end of the expression
string text = richTextBox1.Text.Trim() + "#";
Example.ToNiBoLan(text);
richTextBox1.Text = Example.numStack.Pop().ToString();
}
Besides, you can refer to the link Reverse polish notation C# don't work correctly.

Related

Unhandled Exception: System.InvalidOperationException: Stack empty

I'm learning data structures so I'm trying to implement expression evaluation using stack in two steps (convert infix expression to postfix then use the result of it to evaluate postfix)
but I keep getting this error :
Unhandled Exception: System.InvalidOperationException: Stack empty.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Stack`1.Pop()
at DataStructures.StackArray.evaluatePostfix(String exp) in E:\visual studio c#\New folder\DataStructures\StackArray.cs:line 281
at DataStructures.Program.Main(String[] args) in E:\visual studio c#\New folder\DataStructures\Program.cs:line 71
I definitely miss something silly for some reason so I'll appreciate any advice.
public static string infixToPostfix(string exp)
{
var postFix = "";
Stack<char> Stack = new Stack<char>();
for(int i = 0; i < exp.Length; ++i)
{
char x = exp[i];
// If the scanned character is an operand, add it to output.
if (char.IsLetterOrDigit(x))
{
postFix += x;
}
//parentheses part
else if (x == '(')
{
Stack.Push(x);
}
else if (x == ')')
{
while (Stack.Count>0 && Stack.Peek() != '(')
{
postFix += Stack.Pop();
}
if(Stack.Peek() == '(')
{
Stack.Pop();
}
}
else
{
while (Stack.Count > 0 && x <= Precedence(Stack.Peek()))
{
postFix += Stack.Pop();
}
Stack.Push(x);
}
}
//pop the remain of stack
while(Stack.Count > 0)
{
postFix += Stack.Pop();
}
return postFix;
}
/////////////////////////////////////////////////////
public static int evaluatePostfix(string exp)
{
Stack<int> Stack = new Stack<int>();
for(int i = 0; i < exp.Length; i++)
{
char x = exp[i];
//if "x" whitespace
if (x == ' ')
{
//skip it
continue;
}
else if (char.IsDigit(x))
{
//create new variable to store the extracted numbers in it
int num = 0;
while (char.IsDigit(x))
{
num = num * 10 + (int)(x - '0');
i++;
x = exp[i];
}
i--;
Stack.Push(num);
}
else
{
//create two vaiables to present the two elements
int v1 = Stack.Pop();
int v2 = Stack.Pop();
// Perform arithmetic operations between 2 operands
switch (x)
{
case '+':
Stack.Push(v2 + v1);
break;
case '-':
Stack.Push(v2 - v1);
break;
case '/':
Stack.Push(v2 / v1);
break;
case '*':
Stack.Push(v2 * v1);
break;
}
}
}
return Stack.Pop();
}
main method:
static void Main(string[] args)
{
var infix = Console.ReadLine();
string postFix;
var r = StackArray.infixToPostfix(infix);
Console.WriteLine($"postfix is {r}");
//evaluate postfiix
int x = StackArray.evaluatePostfix(r);
Console.WriteLine($"result is {x}");
}

Is it possible to escape Json string using System.Text.Json [duplicate]

Are there any classes/functions available to be used for easy JSON escaping? I'd rather not have to write my own.
I use System.Web.HttpUtility.JavaScriptStringEncode
string quoted = HttpUtility.JavaScriptStringEncode(input);
For those using the very popular Json.Net project from Newtonsoft the task is trivial:
using Newtonsoft.Json;
....
var s = JsonConvert.ToString(#"a\b");
Console.WriteLine(s);
....
This code prints:
"a\\b"
That is, the resulting string value contains the quotes as well as the escaped backslash.
Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:
static string EscapeForJson(string s) {
string quoted = System.Web.Helpers.Json.Encode(s);
return quoted.Substring(1, quoted.Length - 2);
}
The Substring call is required, since Encode automatically surrounds strings with double quotes.
Yep, just add the following function to your Utils class or something:
public static string cleanForJSON(string s)
{
if (s == null || s.Length == 0) {
return "";
}
char c = '\0';
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
String t;
for (i = 0; i < len; i += 1) {
c = s[i];
switch (c) {
case '\\':
case '"':
sb.Append('\\');
sb.Append(c);
break;
case '/':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
if (c < ' ') {
t = "000" + String.Format("X", c);
sb.Append("\\u" + t.Substring(t.Length - 4));
} else {
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
I have used following code to escape the string value for json.
You need to add your '"' to the output of the following code:
public static string EscapeStringValue(string value)
{
const char BACK_SLASH = '\\';
const char SLASH = '/';
const char DBL_QUOTE = '"';
var output = new StringBuilder(value.Length);
foreach (char c in value)
{
switch (c)
{
case SLASH:
output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);
break;
case BACK_SLASH:
output.AppendFormat("{0}{0}", BACK_SLASH);
break;
case DBL_QUOTE:
output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE);
break;
default:
output.Append(c);
break;
}
}
return output.ToString();
}
In .Net Core 3+ and .Net 5+:
string escapedJsonString = JsonEncodedText.Encode(jsonString);
The methods offered here are faulty.
Why venture that far when you could just use System.Web.HttpUtility.JavaScriptEncode ?
If you're on a lower framework, you can just copy paste it from mono
Courtesy of the mono-project #
https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
if (string.IsNullOrEmpty(value))
return addDoubleQuotes ? "\"\"" : string.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
{
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new System.Text.StringBuilder();
if (addDoubleQuotes)
sb.Append('"');
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat("\\u{0:x4}", (int)c);
else switch ((int)c)
{
case 8:
sb.Append("\\b");
break;
case 9:
sb.Append("\\t");
break;
case 10:
sb.Append("\\n");
break;
case 12:
sb.Append("\\f");
break;
case 13:
sb.Append("\\r");
break;
case 34:
sb.Append("\\\"");
break;
case 92:
sb.Append("\\\\");
break;
default:
sb.Append(c);
break;
}
}
if (addDoubleQuotes)
sb.Append('"');
return sb.ToString();
}
This can be compacted into
// https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{
private static bool NeedEscape(string src, int i)
{
char c = src[i];
return c < 32 || c == '"' || c == '\\'
// Broken lead surrogate
|| (c >= '\uD800' && c <= '\uDBFF' &&
(i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
// Broken tail surrogate
|| (c >= '\uDC00' && c <= '\uDFFF' &&
(i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
// To produce valid JavaScript
|| c == '\u2028' || c == '\u2029'
// Escape "</" for <script> tags
|| (c == '/' && i > 0 && src[i - 1] == '<');
}
public static string EscapeString(string src)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
int start = 0;
for (int i = 0; i < src.Length; i++)
if (NeedEscape(src, i))
{
sb.Append(src, start, i - start);
switch (src[i])
{
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
default:
sb.Append("\\u");
sb.Append(((int)src[i]).ToString("x04"));
break;
}
start = i + 1;
}
sb.Append(src, start, src.Length - start);
return sb.ToString();
}
}
I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's code won by a good bit, presumably because the others are taking into account serialization options. Here are my results:
Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms
\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms
And here is the test code:
public static void Main(string[] args)
{
var testStr1 = "Apple Banana";
var testStr2 = #"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";
foreach (var testStr in new[] { testStr1, testStr2 })
{
var results = new Dictionary<string,List<long>>();
for (var n = 0; n < 10; n++)
{
var count = 1000 * 1000;
var sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
}
var t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.Helpers.Json.Encode(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = cleanForJSON(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Clive Paterson").Add(t);
}
Console.WriteLine(testStr);
foreach (var result in results)
{
Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
}
Console.WriteLine();
}
Console.ReadLine();
}
I would also recommend using the JSON.NET library mentioned, but if you have to escape unicode characters (e.g. \uXXXX format) in the resulting JSON string, you may have to do it yourself. Take a look at Converting Unicode strings to escaped ascii string for an example.
I nice one-liner, used JsonConvert as others have but added substring to remove the added quotes and backslash.
var escapedJsonString = JsonConvert.ToString(JsonString).Substring(1, JsonString.Length - 2);
What about System.Web.Helpers.Json.Encode(...) (see http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx)?
String.Format("X", c);
That just outputs: X
Try this instead:
string t = ((int)c).ToString("X");
sb.Append("\\u" + t.PadLeft(4, '0'));
There's a Json library at Codeplex
I chose to use System.Web.Script.Serialization.JavaScriptSerializer.
I have a small static helper class defined as follows:
internal static partial class Serialization
{
static JavaScriptSerializer serializer;
static Serialization()
{
serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
}
public static string ToJSON<T>(T obj)
{
return serializer.Serialize(obj);
}
public static T FromJSON<T>(string data)
{
if (Common.IsEmpty(data))
return default(T);
else
return serializer.Deserialize<T>(data);
}
}
To serialize anything I just call Serialization.ToJSON(itemToSerialize)
To deserialize I just call Serialization.FromJSON<T>(jsonValueOfTypeT)

I am trying to figure out how to convert roman numerals into integers

I am trying to figure out how to convert roman numerals to integers. This is a portion of my code. When I prompt the user to enter M it shows 1000, but when I prompt the user to enter a roman numeral such as VM, it does not give me 995 but instead 1005. This is because I am telling my program to do just that.
What I am trying to figure out is how I can look ahead and get it to know when it is adding or subtracting roman numerals.
How do I begin to go about doing this?
class Roman
{
public int inprogress = 0;
public Roman(string roman)
{
char temp = 'Z';
int length;
length = roman.Length;
for (int i = 0; i < length; i++)
{
temp = roman[i];
if (temp == 'M')
{
inprogress = inprogress + 1000;
}
if (temp == 'D')
{
inprogress = inprogress + 500;
}
if (temp == 'C')
{
inprogress = inprogress + 100;
}
if (temp == 'L')
{
inprogress = inprogress + 50;
}
if (temp == 'X')
{
inprogress = inprogress + 10;
}
if (temp == 'V')
{
inprogress = inprogress + 5;
}
if (temp == 'I')
{
inprogress = inprogress + 1;
}
}
}
}
the trick to converting roman numerals is to work backwards (from the end of the string) not forwards, makes it a lot easier.
eg, if you have IX
you start with X, = 10
move back 1.... now its I, I is less than X so now subtract off 1 = 9
A reference solution....
public class RomanNumeral
{
public static int ToInt(string s)
{
var last = 0;
return s.Reverse().Select(NumeralValue).Sum(v =>
{
var r = (v >= last)? v : -v;
last = v;
return r;
});
}
private static int NumeralValue(char c)
{
switch (c)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return 0;
}
}
NOTE: this doesn't validate roman numerals, just convert ones that are already valid.
List<Level> levels = new List<Level>();
int[] val = new int[255];
private void Form1_Load(object sender, EventArgs e)
{
val[(byte)'I'] = 1;
val[(byte)'V'] = 5;
val[(byte)'X'] = 10;
val[(byte)'L'] = 50;
val[(byte)'C'] = 100;
val[(byte)'D'] = 500;
val[(byte)'M'] = 1000;
levels.Clear();
levels.Add(new Level('I', 'V', 'X'));
levels.Add(new Level('X', 'L', 'C'));
levels.Add(new Level('C', 'D', 'M'));
}
int fromRoman(string n)
{
n = n.ToUpper();
var result = 0;
var lastDigit = 0;
for (var pos = n.Length - 1; pos >= 0; pos--)
{
var curDigit = val[(byte)n[pos]];
if (curDigit >= lastDigit)
result += curDigit;
else
result -= curDigit;
lastDigit = curDigit;
}
return result;
}
public class Level
{
public Level(char i, char v, char x)
{
this.i = i;
this.x = x;
this.v = v;
}
public char i;
public char v;
public char x;
}
Then Run
int Result = fromRoman("X");
You need to add logic that basically says that if the V is before the M then subtract it. Based on this line here:
if (temp == 'V')
{
inprogress = inprogress + 5;

Tic-Tac-Toe programming

I'm trying to create a program for homework that displays a Tic-Tac-Toe board, and when the user clicks the button it displays a random number in all of the boxes. The number 1 = "X" and 0 = "O". I created 9 labels labeled "label1, label2...etc". Once the labels are full, I need to display who won, the letter X or O. I'm using arrays for this but am kinda of lost at this point. what do I need to do to display the random numbers into the labels. Here is the code I've written for the click event handler so far.
Random rand = new Random(2);
int click;
click = rand.Next(2);
const int ROWS = 3;
const int COLS = 3;
int[,] letters = new int[ROWS,COLS];
int ROW = ROWS;
int COL = COLS;
for (int row = 0; row < ROWS; ROW ++) {
for (int col = 0; col < COLS; COL ++) {
letters[row, col] = rand.Next(2);
int X = 1;//???
int O = 0;//???
label1.Text = [ROW,COL].ToString();//???
}
}
Here an attempt at an explanation:
first, you have the data to represent your problem:
const int ROWCOUNT = 3;
const int COLCOUNT = 3;
private int[,] letters = new int[ROWCOUNT,COLCOUNT];
Random rand = new Random(DateTime.Now.Ticks);
then you want to randomly fill that data:
private void randomize()
{
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
letters[row,col] = rand.nextInt(2);
}
}
}
finally, you want to display the array somewhere (in your case labels):
//These need to be added to a GridLayoutManager
private JLabel[,] labels = new JLabel[ROWCOUNT,COLCOUNT];
private void updateView(){
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
var current = letters[row,col];
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
}
}
}
so, when the user clicks the button, you call:
randomize();
updateView();
hope it helps
from your comments, it seems setting the Label Text needs more explanation:
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
maybe, i should have written it more like this:
String textForLabel = "O"; //0 represents O, 1 represents X
//test to see, if it really is a 0, not a 1
if( current != 0 ){
//oh, it is not a zero, therefore, set
textForLabel = "X";
}
JLabel labelAtRowAndCol = labels[row,col];
labelAtRowAndCol.Text = textForLabel;
I refuse to provide you the exact answer since you learning how to dot his is the entire point of this excerise.
Before I started the game I would randomly choose the first move: X or O.
I would then do the following:
1) I would place all the Labels into a collection.
2) I would randomly choose one of the Labels within the collection and change the Text property.
3) I would then remove the same Label from the collection
4) Rinse and Repeat.
You DO NOT need a two diminsional array for this.
In order to figure out the winner...I would keep track of the moves of each player. There is only a static number of winning moves in this game. Would be a simple task to determine if there were three X's in the top row or not.
#include<iostream>
#include<iomanip>
#include<set>
using namespace std;
char s[3][3] = {{'*','*','*'},{'*','*','*'},{'*','*','*'}};
void show(char os[3][3]);
int def[9];
void changeo(int n);
void changex(int n);
int stop();
set<int> cset;
int search (int n){
}
int main(){
int n; show(s);
int ss = 2;
cout<<endl;
while (stop()){
if (ss%2==0){
cout<<"player One(O) : enter n "; cin>>n;
if (!cset.count(n) && n<10){
cset.insert(n);
changeo(n);
show(s);
ss++;
}
else{
cout<<"invalid move"<<endl;
}
}
else{
cout<<"player Two(X) : enter n "; cin>>n;
if (!cset.count(n)&& n<10){
cset.insert(n);
changex(n);
show(s);
ss++;
}
}
}
cout<<"\nyou can see the winner"<<endl;
cout<<"your moves are "<<ss;
return 0;
}
void show(char s[3][3]){
cout<< setw(7)<< "1: " <<s[0][0]<<setw(5)<<"2: " <<s[0][1]<<setw(5)<<"3: " <<s[0][2]<<endl;
cout<< setw(7)<< "4: " <<s[1][0]<<setw(5)<<"5: " <<s[1][1]<<setw(5)<<"6: " <<s[1][2]<<endl;
cout<< setw(7)<< "7: " <<s[2][0]<<setw(5)<<"8: " <<s[2][1]<<setw(5)<<"9: " <<s[2][2]<<endl;
cout<<endl;
}
void changeo(int n){
switch(n){
case 1:
s[0][0] = 'O';
break;
case 2:
s[0][1] = 'O';
break;
case 3:
s[0][2] = 'O';
break;
case 4:
s[1][0] = 'O';
break;
case 5:
s[1][1] = 'O';
break;
case 6:
s[1][2] = 'O';
break;
case 7:
s[2][0] = 'O';
break;
case 8:
s[2][1] = 'O';
break;
case 9:
s[2][2] = 'O';
break;
}
}
void changex(int n){
switch(n){
case 1:
s[0][0] = 'X';
break;
case 2:
s[0][1] = 'X';
break;
case 3:
s[0][2] = 'X';
break;
case 4:
s[1][0] = 'X';
break;
case 5:
s[1][1] = 'X';
break;
case 6:
s[1][2] = 'X';
break;
case 7:
s[2][0] = 'X';
break;
case 8:
s[2][1] = 'X';
break;
case 9:
s[2][2] = 'X';
break;
}
}
int stop(){
int m=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if(s[i][j]=='*'){
m=1;
break;
}
}
}
return m;
}

What is the name of the function, which does the opposite to HttpUtility.JavaScriptStringEncode?

I need to evaluate escape sequences on the string.
To escape the string, HttpUtility.JavaScriptStringEncode or something similar was used.
How do I do the opposite transformation?
Here's an example:
var s = #"otehu""oeuhnoa
oaehu
oatehu
oeu";
var t = HttpUtility.JavaScriptStringEncode(s);
var n = Decode(t);
i need such function Decode, which would make n == s;
here is my implementation, for those who are looking for it
private string JavaScriptStringDecode(string value, bool removeDoubleQuotes)
{
StringBuilder b = new StringBuilder();
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++)
{
var c = value[i];
if (c == '\\')
{
if (count > 0)
{
b.Append(value, startIndex, count);
count = 0;
}
if (i < value.Length - 1)
{
var c1 = value[i + 1];
bool ignore = false;
char charToAppend;
switch (c1)
{
case 'r':
charToAppend = '\r';
break;
case 't':
charToAppend = '\t';
break;
case 'n':
charToAppend = '\n';
break;
case 'b':
charToAppend = '\b';
break;
case 'f':
charToAppend = '\f';
break;
case '\\':
charToAppend = '\\';
break;
case '\'':
charToAppend = '\'';
break;
case '\"':
charToAppend = '\"';
break;
case 'u':
case 'U':
if (i < value.Length - 5)
{
var style = NumberStyles.HexNumber;
var cult = CultureInfo.InvariantCulture;
int u;
if (Int32.TryParse(value.Substring(i + 2, 4), style, cult, out u))
{
charToAppend = ((char)u);
i += 4;
break;
}
}
charToAppend = '\\';
ignore = true;
break;
default:
charToAppend = '\\';
ignore = true;
break;
}
if (!ignore)
{
i++;
}
startIndex = i + 1;
b.Append(charToAppend);
continue;
}
}
count++;
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
if (removeDoubleQuotes)
{
if (b.Length > 0)
{
if (b[0] == '"')
{
b.Remove(0, 1);
}
if (b[b.Length - 1] == '"')
{
b.Remove(b.Length - 1, 1);
}
}
}
return b.ToString();
}
I found this function posted on another forum:
public static string JavaScriptStringDecode(string source)
{
// Replace some chars.
var decoded = source.Replace(#"\'", "'")
.Replace(#"\""", #"""")
.Replace(#"\/", "/")
.Replace(#"\\", #"\")
.Replace(#"\t", "\t")
.Replace(#"\n", "\n");
// Replace unicode escaped text.
var rx = new Regex(#"\\[uU]([0-9A-F]{4})");
decoded = rx.Replace(decoded, match => ((char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber))
.ToString(CultureInfo.InvariantCulture));
return decoded;
}
And it worked for me
Here is my full implementation that based on #GDocal's code and String - JavaScript | MDN documentation.
private string JavaScriptStringDecode(string value, bool removeDoubleQuotes)
{
StringBuilder b = new StringBuilder();
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++)
{
var c = value[i];
if (c == '\\')
{
if (count > 0)
{
b.Append(value, startIndex, count);
count = 0;
}
if (i < value.Length - 1)
{
var c1 = value[i + 1];
bool ignore = false;
char charToAppend;
var style = NumberStyles.HexNumber;
var cult = CultureInfo.InvariantCulture;
int u;
switch (c1)
{
case '\'':
charToAppend = '\'';
break;
case '\"':
charToAppend = '\"';
break;
case '\\':
charToAppend = '\\';
break;
case 'n':
charToAppend = '\n';
break;
case 'r':
charToAppend = '\r';
break;
case 'v':
charToAppend = '\v';
break;
case 't':
charToAppend = '\t';
break;
case 'b':
charToAppend = '\b';
break;
case 'f':
charToAppend = '\f';
break;
case 'u':
if (value[i + 2] == '{')
{
if (value[i + 4] == '}' && Int32.TryParse(value.Substring(i + 3, 1), style, cult, out u))
{
charToAppend = ((char)u);
i += 5;
break;
}
else if (value[i + 5] == '}' && Int32.TryParse(value.Substring(i + 3, 2), style, cult, out u))
{
charToAppend = ((char)u);
i += 6;
break;
}
else if (value[i + 6] == '}' && Int32.TryParse(value.Substring(i + 3, 3), style, cult, out u))
{
charToAppend = ((char)u);
i += 7;
break;
}
else if (value[i + 7] == '}' && Int32.TryParse(value.Substring(i + 3, 4), style, cult, out u))
{
charToAppend = ((char)u);
i += 8;
break;
}
else if (value[i + 8] == '}' && Int32.TryParse(value.Substring(i + 3, 5), style, cult, out u))
{
charToAppend = ((char)u);
i += 9;
break;
}
else if (value[i + 9] == '}' && Int32.TryParse(value.Substring(i + 3, 6), style, cult, out u))
{
charToAppend = ((char)u);
i += 10;
break;
}
else
{
// Syntax Error
throw new FormatException(#"The Unicode code point should be \u{X} ~ \u{XXXXXX}.");
}
}
else
{
if (i < value.Length - 5)
{
if (Int32.TryParse(value.Substring(i + 2, 4), style, cult, out u))
{
charToAppend = ((char)u);
i += 4;
break;
}
}
}
charToAppend = '\\';
ignore = true;
break;
case 'x':
if (i < value.Length - 3)
{
if (Int32.TryParse(value.Substring(i + 2, 2), style, cult, out u))
{
charToAppend = ((char)u);
i += 2;
break;
}
}
charToAppend = '\\';
ignore = true;
break;
default:
charToAppend = '\\';
ignore = true;
break;
}
if (!ignore)
{
i++;
}
startIndex = i + 1;
b.Append(charToAppend);
continue;
}
}
count++;
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
if (removeDoubleQuotes)
{
if (b.Length > 0)
{
if (b[0] == '"')
{
b.Remove(0, 1);
}
if (b[b.Length - 1] == '"')
{
b.Remove(b.Length - 1, 1);
}
}
}
return b.ToString();
}

Categories

Resources