I have a table called dttemp inside c# code, and a column of page number that I get from input. I want to validate function that tells me if there is duplicate string of number in the column. But turns out i create wrong one.
but remember the input of page_number is a string
The table looks like this:
id
page_numb
1
1,2,3,4,5,6,7,8,9
1
10
So before I ask this I have already try mine with this loop:
for (int i = 0; i < dttemp.Rows.Count; i++)
{
string[] abc = dttemp.Rows[i]["page_numb"].ToString().Split(',');
for (int az = 0; az < abc.Length; az++)
{
int count = 0;
for (int j = 0; j < dttemp.Rows.Count; j++)
{
if (dttemp.Rows[j]["page_numb"].ToString().Contains(abc[az].ToString()))
{
count = count + 1;
}
if (dttemp.Rows[j]["page_numb"].ToString().Contains(abc[az].ToString()) && count > 1)
{
MessageBox.Show("There is number of page been input more than once");
return;
}
}
}
}
But the function tells me there is same number too.
I think the code that I wrote validate between number 1 and 10 is same page number,
because the 10 having '1' in it, which is already input it in the first row belong with other number '1,2,3,4,5,6,7,8,9'.
Or maybe I am wrong. But the fact this function tells me I have same page number, which is wrong.
I do new to the code though so this question maybe easy, I just want to know how can I fix this?
Because the code will decide which page should I split from 1 file
You should exclude the current Row in the inner for-loop.
for (int i = 0; i < dttemp.Rows.Count; i++)
{
string[] abc = dttemp.Rows[i]["page_numb"].ToString().Split(',');
for (int az = 0; az < abc.Length; az++)
{
int count = 0;
for (int j = 0; j < dttemp.Rows.Count; j++)
{
// Exclude the current Row[i]
if (j == i)
{
continue;
}
if (dttemp.Rows[j]["page_numb"].ToString().Contains(abc[az].ToString()))
{
count = count + 1;
}
if (dttemp.Rows[j]["page_numb"].ToString().Contains(abc[az].ToString()) && count > 1)
{
Console.WriteLine("There is number of page been input more than once");
return;
}
}
}
}
Check it here
Related
today while I was coding I ran into a problem I couldn't figure out.
So my task is to print a chosen amount of characters, the catch is I need to also specify how much characters are in one line.
For example:
I need to print 24 characters '*'
I select the character.
Select how many: 24.
Select how many character per each line: 7.
Result should look something like this:
*******
*******
*******
***
I have to strictly use nested loops!
Code example:
static void Main(string[] args)
{
char character;
int charAmount;
int charAmountInLine;
Console.WriteLine("Select character");
character = char.Parse(Console.ReadLine());
Console.WriteLine("Select total amount of characters");
charAmount = int.Parse(Console.ReadLine());
Console.WriteLine("Select amount of characters in each line");
charAmountInLine = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = 0; i < charAmount; i++)
{
for(int j = 0; j < charAmountInLine; j++)
{
}
}
}
}
}
In this program, you need to identify:
Number of lines that print full characters in a line (row)
Print the remaining characters (remainder)
Concept:
Iterate each row (first loop).
Print character(s) in a line (nested loop in first loop).
Once print character(s) in a line is completed, print the new row and repeat Step 1 to Step 3 to print full characters in a line if any.
Print the remaining character in a line (second loop).
int row = amount / characterPerLine;
int remainder = amount % characterPerLine;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < characterPerLine; j++)
{
Console.Write(character);
}
Console.WriteLine();
}
// Print remaining character
for (int i = 0; i < remainder; i++)
{
Console.Write(character);
}
Demo # .Net Fiddle
First of all count number of rows for outer loop
int numberOfRows = (int)Math.Ceiling((double)charAmount / charAmountInLine);
for (int i = 0; i < numberOfRows; i++)
{
charAmount -= charAmountInLine;
charAmountInLine = charAmount> charAmountInLine? charAmountInLine: charAmount;
for (int j = 0; j < charAmountInLine; j++)
{
Console.Write(character);
}
Console.WriteLine("");
}
Try this one:
int row = (int)Math.Ceiling((double)charAmount/(double)charAmountInLine);
int column = 0;
int temp = 0;
for (int i = 1; i <= row; i++)
{
temp = (i * charAmountInLine);
column = temp < charAmount ? charAmountInLine : temp - charAmount;
for(int j = 0; j < column; j++)
{
Console.Write(character);
}
Console.WriteLine();
}
How can I print the following pattern with the for statement?
AAAA
AAAB
AABB
ABBB
BBBB
What I tried to do:
Code:
int stars = 4;
for (int row = stars; row >= 1; row--)
{
for (int i = 0; i < row; i++)
{
Console.Write("A");
}
Console.WriteLine();
}
You where almost there.
I made a small change in the first for loop to add another row (>= 1 to >= 0). We need 5 rows for 4 stars, 6 rows for 5 stars, etc.
Compared the second for loop to stars as well because we want 4 values on each row (when stars is 4).
Added an if statement to check if we need to write an A or B based on the iteration number of both loops.
See code below:
int stars = 4;
for(int i = stars; i >= 0; i--) {
for(int j = 0; j < stars; j++) {
if(i > j) {
Console.Write('A');
}
else {
Console.Write('B');
}
}
Console.WriteLine();
}
i have a huge Problem when dealing with jagged arrays [][].
I wrote a program that interacts with lots of CSV-files. It will read them and then compare them. Now i have a problem if Array A has the dimension of 10 Rows and 10 Columns but Array B only has the dimension of 5 Rows and 5 Columns. I get the "out of range" on array B. This is only an example it gets even worse if i have a array which has different amount of Rows in each Column...
I tried checking for "null" but this doesnt work since i get the "out of range" once it tries to acess the field...
Now i have 2 theories to solve the problem:
A.)Check for "out of range" in Array B and if so fill Array A at the same field with a "0"
B.) Check if Array A and Array B has same dimension and if not fill the array with lesser amount with "0" so that it has the same amount
On both solutions i have absolutely no clue how to do this in C#... I am always getting the out of range...
What i currently do for 1 array is:
for (int b = CSV_Statistiken.Length - 1; b >= 0; b--)
{
for (int a = 0; a < CSV_Statistiken[b].Length; a++)
{
CSV_Statistiken[b][a] = 1;
}
}
so i get the dimension of the array and iterate through it, setting every value to 1. But how do i deal with my problem with 2 arrays?
I researched a bit but couldnt find any solution to this =/
Thanks in advance
Edit: What i am trying to do for examlple:
for (int i = 0; i < number; i++) //runs through every File existing
{
NextFile = fold.Filepath + "\\" + files[i].ToString();
file = new FileInfo(#NextFile);
max_Rows = 0;
max_Col = 0;
CSV_temp = ReadCSV(file, ref max_Rows, ref max_Col); // reads the next file to an arraay [][] and saves the size of this array in max_col/ max_rows
MAX_Col_Total = GetHighestValues(ref MAX_Col_Total, max_Col);
MAX_Rows_Total = GetHighestValues(ref MAX_Rows_Total, max_Rows);
for (int j = 0; j < MAX_Col_Total; j++) //runs thrugh the max amount of cols found
{
for (int k = MAX_Rows_Total - 1; k >= 0; k--) //runs through the max mount of rows found
{
if (CSV_temp.GetLength(0) >= j && CSV_temp.GetLength(1) >= k)//Checks if Field exists -> does NOT work!
{
if (CSV_temp[k][j] > (Threshhold))) //
{
do something
}
}
else
{
// Field doesnt exists -> do something else
}
}
}
}
You can check Lengths of two arrays in for loops:
for (int a = 0; a < array1.Length && a < array2.Length; a++)
{
for (int b = 0; b < array1[a].Length && b < array2[a].Length; b++)
{
//compare
}
}
Now your loops never go outside of any array index and you won't get IndexOutOfRangeException.
EDIT:
var biggestLength1 = Math.Max(array1.Length, array2.Length);
for (int a = 0; a < biggestLength1; a++)
{
var biggestLength2 = 0;
if (array1.Length > a && array2.Length > a)
{
biggestLength2 = Math.Max(array1[a].Length, array2[a].Length);
}
else
{
biggestLength2 = array1.Length > a ? array1.Length : array2.Length;
}
for (int b = 0; b < biggestLength2; b++)
{
if (a < array1.Length &&
a < array2.Length &&
b < array1[a].Length &&
b < array2[a].Length)
{
// every array has enough elements count
// you can do operations with both arrays
}
else
{
// some array is bigger
}
}
}
I'm writing a program to find the largest palindromic number made from product of 3-digit numbers. Firstly,i Create a method which has ability to check if it is a palindromic number. Here is my code :
static int check(string input_number)
{
for (int i = 0; i < input_number.Length/2; i++)
if (input_number[i] != input_number[input_number.Length - i])
return 0;
return 1;
}
After that, it's my main code:
static void Main(string[] args)
{
int k = 0;
for (int i = 0; i < 999; i++)
for (int j = 0; j < 999; j++)
{
k = i * j;
if (check(k.ToString()) == 1)
Console.Write(k + " ");
}
}
But when it has a problem that the length of input_number is zero. So my code doesn't run right way. What can I do to solve the length of input_number?
You have a few bugs in your code:
1. 3-digit-numbers range from `100` to `999`, not from `0` to `998` as your loops currently do.
So your Main method should look like this:
static void Main(string[] args)
{
int k = 0;
for (int i = 100; i <= 999; i++)
for (int j = 100; j <= 999; j++)
{
k = i * j;
if (check(k.ToString()) == 1)
Console.Write(k + " ");
}
}
Now all pairs of three digit numbers are checked. But to improve performance you can let j start at i, because you already checked e.g. 213 * 416 and don't need to check 416 * 213 anymore:
for (int i = 100; i <= 999; i++)
for (int j = i; j <= 999; j++) // start at i
And since you want to find the largest, you may want to start at the other end:
for (int i = 999; i >= 100; i--)
for (int j = 999; j >= 100; j--)
But that still does not guarantee that the first result will be the largest. You need to collect the result and sort them. Here is my LINQ suggestion for your Main:
var results = from i in Enumerable.Range(100, 900)
from j in Enumerable.Range(i, 1000-i)
let k = i * j
where (check(k.ToString() == 1)
orderby k descending
select new {i, j, k};
var highestResult = results.FirstOrDefault();
if (highestResult == null)
Console.WriteLine("There are no palindromes!");
else
Console.WriteLine($"The highest palindrome is {highestResult.i} * {highestResult.j} = {highestResult.k}");
2. Your palindrome-check is broken
You compare the character at index i to input_number[input_number.Length - i], which will throw an IndexOutOfRangeException for i = 0. Strings are zero-based index, so index of the last character is Length-1. So change the line to
if (input_number[i] != input_number[input_number.Length - i - 1])
Finally, I suggest to make the check method of return type bool instead of int:
static bool check(string input_number)
{
for (int i = 0; i < input_number.Length/2; i++)
if (input_number[i] != input_number[input_number.Length - i - 1])
return false;
return true;
}
This seems more natural to me.
You can use method below. Because you are trying to find the largest number you start from 999 and head backwards, do multiplication and check if its palindrome.
private void FindProduct()
{
var numbers = new List<int>();
for (int i = 999; i > 99; i--)
{
for (int j = 999; j > 99; j--)
{
var product = i * j;
var productString = product.ToString();
var reversed = product.Reverse();
if (product == reversed)
{
numbers.Add(product);
}
}
}
Console.WriteLine(numbers.Max());
}
guys!
I need some help with my code.
So, the story is, I had a task to do a form application, where user could count entropy of discrete random variables. He types events and probabilities, and program calculates the entropy.
So I used DataGridView, a button and a TextBox. I've made everything, including restriction, such as "sum of all probabilities must be equal to 1".
But the thing I can't do is - the program itself must delete or ignore rows, which contain "0" or rows, which are empty (because formula of entropy contains log of a number, and log of 0 is an infinity, that's why program will output "NaN - not a number").
The main code is located in "button".
Here is a snippet of it:
for (int z = dataGridView1.Rows.Count - 1; z >= 0; z--)
{
if (dataGridView1[1, z].Value == null)
{
dataGridView1.Rows.Remove(dataGridView1.Rows[z]);
}
else if (dataGridView1[1, z].Value == "0")
{ dataGridView1.Rows.Remove(dataGridView1.Rows[z]);}
}
The only thing I get after this code, is an error saying, that it can't delete a new "transmitted" (don't know how to translate that to English) line.
This is the whole code, located in "button":
int counter = 1;
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[0, i].Value = counter++;
}
double X = 0;
double A = 1;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
X += Convert.ToDouble(dataGridView1[1, i].Value);
}
if (X < A && X > A)
{
MessageBox.Show("Cумма вероятностей меньше или больше 1, введите другие значения вероятностей", "АШИППКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
double H = 0;
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
for (int z = dataGridView1.Rows.Count - 1; z >= 0; z--)
{
if (dataGridView1[1, z].Value == null)
{
dataGridView1.Rows.Remove(dataGridView1.Rows[z]);
}
else if (dataGridView1[1, z].Value == "0")
{ dataGridView1.Rows.Remove(dataGridView1.Rows[z]);}
}
double p = Convert.ToDouble(dataGridView1[1, i].Value);
H += p * Math.Log(p, 2.0);
}
textBox1.Text = Convert.ToString(-H);
}
Sorry for my bad english, it's not my native language, that's why there are a lot of mistakes. Please, ask, if you don't understand something.
Help me, please.
Elaborating on comment above.
If your DataGridView uses a DataTable or a BindingSource, e.g.
DataTable table = new DataTable();
table.Columns.Add(...);
DataGridView dgv = new DataGridView();
dgv.DataSource = table;
Anywhere your loops reference dataGridView1, replace that with table instead.
E.g.
for (int i = 0; i < table.Rows.Count; i++) {
//...
}