Set two values in one matrix - c#

Is it possible to set two values in one for loop? I would like to create a string matrix [,], the first element (i) is variable, the second (j) is constant
int rowRun = 1;
string[,] costume = new string [elementsOfRunning, rowRun];
int columnRun = costume.GetLength(0);
for (int i = 0; i < columnRun; i++)
{
int rowOfRunning;
do
{
Console.WriteLine("Row of running (0-42)");
rowOfRunning = int.Parse(Console.ReadLine());
}
while (!(0 <= rowOfRunning && rowOfRunning <= 42));
string rowOfRunning2 = rowOfRunning.ToString();
}
And here I would like to set the i value for example: costume[i,j] = rowOfRunning; But I can't in this way.
for (int j = 0; j < rowRun; j++)
{
string comment = "";
do
{
Console.WriteLine("Write a comment: („verseny”, „terep”, „laza”, „fartlek”, „résztáv”");
comment = Console.ReadLine();
}
while (!comment.Contains(",") && comment != "verseny" && comment != "terep" && comment != "laza" && comment != "fartlek" && comment != "résztáv");
costume[i, j] = comment;
Console.WriteLine(costume[i,j]);
}

I'm not sure what you want to do but you can declare more than one variable in for loop like this:
var array = new Array[10, 10];
for (int i = 0, j = 1; i < 3; j++, i++)
{
Console.WriteLine("i:" + i + " j:" + j);
array[i,j] = Console.ReadLine();
}

Related

Cross Search generate char Matrix

I am trying to create a word search puzzle matrix, this is the code I have,
static void PlaceWords(List<string> words)
{
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;
while (placed == false)
{
int nRow = rn.Next(0,10);
int nCol = rn.Next(0,10);
int nDirX = 0;
int nDirY = 0;
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed = PlaceWord(s.ToUpper(), nRow, nCol, nDirX, nDirY);
}
}
}
static bool PlaceWord(string s, int nRow, int nCol, int nDirX, int nDirY)
{
bool placed = false;
int LetterNb = s.Length;
int I = nRow;
int J = nCol;
if (MatriceIndice[nRow, nCol] == 0)
{
placed = true;
for (int i = 0; i < s.Length-1; i++)
{
I += nDirX;
J += nDirY;
if (I < 10 && I>0 && J < 10 && J>0)
{
if (MatriceIndice[I, J] == 0)
placed = placed && true;
else
placed = placed && false;
}
else
{
return false;
}
}
}
else
{
return false;
}
if(placed==true)
{
int placeI = nRow;
int placeJ = nCol;
for (int i = 0; i < s.Length - 1; i++)
{
placeI += nDirX;
placeJ += nDirY;
MatriceIndice[placeI,placeJ] = 1;
MatriceChars[placeJ, placeJ] = s[i];
}
}
return placed;
}
However it seems like it is an infinite loop. I am trying to add the code in a 1010 char matrix linked to a 1010 int matrix initially filled with 0 where I change the cases to 1 if the word is added to the matrix. How should I fix the code?
There are several errors. First,
MatriceChars[placeJ, placeJ] = s[i];
should be
MatriceChars[placeI, placeJ] = s[i];
Second,
for (int i = 0; i < s.Length - 1; i++)
(two occurrences) should be
for (int i = 0; i < s.Length; i++)
(You do want all the letters in the words, right?)
Third, when testing indices, you should use I >= 0, not I > 0, as the matrix indices start at 0.
However, the main logic of the code seems to work, but if you try to place too many words, you will indeed enter an infinite loop, since it just keeps trying and failing to place words that can never fit.

LCS C# Algorithm - Get the deleted lines and added lines in previous and current text

I have to rewrite the LCS algorithm because some company policies.
I've already get done the LCS algorithm, but next step is to identify which lines were removed from the previous text and which one were added in the current text.
I tried a simple check thought the lines, but it won't work if I got a text with duplicated lines.
He is my code:
LCS Method
private static string[] LcsLineByLine(string previous, string current)
{
string[] Previous = previous.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string[] Current = current.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string lcsResult = string.Empty;
int a = Previous.Length;
int b = Current.Length;
int[,] table = new int[a + 1, b + 1];
//create a table with first line and column equal 0
for (int i = 0; i <= a; i++)
table[i, 0] = 0;
for (int j = 0; j <= b; j++)
table[0, j] = 0;
//create a table matrix
for (int i = 1; i <= a; i++)
{
for (int j = 1; j <= b; j++)
{
if (string.Equals(Previous[i - 1].Trim(), Current[j - 1].Trim(), StringComparison.InvariantCultureIgnoreCase))
{
table[i, j] = table[i - 1, j - 1] + 1;
}
else
{
table[i, j] = Math.Max(table[i, j - 1], table[i - 1, j]);
}
}
}
//get the lcs string array with the differences
int index = table[a, b];
string[] lcs = new string[index + 1];
lcs[index] = "0";
while (a > 0 && b > 0)
{
if (string.Equals(Previous[a - 1].Trim(), Current[b - 1].Trim(), StringComparison.InvariantCultureIgnoreCase))
{
lcs[index - 1] = Previous[a - 1].Trim();
a--;
b--;
index--;
}
else if (table[a - 1, b] > table[a, b - 1])
a--;
else
b--;
}
return lcs;
}
And this is the code that is not working with duplicated lines with same value.
Method to get all deleted items in the previous text:
private List<DiffItem> GetDiffPrevious(string[] previous, string[] diff)
{
List<DiffItem> differences = new List<DiffItem>();
//check items deleted
int line = 0;
for (int i = 0; i < previous.Length; i++)
{
bool isAbsent = false;
for (int j = 0; j < diff.Length; j++)
{
if (string.Equals(previous[i].Trim(), diff[j].Trim(), StringComparison.InvariantCultureIgnoreCase))
{
differences.Add(new DiffItem() { Position = line, Text = diff[j], Status = DiffStatus.Equal });
line++;
isAbsent = false;
break;
}
else
{
isAbsent = true;
}
}
//mark as deleted
if (isAbsent)
{
differences.Add(new DiffItem() { Position = line, Text = previous[i].Trim(), Status = DiffStatus.Deleted });
line++;
}
}
return differences;
}
If anyone could help me or any feedback would be great. Just a reminder, I cannot use third party libraries.
Thanks in advance.
I found the solution!
Basically, I rewrite the two lists and translated using Hashtable, so all the values will be unique by line. Then, I use the method LCS and got the result as expected.
I hope it helps somebody.

char 2D array compression

There is a .txt file what I have to read, compress and make an output txt for the compressed txt. Could anyone tell me what should I fix in my code?
My code:
namespace Tomorites
{
class Compression
{
public void Compress(char[,] source)
{
for (int i = 0; i < source.GetLength(0); i++)
{
int white = 0;
int red = 0;
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j] == 'P')
{
if (source[i, j] > 0)
{
red++;
Console.Write(red + " P ");
}
}
else if(source[i,j]=='F')
{
if (source[i, j] > 0)
{
white++;
Console.Write(white + " F ");
}
}
}
Console.WriteLine();
}
}
}
}
My console output
Source txt file
The compressed txt file which has to be
You was pretty close, but messed one important thing: reset first char counter when second char appear or second char counter when first char appear.
Also source[i, j] > 0 condition do nothing for you.
So at result we may have:
Fill source array:
static void Main(string[] args)
{
// Declare array
char[,] source = new char[7, 10];
// Fill array as at example
for (int i = 0; i < source.GetLength(0); i++)
for (int j = 0; j < source.GetLength(1); j++)
source[i, j] = i == 3 || j == 3 ? 'F' : 'P';
// Print filled array to Console
Console.WriteLine("Source:\n" + new string('-', 10));
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
Console.Write(source[i, j] + " ");
Console.WriteLine();
}
// Just new line
Console.WriteLine();
// Now "compress"
Console.WriteLine("Compressed:\n" + new string('-', 10));
Compress(source);
Console.ReadKey();
}
Source output:
Compress source array:
static void Compress(char[,] source)
{
// Declare counters for P and F chars
int PCount = 0, FCount = 0;
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j] == 'P')
{
// If char is P - then count P's up
PCount++;
// If there was F char counted before (> 0) - print it and reset counter
if (FCount > 0)
{
Console.Write(FCount + " F ");
FCount = 0;
}
}
else if (source[i, j] == 'F')
{
// If char is P - then count F's up
FCount++;
// If there was P char counted before (> 0) - print it and reset counter
if (PCount > 0)
{
Console.Write(PCount + " P ");
PCount = 0;
}
}
}
// Before go to next "row" - print remained P or F counts and again, reset counters
if (PCount > 0)
{
Console.Write(PCount + " P ");
PCount = 0;
}
else if (FCount > 0)
{
Console.Write(FCount + " F ");
FCount = 0;
}
// Go new "row"
Console.WriteLine();
}
}
Compressed output:
UPD.
My answer is just solution for a provided example source and example output. #Dmitry Bychenko's solution is universal, not dependent on any two specific characters so in general use I recommend his way.
You can try something like this (you can fiddle with the code):
public static string Compress(char[,] source) {
if (null == source || source.GetLength(0) <= 0 || source.GetLength(1) <= 0)
return "";
StringBuilder sb = new StringBuilder();
for (int row = 0; row < source.GetLength(0); ++row) {
if (sb.Length > 0)
sb.AppendLine();
int count = 0;
char prior = '\0';
bool left = true;
for (int col = 0; col < source.GetLength(1); ++col) {
if (count == 0 || prior == source[row, col])
count += 1;
else {
if (!left)
sb.Append(' ');
left = false;
sb.Append($"{count} {prior}");
count = 1;
}
prior = source[row, col];
}
if (!left)
sb.Append(' ');
sb.Append($"{count} {prior}");
}
return sb.ToString();
}
Demo:
char[,] test = new char[,] {
{'a', 'a', 'a', 'a'},
{'a', 'b', 'c', 'c'},
};
Console.WriteLine(Compress(test));
Outcome:
4 a
1 a 1 b 2 c

how can i fetch text box value in string array and print

this is my code 1 index print second index showing error "Index was outside the bounds of the array." please help what should I do?
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
for (int i = 0; i <= SName.Length - 1; i++)
{
Response.Write(SName[i]);
Response.Write(Email[i]);
}
It is not necessary you get same length for both SName and Email string arrays.
Index is out of bound because length are not same.
Better way is to do it separately:
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
for (int i = 0; i < SName.Length; i++)
Response.Write(SName[i]);
for (int i = 0; i < Email.Length; i++)
Response.Write(Email[i]);
If you want to print one name and email then use this:
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
int iLength = -1;
if(SName.Length > Email.Length)
iLength = SName.Length;
else
iLength = Email.Length;
for (int i = 0; i < iLength; i++)
{
if(i < SName.Length)
Response.Write(SName[i]);
if(i < Email.Length)
Response.Write(Email[i]);
}
NOTE:
If you are not dealing with array of HTML element with same name then you don't have to use Request.Form.GetValues("title"). See following example:
string SName = Request.Form["title"];
string Email = Request.Form["fname"];
Response.Write(SName + " " + Email);
Your code should be.
if (SName != null)
for (int i = 0; i < SName.Length; i++)
Response.Write(SName[i]);
if (Email != null)
for (int i = 0; i < Email.Length; i++)
Response.Write(Email[i]);
The problem is that length of SName and Email are different.
You can use the below code, which gives the result in a single loop
if (SName != null && SName.Length > 0 && Email != null && Email.Length > 0)
{
for (int i = 0,j=0; i < SName.Length && j<Email.Length; i++,j++)
{
Response.Write(SName[i]);
Response.Write(Email[j]);
}
}

In C# arrays, how not to create duplicated random numbers?

I'm a beginner in C#, trying to make a lottery form applicaton.
There are types, first when you have 5 tips ( otos bool ) and 5 tips ( hatos bool ).
And there are many types of how many numbers will be raffled (tiz, harminc, kilencven, negyvenot).
I tried to scan the numbers after the raffle with Array.Equals with this code:
for (int i = 0; i <= 4; i++)
{
for (int y = 0; y <= 4; y++)
{
if (Array.Equals(lottoszamok[i], lottoszamok[y]))
lottoszamok[i] = r.Next (1, ?);
}
}
but at this the number will be scanned with itself too, so it will be always equal.
here is my code by the way:
if (otos == true)
{
for (int i = 0; i <= 5; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
if (hatos == true)
{
for (int i = 0; i <= 6; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
If you're trying to pick numbers from a range 1..n without repetitions, you need to "shuffle" the numbers out:
int[] allPossibleNumbers = Enumerable.Range(1, maxNumber).ToArray();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int index = r.Next(i, maxNumber);
picked[i] = allPossibleNumbers[index];
allPossibleNumbers[index] = allPossibleNumbers[i];
}
where numberToPick is 5 if otos or 6 if hatos, and maxNumber depends on tiz, harminc, kilencven, negyvenot, egyeni and egyeniertek.
If your maxNumber is huge and you only want to pick a few numbers, the following doesn't require the whole range to be in memory at once:
Dictionary<int, int> outOfPlace = new Dictionary<int,int>();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int shuffleOut = outOfPlace.ContainsKey(i) ? outOfPlace[i] : i;
int index = r.Next(i, maxNumber);
picked[i] = 1 + (outOfPlace.ContainsKey(index) ? outOfPlace[index] : index);
outOfPlace[index] = shuffleOut;
outOfPlace.Remove(i);
}
Try this one!
if (i!=y && Array.Equals(lottoszamok[i], lottoszamok[y]))
I made it this way, if you want you could put swapping like method.
static void SwapInts(int[] array, int position1, int position2)
{
// Swaps elements in an array.
int temp = array[position1]; // Copy the first position's element
array[position1] = array[position2]; // Assign to the second element
array[position2] = temp; // Assign to the first element
}
static void Main()
{
Random rng = new Random();
int n = int.Parse(Console.ReadLine());
int[] intarray = new int[n];
for (int i = 0; i < n; i++)
{
// Initialize array
intarray[i] = i + 1;
}
// Exchange resultArray[i] with random element in resultArray[i..n-1]
for (int i = 0; i < n; i++)
{
int positionSwapElement1 = i + rng.Next(0, n - i);
SwapInts(intarray, i, positionSwapElement1);
}
for (int i = 0; i < n; i++)
{
Console.Write(intarray[i] + " ");
}
}
}
I spend many time to get this, but i believe i can do it, now it's done, By the Easier way in the word, this kill every think about Random not duplicate,very simply code without any philosophy or difficulty of Developers made ... (welcome to my work) that (BEST OF THE BEST):
Numbers between (1-10) without any duplicate, 1- MY WORK in C#
private void TenNumbersRandomly()
{
int[] a = new int[10];
Random r = new Random();
int x;
for (int i = 0; i < 10; i++)
{
x= r.Next(1, 11);
for (int j = 0; j <= i ; j++)
{
while (a[j] == x)
{
x = r.Next(1, 11);
j = 0;
}
}
a[i] = x;
tb1.Text += a[i]+"\n";
}
}
2- in VB some Different i also have it :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Integer, i As Integer, j As Integer
x = Int(Rnd() * 10) + 1
Label1.Text = ""
Dim a(9) As Integer
For i = 0 To 9
x = Int(Rnd() * 10) + 1
For j = 0 To i
While (a(j) = x)
x = Int(Rnd() * 10) + 1
j = 0
End While
Next j
a(i) = x
Label1.Text += a(i).ToString() + " "
Next i

Categories