Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i need help, i had my friend to help me debug this code, and we found that the code stops at random points on the code, sometimes on first loop, sometimes on last loop and so on.
the code is just to make a 9x9 sudoku board with all the rules applied. when i tested each block separately it worked and printed a well done sudoku board, but the problem here is that is gets stuck somehow.
help will be appreciated.
int[,] helpblock = new int[10, 10];
int[,] helplines = new int[10, 10];
int[,] helpcols = new int[10, 10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
helplines[i, j] = 0;
helpcols[i, j] = 0;
helpblock[i, j] = 0;
}
}
Random rnf = new Random();
int help1;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
help1 = rnf.Next(1, 10);
if (i == 0 || i == 1 || i == 2) {
if (j == 0 || j == 1 || j == 2) {
if (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[0, help1]++;
} else if (j == 3 || j == 4 || j == 5) {
if (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[1, help1]++;
} else if (j == 6 || j == 7 || j == 8) {
if (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[2, help1]++;
}
} else if (i == 3 || i == 4 || i == 5) {
if (j == 0 || j == 1 || j == 2) {
if (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[3, help1]++;
} else if (j == 3 || j == 4 || j == 5) {
if (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[4, help1]++;
} else if (j == 6 || j == 7 || j == 8) {
if (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[5, help1]++;
}
} else if (i == 6 || i == 7 || i == 8) {
if (j == 0 || j == 1 || j == 2) {
if (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[6, help1]++;
} else if (j == 3 || j == 4 || j == 5) {
if (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[7, help1]++;
} else if (j == 6 || j == 7 || j == 8) {
if (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
while (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
}
map[i, j] = help1;
helplines[i, help1]++;
helpcols[j, help1]++;
helpblock[8, help1]++;
}
}
}
}
PrintSudoku(map);
This is not really an answer, but hopefully it will help you debug the program. Inside your for loops you have a whole bunch of if statements that look something like:
if (i == 0 || i == 1 || i == 2) {
if (j == 0 || j == 1 || j == 2) {
It looks like you are using this logic to determine which block you're in, because that's the one array that you are using a hard-coded value for the first index.
Instead of doing it this way, consider calculating the block using a formula based on the current row and column value.
Your grid currently looks something like this:
| 0 1 2 | 3 4 5 | 6 7 8 |
--+-------+-------+--------
0 | | | |
1 | [0] | [1] | [2] |
2 | | | |
--+-------+-------+--------
3 | | | |
4 | [3] | [4] | [5] |
5 | | | |
--+-------+-------+--------
6 | | | |
7 | [6] | [7] | [8] |
8 | | | |
---------------------------
What you might notice is that if you take the row number and do an integer division by 3, you will get the Block row number (0, 1, or 2). Multiplying this number by 3 gives you the first block in each row (0, 3, and 6). Now, if we take the current column and integer-divide that by 3, we will get the current block column (0, 1, or 2). Adding the "block row" to the "block column" then will give us the block index:
int block = ((row / 3) * 3) + (column / 3);
(Note that it looks like you could simplify this since row is being divided by three and then multiplied by three, but remember that integer division rounds down, so 2 / 3 == 0, not .6667)
By calculating the block this way, you can drastically reduce the number of lines you have to walk through.
Also, using some more meaningful variable names will help with the readability.
I simplified your code to something that I believe does the exact same thing. Maybe it will help your analysis:
int[,] blocks = new int[10, 10];
int[,] rows = new int[10, 10];
int[,] columns = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
rows[i, j] = 0;
columns[i, j] = 0;
blocks[i, j] = 0;
}
}
Random rnd = new Random();
int randomNumber;
for (int row = 0; row < 9; row++)
{
for (int column = 0; column < 9; column++)
{
int block = ((row / 3) * 3) + (column / 3);
randomNumber = rnd.Next(1, 10);
while (rows[row, randomNumber] != 0 ||
blocks[block, randomNumber] != 0 ||
columns[column, randomNumber] != 0)
{
System.Threading.Thread.Sleep(1);
randomNumber = rnd.Next(1, 10);
}
map[row, column] = randomNumber;
rows[row, randomNumber]++;
columns[column, randomNumber]++;
blocks[block, randomNumber]++;
}
}
After playing with this, of course, I got interested in the problem. Below is what I came up with to solve it, which is pretty much a brute-force method:
Start with numbers 1-9 available for each row, column, and block
From the list of available numbers for a cell, assign one of them at random, one cell at a time
Remove that number from the available numbers for that row, column, and block
If we run into the case where there is no valid number available for the cell, reset everything and try again.
Notice there is potential that this will run and never finish, but in my testing it usually finds a solution in less than 400 tries (which is relatively fast from a user's point of view).
What I did differently was, instead of using arrays to store the row/column/block information, I decided to use a Dictionary<int, List<int>>, which stores the row/column/block index as the key, and the value for each key is a List of available numbers for that index.
Then in our loop, I just put the intersection of the available numbers left for the current row, column, and block into a List. Then I pick a random index in that list and assign that value to the cell (and remove it from the available items in that row, column, and block).
I also added some logging to find out how many times it failed before finding a solution.
Here's the code, which also prints the solution at the end:
static void Main()
{
int[,] map = new int[9, 9];
var blocks = new Dictionary<int, List<int>>();
var rows = new Dictionary<int, List<int>>();
var columns = new Dictionary<int, List<int>>();
// initialize lists of available numbers
for (int i = 0; i < 9; i++)
{
blocks.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
rows.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
columns.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
}
Random rnd = new Random();
int failCount = 0;
// For each row
for (int row = 0; row < 9; row++)
{
// For each column in this row
for (int column = 0; column < 9; column++)
{
// Calculate block based on current row and column
int block = ((row / 3) * 3) + (column / 3);
// Get set of available numbers for this cell by getting the intersection
// of available numbers for the row, column, and block
var availableItems =
rows[row].Intersect(
columns[column].Intersect(
blocks[block])).ToList();
// If we reach a point where there are no availableItems, then this is
// not a valid Sudoku pattern. Reset everything and try again
if (availableItems.Count == 0)
{
failCount++;
Console.WriteLine($"Failed {failCount} times. Trying again...");
// Reset to the first cell
row = 0;
column = 0;
block = 0;
// Initialize data
for (int i = 0; i < 9; i++)
{
blocks[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
rows[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
columns[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
availableItems = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
// Grab a number from the available numbers by choosing a random index
var randomNumber = availableItems[rnd.Next(0, availableItems.Count)];
// Update our map with this item
map[row, column] = randomNumber;
// Remove this item from our lists
rows[row].Remove(randomNumber);
columns[column].Remove(randomNumber);
blocks[block].Remove(randomNumber);
}
}
// Print our Sudoku map:
Console.WriteLine(new string('-', 25));
for(int i = 0; i < 9; i++)
{
Console.Write("|");
for (int j = 0; j < 9; j++)
{
Console.Write($" {map[i, j]}");
if ((j + 1) % 3 == 0) Console.Write(" |");
}
Console.WriteLine();
if ((i + 1) % 3 == 0) Console.WriteLine(new string('-', 25));
}
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Ouput:
These loops look deadly:
while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
System.Threading.Thread.Sleep(1);
help1 = rnf.Next(1, 10);
}
If the new value of help1 doesn't change the while condition to false, it will loop forever.
Related
I'd like to access the rows, cols and the diagonals of a 2d matrix. How can I do this correctly?
I'm planning to use this in a function where I will access a particular row, column or diagonal and then exit the nested loop.
I've tried the following example :
Considering a 2d matrix of chars :
char[,] board = { { 'O', 'O', 'O' }, { 'X', 'X', 'X' }, { 'O', 'O', 'O' } };
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
// for example the second row where all the values are X
if (board[i+1, j] == 'X' && board[i+1, j+1] == 'X' && board[i+1, j+2] == 'X')
{
Console.WriteLine(board[i+1, j]);
Console.WriteLine(board[i+1, j+1]);
Console.WriteLine(board[i+1, j+2]);
}
}
}
To read from the array in the method you want, omit the for loops and just access the array directly...
// Only X's
Console.Write(board[1, 0]);
Console.Write(board[1, 1]);
Console.WriteLine(board[1, 2]);
// Diagonal
Console.Write(board[0, 0]);
Console.Write(board[1, 1]);
Console.WriteLine(board[2, 2]);
Use the for loops if you want to iterate through and display all of the values contained within the array. Remove the i+1 or 2 and j+1 or 2 as these will end up exceeding the array's constraints and cause an error
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
Console.WriteLine(board[i, j]);
}
}
To search for winners, you can do something as simple as checking all 8 combinations:
if ((board[0, 0] == charToCompare && board[0, 1] == charToCompare && board[0, 2] == charToCompare) || //Row 1
(board[1, 0] == charToCompare && board[1, 1] == charToCompare && board[1, 2] == charToCompare) || //Row 2
(board[2, 0] == charToCompare && board[2, 1] == charToCompare && board[2, 2] == charToCompare) || //Row 3
(board[0, 0] == charToCompare && board[1, 0] == charToCompare && board[2, 0] == charToCompare) || //Col 1
(board[1, 0] == charToCompare && board[1, 1] == charToCompare && board[1, 2] == charToCompare) || //Col 2
(board[2, 0] == charToCompare && board[2, 1] == charToCompare && board[2, 2] == charToCompare) || //Col 3
(board[0, 0] == charToCompare && board[1, 1] == charToCompare && board[2, 2] == charToCompare) || //Diagonal Top to Bottom
(board[2, 0] == charToCompare && board[1, 1] == charToCompare && board[0, 2] == charToCompare)) //Diagonal Bottom to Top
{
Console.WriteLine("Winner");
}
Or to modify your original code with 1 for loop and the breaks, you can do like so. There are probably much better ways, but effectively you will need to implement a routine to check for the solutions you desire
char[,] board = { { 'X', 'O', 'O' }
, { 'X', 'X', 'O' }
, { 'O', 'X', 'X' } };
char charToCompare = 'X';
for (int i = 0; i < 3; i++)
{
if (board[i, 0] == charToCompare && board[i, 1] == charToCompare && board[i, 2] == charToCompare)
{
Console.WriteLine($"Winner Row {i}");
break;
}
if (board[0, i] == charToCompare && board[1, i] == charToCompare && board[2, i] == charToCompare)
{
Console.WriteLine($"Winner Column {i}");
break;
}
}
if (board[0, 0] == charToCompare && board[1, 1] == charToCompare && board[2, 2] == charToCompare)
{
Console.WriteLine("Winner diagonal top to bottom");
}
if (board[2, 0] == charToCompare && board[1, 1] == charToCompare && board[0, 2] == charToCompare)
{
Console.WriteLine("Winner diagonal bottom to top");
}
I am having issues with this assignment I have. I am to print a spiral matrix which cannot be square, in other words the user should input the number of rows and columns.
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter m: ");
int m = int.Parse(Console.ReadLine());
int[,] matrix = new int[n,m];
int row = 0;
int col = 0;
string direction = "right";
int maxRotations = n * m;
for (int i = 1; i <= maxRotations; i++)
{
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
{
direction = "down";
col--;
row++;
}
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
{
direction = "left";
row--;
col--;
}
if (direction == "left" && (col < 0 || matrix[row, col] != 0))
{
direction = "up";
col++;
row--;
}
if (direction == "up" && row < 0 || matrix[row, col] != 0)
{
direction = "right";
row++;
col++;
}
matrix[row, col] = i;
if (direction == "right")
{
col++;
}
if (direction == "down")
{
row++;
}
if (direction == "left")
{
col--;
}
if (direction == "up")
{
row--;
}
}
// displej matrica
for (int r = 0; r < n; r++)
{
for (int c = 0; c < m ; c++)
{
Console.Write("{0,4}", matrix[r,c]);
}
Console.WriteLine();
}
Console.ReadLine();
}
My issue currently is that is not printing and at the same is printing in a spiral. In other words the spiral is kind of messed up.
If i run the code and enter 4 as the number of rows and 6 as the number of columns I get the following:
1 2 3 4 0 24
12 13 14 5 0 23
11 16 17 18 19 22
10 9 8 7 20 21
What am i doing wrong?
Your first two conditions check the same boundary (n):
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
I guess for "right" your boundary should be m.
if (direction == "right" && (col > m - 1 || matrix[row, col] != 0))
That's why it is "turning" early: n is 4. And that's exactly where it is turning. The rest are all follow-up errors.
So I have a combobox and I have it so that based on other criteria the MaxLength is edited. The problem is that the MaxLength property only applies to typed inputs and not items from the combobox. So is there a way to remove items from the combobox based on their length and add them back if the length increases again? here is my code:
private void titleText_TextChanged(object sender, EventArgs e)
{
int colourNum;
int textType = 1;
if (titleTextType.Text == "Material")
textType = 1;
else if (titleTextType.Text == "Material Flipped")
textType = 2;
else if (titleTextType.Text == "Normal")
textType = 3;
else if (titleTextType.Text == "3D")
textType = 4;
else textType = 0;
if (titleTextColour.Text == "Red")
colourNum = 49;
else if (titleTextColour.Text == "Green")
colourNum = 50;
else if (titleTextColour.Text == "Yellow")
colourNum = 51;
else if (titleTextColour.Text == "Blue")
colourNum = 52;
else if (titleTextColour.Text == "Cyan")
colourNum = 53;
else if (titleTextColour.Text == "Pink")
colourNum = 54;
else if (titleTextColour.Text == "White")
colourNum = 55;
else if (titleTextColour.Text == "Black")
colourNum = 48;
else if (titleTextColour.Text == "Yale Blue")
colourNum = 59;
else if (titleTextColour.Text == "Light Yellow")
colourNum = 58;
else colourNum = 0;
byte[] colourArray = new byte[2]
{
(byte) 94,
(byte) colourNum
};
byte[] prefixArray1 = new byte[5]
{
(byte) 94,
(byte) textType,
(byte) 0x3D,//125decmax
(byte) 0x3D,//125decmax
(byte) titleText.Text.Length
};
if (textType == 3 && colourNum == 0)
{
titleText.MaxLength = 23;
}
else if (textType == 3 && colourNum != 0)
{
titleText.MaxLength = 21;
}
else if (textType == 1 && colourNum == 0 || textType == 2 && colourNum == 0)
{
titleText.MaxLength = 18;
}
else if (textType == 1 && colourNum != 0 || textType == 2 && colourNum != 0)
{
titleText.MaxLength = 16;
}
else if (textType == 4)
{
titleText.MaxLength = 3;
}
}
Thanks in advance c:
Here, will be easier to demonstrate code here.
My comboBox is named comboBox1.
This test code adds Test1 - Test20 and then removes them based on their length:
for (int x = comboBox1.Items.Count-1; x >= 0; x--)
if (comboBox1.Items[x].ToString().Length > comboBox1.MaxLength)
comboBox1.Items.RemoveAt(x);
Your code should look like this:
for (int x = titleText.Items.Count-1; x >= 0; x--)
if (titleText.Items[x].ToString().Length > titleText.MaxLength)
titleText.Items.RemoveAt(x);
I've two lists and I assign one of them this way:
var query = Enumerable.Range(0, 1440).Select((n, index) =>
{
if ((index >= 525 && index <= 544) || (index >= 600 && index <= 749) || (index >= 810 && index <= 1079) || (index >= 1300 && index <= 1439))
return 0;
else if (index >= 1080 && index <= 1299)
return 1;
else if (index >= 545 && index <= 599)
return 3;
else if (index >= 750 && index <= 809)
return 4;
else
return 2;
}).ToList();
My second list is named lst2. I want to assign it "0" or "1" depending on my first list query. So, if query is "1" or "2", lst2's same indices and previous indices that are "0" value, should be "1". If the query list is "3" or "4", lst2's same indices and previous indices that are "1" value, should be "0". In addition, if the query's first indice(s) has "3" or "4" value, then lst2's same indice(s) should be "0". For example;
query = {3,3,3,0,0,0,2,2,0,0,0,0,4,4,4,4,0,0,0,0,1,1,1,0,0,2,2,0,0,4,4}
lst2 = {0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0}
How can I do this?
EDIT: If query's any indice has 3 or 4 value, lst2's same indice must have 0 value. If query's any indice has 3 or 4 value AND previous indice has 0 value, lst2's same indices must have 0 value. Likewise; If query's any indice has 1 or 2 value, lst2's same indice must have 1 value. If query's any indice has 1 or 2 value AND previous indice has 0 value, lst2's same indices must have 1 value.
An alternative approach, only filling the tracing 0's when needed. Performance wise it's still best to loop reversed, but I only just saw T_D already did that, so as far as the lookahead -> lookback goes, the below is basically the same, but with other syntax and a different trailing 0 filler.
var arr = new int[query.Count];
int cnt = query.Count - 1, toappendindex = -1;
Func<int,int,int> getval = (ind, val) =>
{
if (val == 3 || val == 4) return 0;
if (val == 2 || val == 1) return 1;
if (ind == cnt) return -1;
return arr[ind + 1];
};
for (int ind = cnt; ind >= 0; ind-- )
{
if ((arr[ind] = getval(ind,query[ind])) == -1)
toappendindex = ind; //only if there are trailing 0's
}
if (toappendindex > 0)
for (; toappendindex < arr.Length; toappendindex++) arr[toappendindex] = arr[toappendindex - 1];
//var lst2 = arr.ToList(); if list is needed instead of array, otherwise arr could be used directly
Try doing this.
List<int> query = Enumerable.Range(0, 1440).Select((n, index) =>
{
if ((index >= 525 && index <= 544) || (index >= 600 && index <= 749) || (index >= 810 && index <= 1079) || (index >= 1300 && index <= 1439))
return 0;
else if (index >= 1080 && index <= 1299)
return 1;
else if (index >= 545 && index <= 599)
return 3;
else if (index >= 750 && index <= 809)
return 4;
else
return 2;
}).ToList();
Console.WriteLine(string.Concat("{", string.Join(",", query.ToArray()), "}"));
List<int> lst2 = Enumerable.Range(0, 1440).Select((n, index) =>
{
if (query[index] == 1 || query[index] == 2)
return 1;
else if (query[index] == 3 || query[index] == 4)
return 0;
else
{
int retval = 1;
//look ahead
for (int i = index; i < query.Count; i++)
{
if (query[i] == 1 || query[i] == 2)
{
break;
}
if (query[i] == 3 || query[i] == 4)
{
retval = 0;
break;
}
}
return retval;
}
}).ToList();
Console.WriteLine(string.Concat("{", string.Join(",", lst2.ToArray()), "}"));
Let me know if this is what you are looking for. You can replace List with var if you like. I just like it strong-typed so that I can easily check the output.
I hope this is what you need:
int n = 1440;
byte[] query = new byte[n];
byte[] lst2 = new byte[n];
byte mode = 0;
bool first = true;
for(int index = n-1; index >= 0; index--)
{
if ((index >= 525 && index <= 544) || (index >= 600 && index <= 749) || (index >= 810 && index <= 1079) || (index >= 1300 && index <= 1439))
query[index] = 0;
else if (index >= 1080 && index <= 1299)
query[index] = 1;
else if (index >= 545 && index <= 599)
query[index] = 3;
else if (index >= 750 && index <= 809)
query[index] = 4;
else
query[index] = 2;
if(query[index] == 3 || query[index] == 4)
{
mode = 0;
lst2[index] = 0;
}
else if(query[index] == 1 || query[index] == 2)
{
if(first)
{
//change ending zeros to 1
for(int j=index+1; j < n; j++)
lst2[j] = 1;
first = false;
}
mode = 1;
lst2[index] = 1;
}
else
{
lst2[index] = mode;
}
}
I'm trying to add the integers 6 from 30, except for 22 and 26, to a List using a for loop. But 22 and 26 are still being added. What did I do wrong?
List<int> lineNumbers = new List<int>();
for (int x = 6; x < 30; x++)
{
if ((x != 22) || (x != 26))
{
lineNumbers.Add(x);
}
}
The two integers are not added if the code is like below:
for (int x = 6; x < 30; x++)
{
if (x == 22 )
{
}
else if (x == 26)
{
}
else
{
lineNumbers.Add(x);
}
}
You need to replace the || with &&:
for (int x = 6; x < 30; x++)
{
if ((x != 22) && (x != 26))
{
lineNumbers.Add(x);
}
}
Or perhaps, to be more clear:
for (int x = 6; x < 30; x++)
{
if ((x == 22) || (x == 26))
continue;
lineNumbers.Add(x);
}
Alternatively, you could perform this as a one-liner using LINQ. This isn't necessarily faster or anything, so if your for loop is clearer to you, then keep it as-is.
lineNumbers.AddRange(Enumerable.Range(6, 24).Except(new[] { 22, 26 }));
Change your conditions. Use && instead of ||
if ((x != 22) && (x != 26))
Use && instead of || because you want to match between both conditions.
if ((x != 22) && (x != 26))
You can also do this using LINQ (not necessarily but I like LINQ :)
var lineNumbers = Enumerable.Range(6, 30).Except(new[] {22, 26}).ToList();
Replace if ((x != 22) || (x != 26)) to if ((x != 22) && (x != 26))
Or you can use continue like below :
for (int x = 6; x < 30; x++)
{
if ((x == 22) || (x == 26))
continue;
else
lineNumbers.Add(x);
}