First time asking a question on Stackoverflow, fingers crossed! I'm new to programming and I'm struggeling to solve an issue. I got this foor loop:
for (int i = 0; i < antal.Count(); i++)
{
tbxResultat.AppendText(namnLista.ElementAt(i) + " \t");
tbxResultat.AppendText(personnummerLista.ElementAt(i).ToString() + " \t");
tbxResultat.AppendText(distriktLista.ElementAt(i) + " \t");
tbxResultat.AppendText(antal.ElementAt(i).ToString() + newLine);
}
I want to group the results from the loop into 4 sections: first values 0-49, second 50-99, third 100-199 and fourth 199. I'm interested in seeing how many is in each section and having it printed right each section, like:
23
37
---------------------------------
Total count of 2 in first section.
I've tried putting the for-loop in if statments but with no success. The sortment of the list is done with bubble sort which i modified to take a List instead of array. Any tips in the right direction would be much appriciated!
/Drone
This code should be what you asked for. Note the while in there. It's not if because there may be groups with zero elements, so you have to handle those as well.
int groupLimit = 50;
int elementsInGroup = 0;
for (int i = 0; i < antal.Count(); i++, elementsInGroup++)
{
while (antal[i] >= groupLimit)
{
// Write summary here. Use elementsInGroup..
groupLimit += 50;
elementsInGroup = 0;
}
// Write one row here. I suggest building the string and calling only one AppendText..
}
Related
I have this code that lets you enter 4 values and it prints the highest value you entered.
I understand everything up until the second for loop, how does it print the highest value? I'm rather new to c# and this is part of a school assignment.
The part of code which is within "**" is what I don't really understand.
int[] inputNum = new int[4];
for(int i = 0; i < 4; i++)
{
Console.Write("Enter number: ");
inputNum[i] = int.Parse(Console.ReadLine());
}
**int inputMax = 0;
for(int i2 = 0; i2 < inputNum.Length; i2++)
{
if(inputNum[i2] > inputMax)
{
inputMax = inputNum[i2];
}**
}
Console.WriteLine($"Highest value number: {inputMax}");
The second loop goes over the numbers that were inputted in the first loop and for each iteration checks if the current number is larger than the previous maximum, and if it is, saves it in inputMax. Once the loop is done, you'll be left with the largest number in that variable.
To be honest, though, this problem doesn't really need both loops. If the only requirement is to input four numbers and print out the largest one, there's no need to save them to an array, and you could just perform this check on each number that's inputted.
I am playing with C#. I try to write program that frames the quote entered by a user in a square of chars. So, the problem is... a user needs to indicate the number of lines before entering a quote. I want to remove this moment, so the user just enters lines of their phrase (each line is a new element in the string array, so I guess a program should kinda declare it by itself?..). I hope I explained clear what I meant x).
I've attached the program code below. I know that it is not perfect (for example, when entering the number of lines, I use the conversion to an integer, and if a user enters a letter, then this may confuse my electronic friend, this is a temporary solution, since I do not want to ask this x) The program itself must count these lines! x)) Though, I don't understand why the symbols on the left side are displayed incorrectly when the program displays output, but I think this also does not matter yet).
//Greet a user, asking for the number of lines.
Console.WriteLine("Greetings! I can put any phrase into beautiful #-square."
+ "\n" + "Wanna try? How many lines in the quote: ");
int numberOfLines = Convert.ToInt32(Console.ReadLine());
//Asking for each line.
string[] lines = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
Console.WriteLine("Enter the line: ");
lines[i] = Console.ReadLine();
}
//Looking for the biggest line
int length = 0;
for (int i = 0; i < numberOfLines; i++)
{
if (length < lines[i].Length) length = lines[i].Length;
}
//Starting framing
char doggy = '#';
char space = ' ';
length += 4;
string frame = new String(doggy, length);
Console.WriteLine(frame);
for (int i = 0; i < numberOfLines; i++)
{
string result = new string(space, length - 3 - lines[i].Length);
Console.WriteLine(doggy + space + lines[i] + result + doggy);
}
Console.WriteLine(frame);
Console.ReadLine();
}
}
}
There is performance gap and functionality between "Generic Lists" and arrays, you can read more about cons and pros of this two objects in the internet,
for example you can use list as Dai mentioned in comment like this
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
or you can use arraylist
ArrayList arraylist = new ArrayList();
arraylist.Add();
or even you can change the size of array any times but it erase data in it
int[] arr = new int[100];
there is a function called ToArray() you can use it to change generic list to array
Your problem of the left side output is, that you add two values of char. This is not what you expect to be. You must convert the char to a string to append it to other strings:
Console.WriteLine(doggy.ToString() + space.ToString() + lines[i] + result + doggy.ToString());
I'm having a little trouble figuring out a nested for loop here. Here's the problem:
The population of Ireland is 4.8 million and growing at a rate of 7% per year. Write a program to determine and display the population
in 10 years time. Your program should also display a count of the
number of years that the population is predicted to exceed 5 million.
And here's what I've coded so far:
double pop = 4.8;
int years = 0;
for (int i = 0; i < 10; i++)
{
pop += (pop / 100) * 7;
for (int j = 0; pop >5; j++)
{
years += j;
}
}
Console.WriteLine("Pop in year 2030 is " + Math.Round(pop, 2) + " million and the population will be over 5 million for " + years + " years.");
}
Now to be clear, I need the sum of the years in which population exceeds 5(million) (the answer is 10) and I must only use for loops to solve this problem. I'm thinking the answer is a nested for loop, but have tried and tried with no success.
Can anyone help me on where I've screwed this up?
Look at your inner loop.
for (int j = 0; pop >5; j++)
{
years += j;
}
Your condition being pop > 5, you need pop to shrink if you ever want to exit the loop. But the body of the loop never alters pop, so if it's greater than 5, you'll loop forever.
The problem definition suggests that you don't need an inner loop at all. Just check pop, and if it's greater than 5, increment years.
if (pop > 5)
{
++years;
}
If you're really under such an insane restriction that you can't use if, you could do something boneheaded like create a for loop that only runs once if your other condition is right.
for (int j = 0; j < 1 && pop > 5; ++j)
{
++years;
}
but no sane person does this.
First, you need to clearer variable names in my opinion. Of course, don't go to far with that, but IMO population will be better than just pop.
Furhter, you could use Dictionary to store years alongside with preidcted population.
Also, write comments to better see what's going on :)
With this suggestions, I would code this like below:
double population = 4.8;
int currentYear = 2020;
Dictionary<int, double> predictions = new Dictionary<int, double>();
// Adding current state
predictions.Add(currentYear, population);
// I changed bounds of a loop to handle years in more comfortable way :)
for (int i = 1; i <= 10; i++)
{
population *= 1.07;
predictions.Add(currentYear + i, population);
}
Now you have data in Dictionary that looks like this:
2020 4.8
2021 ...
2022 ...
... ...
Now you can get all years, where population was over 5 million easily with predictions.Where(kvp => kvp.Value > 5).
If I well understand your question.
Technically if you add 7% each year your program should look like this
bool passed = true;
double pop = 4.8;
int year = 0;
for (int i=0; i<10; i++)
{
pop *= 1.07;
if (pop > 5 && passed)
{
year = i;
passed = false;
}
}
I am trying to show multiple things in a textbox in my software and its just printing out 1 / 5
I think I got the for loop all mixed up so here is how it looks
var getTopFive = new FirefoxDriver();
getTopFive.Navigate().GoToUrl("https://www.tradingview.com/");
IList<IWebElement> movies = getTopFive.FindElements(By.CssSelector("tbody tr"));
for (int i = 0; i < 1; ++i)
{
activeTextBox.Text = movies[i].Text;
}
This is what I tried and failed with.
I tried adding another
activeTextBox.Text = movies[i].Text;
Which did not work
I also tried adding a second block of the same code showed at the top but with a different name for the int etc.
Then I tried adding a else if below it which gave me another error.
So my question is, how do I make the loop go through all the 5 items instead of just showing the first one which it does by this line of code right here.
for (int i = 0; i < 1; ++i)
{
activeTextBox.Text = movies[i].Text;
}
There are two issues here. The first is your for loop is only going to happen once because for(int i = 0; i < 1; i++).
To loop more than once, you need to change to 1 to something else. If you want it dynamic, use for(int i = 0; i < movies.Count; i++).
The second issue is activeTextBox.Text is being over-written each time you write to it. No matter how many times you repeat the loop or the line, the only thing that text box will show is the last item in the loop.
If you want it to show all items, you need to do something like:
activeTextBox.Text += movies[i].Text + "\n";
The \n will put each movie on a separate line - you could use a hyphen or similar to separate each item.
IList has a property called Count. This property returns the number of elements in the list. Use it in your loop like this to show all movies:
for (int i = 0; i < movies.Count; i++)
{
activeTextBox.Text = movies[i].Text;
}
A second way is to use a foreach loop like this:
foreach (IWebElement WebElement in movies)
{
activeTextBox.Text = WebElement.Text;
}
Remember you are overwriting your text each loop. So in the end your text will be the last item of your loop. If you want to add the names behind each other do it like this (seperated with a minus)
activeTextBox.Text += " - " + movies[i].Text;
or this
activeTextBox.Text += " - " + WebElement.Text
clear the Text before your loop with
activeTextBox.Text.Clear();
Try using this code (don't forget to add using System.Linq;):
activeTextBox.Text = string.Join("; ", movies.Select(x => x.Text));
Explanation:
movies.Select(x => x.Text) takes every IWebElement (movie) and return its Text property. So you end up with a list of movie names instead of IWebElement objects.
Next, you join those movies together into a single string, separated by semicolon. (string.Join("; ", ...))
And then you assign the result to the activeTextBox.
There is a test that consists of 12 questions. each question must have a value greater than 4 points. all the question must add to 100. also all the questions must have an integer value.
so a possible combination may be 5,5,5,5,5,5,5,5,5,5,5,45
there is a method that theoretically will give this result:
// this method will return the possible number of tests
public static double PosibleNumberOfTests()
{
int q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12; // each question value
double counter=0; // if there is a valid combination then counter will be increased by 1
for (q12 = 5; q12 < 46; q12++)
{
for (q11 = 5; q11 < 46; q11++)
{
for (q10 = 5; q10 < 46; q10++)
{
for (q9 = 5; q9 < 46; q9++)
{
for (q8 = 5; q8 < 46; q8++)
{
for (q7 = 5; q7 < 46; q7++)
{
for (q6 = 5; q6 < 46; q6++)
{
for (q5 = 5; q5 < 46; q5++)
{
for (q4 = 5; q4 < 46; q4++)
{
for (q3 = 5; q3 < 46; q3++)
{
for (q2 = 5; q2 < 46; q2++)
{
for (q1 = 5; q1 < 46; q1++)
{
if (q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12 == 100)
counter++; // here is what we need. How many times will this line be executed!
}
}
}
}
}
}
}
}
}
}
}
}
return counter;
}
note that I created each loop for values less than 46 because if all questions must have a value greater than 4 it will be impossible for a question to be worth 50 points for example.
Edit
Sorry people I think I am not explaining my self clearly. I piked 12 questions as a random guess. This example may have been with a test with 100 questions. I need something like what dlev mentioned in his comment. I also know I can place breaks in the loops to make the method more efficient. if the sum is greater than 100 then why continue looping just brak out of the corresponding loop
This code will evaluate the if statement 22,563,490,300,366,186,081 times. So needless to say, that ain't gonna work...
But with a few changes, it will. I'm not suggesting that brute force would be the way to go to solve this problem, but it does work.
First, to make the expressions a little simpler, observe that he have the same problem if every question must have a non-negative amount of points and the points have to add up to 40.
Now, the first loop becomes for (q12 = 0; q12 <= 40; q12++).
In the second loop, we don't have to test all q11 between 0 and 40, since q11 + q12 can't be greater than 40.
So, the second loop becomes for (q11 = 0; q11 + q12 <= 40; q11++).
And so on...
Finally, the last for loop is completely unnecessary since there's only one possible value for q1.
So, change
for (q1 = 5; q1 < 46; q1++)
if (q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12 == 100)
counter++;
to
if (q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12 <= 40)
counter++;
Not quick. Not elegant. But it works.
While this is much faster than the initial implementation, even if finding 1,000,000 "good" combinations per second, it will still take about 13 hours...
Let's change to problem to "each question must be worth at least 1 point and the sum of all points has to be 52". This is equivalent to the initial question.
We have 52 points to distribute. Each asterisk represents a point:
****************************************************
To do this, we may separate those points using delimiters. Eleven delimiters will give us 12 groups of asterisks.
Example: ****|*****|****|********|*|***|**|****|****|*********|***|*****
Each delimiter must be between two adjacent asterisks. There are 51 of those spaces.
Since the delimiters present no differences, the solution is also the solution of the question "in how many different, order-independent ways can 11 items be allocated in 51 spots.
The number of 11-combinations from a given set of 51 elements is 51! / ( 40! * 11! ) which gives us 47,626,016,970.
This all is assuming that "order matters", i. e., it's different if question 1 is worth 10 points and question 2 is worth 20 points or viceversa.
For q questions, each worth more than p points and a total of t points on the test, the formula would be:
(t - p * q - 1)! / ( (t - (p + 1) * q)! * (q - 1)! )
Whenever you encounter a counting question, it's always a good idea to subtract constants first. In this case, the minimum value for each question is 5, so subtract that from each value and from the total. This gives you a maximum total of 40 with a minimum of 0 for each question. Then at the end, when you present the actual solution, you can add the constants again.
Now look at this question: Distribution of balls into 'bins with given capacities' using Dynamic Programming.
Your problem is the same, except that it's a little bit simpler. It's the same because your questions correspond to the bins and the values correspond to the balls.
Yours is simpler because in your case, the capacity of the questions is not limiting. In the accepted answer to the above question, min(n, c[k]) is always equal to n.
The answer from my teacher: (same as what you guys gave thanks!)