Why Is This Code Running Longer Character Combinations Than Necessary? - c#

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}

Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Related

Determine whether each character in the first string can be uniquely replaced by a character in the second string so that the two strings are equal

Give two strings of equal size. Determine whether each character in the first string can be uniquely replaced by a character in the second string so that the two strings are equal. Display also the corresponding character pairs between the two strings. The code works well now.
Example 1:
For input data:
aab
ttd
The console will display:
True
a => t
b => d
Example 2:
For input data:
tab
ttd
The console will display:
False
In the second example the answer is false because there is no unique correspondence for the character 'a': both 't' and 'd' correspond to it.
This is my code:
using System;
namespace problemeJM
{
class Program
{
static void Main(string[] args)
{
string firstPhrase = Convert.ToString(Console.ReadLine());
string secondPhrase = Convert.ToString(Console.ReadLine());
string aux1 = string.Empty, aux2 = string.Empty;
bool x = true;
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
if (aux1.Length != aux2.Length)
{
Console.WriteLine("False");
}
else
{
for (int i = 0; i < firstPhrase.Length - 2; i++)
{
for (int j = 1; j < secondPhrase.Length - 1; j++)
{
if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = false;
break;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = false;
break;
}
}
}
Console.WriteLine(x);
aux1 = string.Empty;
aux2 = string.Empty;
if (x == true)
{
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
for (int i = 0; i <= aux1.Length - 1; i++)
{
for (int j = 1; j <= aux2.Length; j++)
{
if (aux1[i] == aux1[j] && aux2[i] == aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
else if (aux1[i] != aux1[j] && aux2[i] != aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
}
}
}
}
}
}
}
I think you should use a Dictionary<char, char> as commented. But you need to check if there's a unique mapping in both string, so from s1 to s2 and from s2 to s1:
static bool UniqueMapping(string s1, string s2)
{
int length = Math.Min(s1.Length, s2.Length);
var dict = new Dictionary<char, char>(length);
for (int i = 0; i < length; i++)
{
char c1 = s1[i];
char c2 = s2[i];
bool contained = dict.TryGetValue(c1, out char c);
if (contained && c2 != c)
{
return false;
}
dict[c1] = c2;
}
return true;
}
Here are your samples. Note that i use UniqueMapping twice(if true after 1st):
static void Main(string[] args)
{
var items = new List<string[]> { new[]{ "aab", "ttd" }, new[] { "tab", "ttd" }, new[] { "ala bala portocala", "cuc dcuc efghficuc" }, new[] { "ala bala portocala", "cuc dcuc efghijcuc" } };
foreach (string[] item in items)
{
bool result = UniqueMapping(item[0], item[1]);
if(result) result = UniqueMapping(item[1], item[0]);
Console.WriteLine($"Word 1 <{item[0]}> Word 2 <{item[1]}> UniqueMapping? {result}");
}
}
.NET Fiddle: https://dotnetfiddle.net/4DtIyH

Multiplication and Sum in GridView ASP.Net C#

I have a datatable which is bound to GridView datasource as follows.
Overall i want to Multiply 'Quantity' column value with 'Part1 qty' column value until 'column5' cell value is repeating and so on
the result of operation should appear underneath the value as highlighted in red for understanding
My GridView data currently
I want the following output
Required Output
My GridMarkup
My GridMarkup
What I have done so far is
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax=columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult=0;
int counter = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
counter++;
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity= GridView1.Rows[i-1].Cells[1].Text;
var PreviousGLQuantity= GridView1.Rows[i-1].Cells[result].Text;
//var Quantity = dt.Rows[i].ItemArray[1];
//var GLQuantity = dt.Rows[i].ItemArray[Convert.ToInt64(result)].ToString();
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
MultiplicationResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ) + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
GridView1.Rows[i].Cells[j].Text = o.ToString();
GridView1.Rows[i].Cells[j].Text.Replace("\n", "<br/>");
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}
Thanks in advance.
We can use below Answer
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax = columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult = 0;
decimal currentCellResult = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
var defaultvalue = row.Cells[j].Text.ToString();
var defaultvalueArray = defaultvalue.Split(' ');
var originalMultiplicationResult = defaultvalueArray.Count() == 2 ? defaultvalueArray.Last() : "0";
var originalCellValue = defaultvalueArray.Count() == 2 ? defaultvalueArray.First() : row.Cells[j].Text.ToString();
if (originalCellValue == previousRow.Cells[j].Text)
{
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity = GridView1.Rows[i - 1].Cells[1].Text;
var PreviousGLQuantity = GridView1.Rows[i - 1].Cells[result].Text;
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
currentCellResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ);
MultiplicationResult = currentCellResult + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
if (row.Cells[j].RowSpan == 0)
{
//DataTable dt = (DataTable)ViewState["dt"];
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text = previousRow.Cells[j].Text.Split("");
}
else
{
//DataTable dt = (DataTable)ViewState["dt"];
var t = Convert.ToDecimal(originalMultiplicationResult) - Convert.ToDecimal(currentCellResult) + MultiplicationResult;
object o = dt.Rows[i].ItemArray[j] + " " + t.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text.Replace("\n", "<br>");
}
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}

C# Calculator "Input string was not in a correct format" on every operation except addition

I tried to create a small calculator and everything worked just fine. I could do every operation without an error. Then I tried to improve some things and add some.
Out of a sudden the original Part does not work anymore and i get the Error:[ System.FormatException: "Input string was not in a correct format." ] every time i try to substract, multiply or divide.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator_V2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
answer.Text = Calculate(textBox.Text);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
public string Calculate(string text)
{
double finalAnswer = AddAndSubstract(text);
return finalAnswer.ToString();
}
public double AddAndSubstract(string text1)
{
string[] text = text1.Split('-');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('+') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('+');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "+");
}
}
}
}
double total;
if (textList[0].Contains("*") || textList[0].Contains("/"))
{
total = DivideAndMultiply(textList[0]);
return total;
}
else
{
total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "-")
{
total = total - DivideAndMultiply(textList[i]);
}
else if (textList[i - 1] == "+")
{
total = total + DivideAndMultiply(textList[i]);
}
}
return total;
}
}
public double DivideAndMultiply(string text1)
{
string[] text = text1.Split('*');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("*");
}
textList.Add("*");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('/') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('/');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "/");
}
}
}
}
double total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "/")
{
total = total / Convert.ToDouble(textList[i]);
}
else if (textList[i - 1] == "*")
{
total = total * Convert.ToDouble(textList[i]);
}
}
return total;
}
private void Button_Click_C(object sender, RoutedEventArgs e)
{
double finalAnswer = 0;
answer.Text = "";
textBox.Text = "";
}
private void Button_Click_zahl(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
private void Button_Click_equals(object sender, RoutedEventArgs e)
{
answer.Text = RemoveBrackets(textBox.Text);
}
public string RemoveBrackets(string text)
{
while (text.Contains('(') && text.Contains(')'))
{
int openIndex = 0;
int closeIndex = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '(')
{
openIndex = i;
}
if (text[i] == ')')
{
closeIndex = i;
text = text.Remove(openIndex,closeIndex-openIndex +1).Insert(openIndex,ResolveBrackets(openIndex, closeIndex, text));
break;
}
}
}
for (int i = 1; i < text.Length; i++)
{
if (text[i] == '-' && (text[i]-1=='*' || text[i] - 1 == '/'))
{
for (int j=i-1; j>=0; j++)
{
if (text[j] == '+')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '-';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
else if (text[j] == '-')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '+';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
}
}
}
if (text[0] == '-') //für Fehler wenn - als erste Ziffer
{
text = '0' + text;
}
return Calculate(text);
}
public string ResolveBrackets(int openIndex, int closeIndex, string text)
{
string bracketAnswer = Calculate(text.Substring(openIndex +1, closeIndex -1));
return bracketAnswer;
}
}
}
Because you probably add the minus character twice
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
Then, when you loop in step of 2
for (int i = 2; i < textList.Count; i += 2)
You don't have [number] [sign] [number] [sign] anymore.
I suggest you look and the items in your list to see the problem. I would also suggest that you split your logic into smaller methods that could individually be tested.
i think the problem is your use of
double total = Convert.ToDouble(textList[0]);
in DivideAndMultiply
First of all it's best practice to test if the string is null or empty using String.IsNullOrEmpty(textList[0]); and use Double.TryParse instead of convert.

How to count the a specific value on a multidimensional array c#(Unity)

I'm having trouble on counting the number of my TIE value in my list
here is my code :
string[,] table = new string[104, 15];
int xIndex = 0;
int yIndex = 0;
for (int i = 0; i < list.Count; i++)
{
newString[0] += list[i].r;
newString[0] += ",";
}
string[] newChars = newString[0].Split(',');
string result = ""; // variable for the substring
string previousValue_ = ""; // store here the newprevious value without the T
int counterForTie = 0;
int counterForRow = 1;
int justMoveToY = 1;
foreach (string previousValue in newChars)
{
//check the length so that it wont throw an error
if (previousValue.Length > 1)
{
//get only the first letter of value P,B,T
result = previousValue.Substring(0, 1);
}
else
{
result = "";
}
if (table.GetLength(0) < xIndex)
{
break;
}
if (result.Equals(newPreviousValue) || result.Equals("T") && yIndex < table.GetLength(1))
{
if (counterForRow == 1)
{
yIndex = 0;
table[xIndex, yIndex] = result;
counterForRow++;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
}
else if (result.Equals(newPreviousValue) && previousValue.Equals("T") && yIndex < table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
if (justMoveToY == 1 && counterForRow == 1)
{
xIndex = 0;
yIndex = 0;
table[xIndex, yIndex] = result;
justMoveToY++;
counterForRow++;
}
else if (justMoveToY == 1)
{
xIndex = 0;
yIndex += 1;
table[xIndex, yIndex] = result;
justMoveToY++;
}
else {
if (firstDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieSecondTime = 0;
if (counterForTieSecondTime == 0)
{
secondDragonTail = true;
firstDragonTail = false;
}
else
{
secondDragonTail = false;
}
}
else if (secondDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieThirdTime = 0;
if (counterForTieThirdTime == 0)
{
thirdDragonTail = true;
secondDragonTail = false;
}
else
{
thirdDragonTail = false;
}
}
else
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTie = 0;
}
}
}
previousValue_ = result;
if (!result.Equals("T"))
{
newPreviousValue = previousValue_;
}
}
My problem here is that i couldn't count separately all the TIE value . All i want just to count the TIE value on every column .
For example like this image
As you can see on the image above i want to know if the TIE value is on the PLAYER value(blue) / BANKER value(red) and count the TIE value if how many is it on the Player column and vice versa.
I tried this
//count tie in a row
if (result.Equals("T") && result.Equals("P"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER :" + tieCounterPlayer);
}
else if(result.Equals("T") && result.Equals("B"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER :" + tieCounterBanker);
}
But unfortunately it didn't work.
Sorry for asking
This is what i did.
if (newPreviousValue.Contains("B"))
{
if (result.Equals("T"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER : " + tieCounterBanker);
}
else
{
tieCounterBanker = 0;
}
}
else if(newPreviousValue.Contains("P"))
{
if (result.Equals("T"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER : " + tieCounterPlayer);
}
else
{
tieCounterPlayer = 0;
}
}

Datagridview cell tooltip word wrap

I have a datagridview which have very long string in one column. When I hover mouse over it the default, one line, tooltip is not enough to display whole content. Any ideas how to word wrap text in datagridview tooltip?
Try this example:
private void dgvProducts_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if ((e.ColumnIndex == dgvProducts.Columns["colDescription"].Index) && e.Value != null)
{
DataGridViewCell cell = dgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.ToolTipText = String.Join(Environment.NewLine, e.Value.ToString().DivideLongString());
}
}
//-------------- Extension Methods ------------- C# 6.0
using static System.String;
public static class Extensions
{
public static string[] DivideLongString(this string text, int length = 10)
{
if (text.Length <= length) return new[] { text };
var words = text.GetTotalWords();
var output = new string[(words.Length % length > 1 ? words.Length / length + 1 : words.Length % length < 1 ? words.Length / length - 1 : words.Length / length) + 100];
var oIndex = 0;
var wIndex = length - 1;
try
{
for (var i = 0; i < words.Length; i++)
{
if (wIndex < i)
{
wIndex += length - 1;
oIndex++;
}
output[oIndex] += $"{words[i]} ";
}
if (output.Length > 2 && !IsNullOrEmpty(output[output.Length - 1]) && output[output.Length - 1].CountWords() < 3)
{
output[output.Length - 2] += output[output.Length - 1];
output[output.Length - 1] = Empty;
}
return output.Where(val => !IsNullOrEmpty(val)).ToArray();
}
catch (Exception ex)
{
ExceptionLogger.Log(ex);
return output.Where(val => !IsNullOrEmpty(val)).ToArray();
}
}
public static string ReplaceMultipleSpacesWith(this string text, string newString)
{
return Regex.Replace(text, #"\s+", newString);
}
public static string[] GetTotalWords(this string text)
{
text = text.Trim().ReplaceMultipleSpacesWith(" ");
var words = text.Split(' ');
return words;
}
}
Try this - it works for me:
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
int wrapLen = 84;
if ((e.RowIndex >= 0) && e.ColumnIndex >= 0)
{
DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
string cellText = cell.Value.ToString();
if (cellText.Length >= wrapLen)
{
cell.ToolTipText = "";
int n = cellText.Length / wrapLen;
for (int i = 0; i <= n; i++)
{
int wStart = wrapLen * i;
int wEnd = wrapLen * (i + 1);
if (wEnd >= cellText.Length)
wEnd = cellText.Length;
cell.ToolTipText += cellText.Substring(wStart, wEnd - wStart) + "\n";
}
}
}
}

Categories