Okay, lets assume we have a variable with an array like this
int[] digit;
int x = 5;
for(int i=0;i < = 5; i++)
{ digit[i] = 0;}
All value array on var Digit have 0. So what i want to do its i want to increment the value on that digit from right using Button Control that adds increment (that means digit[4] to digit[3] and so on) and when the value hits certain number example 5 in digit[4], it would come back to value 0 and the next var digit incremented (digit[3]). And the incremented start again and so on.
I already try using if and switch to make this happen like this
private btnClick_Click(Object Sender, Event Args)
{
digit[4] +=1;
if(digit[4] > 5) { digit[3] += 1;}
if(digit[3] > 5) { digit[2] += 1;}
//and so on
switch(digit[4])
{
case 5: digit[4]=0;
}
//and so on
}
But its only for logic If We Know The Array Number Location. Say if i retrieve that number for somewhere like 15 digit. If we set array number so little on that command Button, it cannot fill the array right?
Imma already confused thinking this, any suggestion, help, discussion ill appreciate it. Thanks.
If you just want to increment by one, and not any substraction or increment by let's say 5, I'd use a simple solution like this:
private void btnClick_Click(Object Sender, Event Args) {
int maxValue = 5;
int carry = 1; // This is our increment
// iterate through your digits back to front
for(int i = digit.Length - 1; i >= 0; i--) {
digit[i] += carry; // increase the value by the carry. This will at least increment the last digit by one
carry = 0;
// if we reach our max value, we set the carry to one to add it to the next digit, and reset our current digit to 0.
// If you wanted to increase by more than 1 a time, we would have to add some more calculations here as it would
// be incorrect to just reset digit[i] to 0.
if(digit[i] >= maxValue) {
carry = 1; // the next digit will now be told to increase by one - and so forth
digit[i] = 0;
} else {
break; // This will break out of the for - loop and stop processing digits as everything just fit nicely and we don't have to update more previous digits
}
}
}
Not that once you reach 44444 and increment, you will end up with 00000.
Related
I'm new to C# and i would really need your help with a project.
The idea is to ask the user for 10 numbers between 1-20. The numbers that the user enters are stored in an array. In the next phase a random number i generated and then the program compare all the numbers that the user previously entered with the random number. If one of numbers matches the program write something like "You win!".
My current solution is okay and working but I want a better exception handling than the current one. Here is my problem:
As you can see in my code below I rely on a loop and try/catch to ensure that the user enters a valid number, but after testing several times I discovered that if you enter a valid input, let say the first time but not the second, the unvalid input is still sent to the for-loop and to the next index.
I want to ensure that the user enters a valid number and if not the for-loop would temporarily "pause" until the next VALID number is entered.
bool start = true; //Create a loop.
{
while (start == true)
{
try
{
for (int x = 0; x < vektor.Length; x++) //To fill my array.
{
Console.WriteLine("Enter a number between 1 and 20:");
vektor[x] = int.Parse(Console.ReadLine());
start = false;
}
}
catch
{
Console.WriteLine("Error, you need to enter a number!");
}
}
}
Make a method that asks the user a question and doesn't give an answer until it's valid:
public int Ask(string question, int lower, int upper){
while(true)
{
Console.WriteLine(question);
string input = Console.ReadLine();
bool valid = int.TryParse(input, out int inputInt); //valid is true if it was a number
valid = valid && inputInt >= lower && inputInt <= upper; //but also test was it in range?
if(valid)
return inputInt; //if not valid, repeat the question because the loop is infinite
}
}
valid will be true if the user enters a number, but if they entered 40 for a 1 to 20 range, then the second validity assessment is:
valid = true /*it was a number*/ && true /*40 is >= 1*/ && false /*40 is not <= 20*/
So valid becomes false. We can only escape the Ask() method, returning the valid number if valid is true, otherwise the loop goes round again
--
Now you can have a list of numbers, say you want 10, we can loop and add numbers to a list until we get 10:
List<int> numbers = new List<int>();
while(numbers.Count < 10)
{
int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
numbers.Add(validNumber);
}
You can do this as an array if you like:
int[] numbers = new int[10];
for(int x = 0; x<numbers.length; x++)
{
int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
numbers[x] = validNumber;
}
Because you know that the Ask method will never return unless the input is valid, so the loop "pauses"
Hello that is my homework from the course for begginers, and I have no idea how to take the first input i than the second, not the numbers typed but the simple i. e.g.
2
3
4
4
3
1
I want to separate them somehow. But with this code it only takes :
1
1
2
3
4
4etc..
And the source.
Console.Write("Enter number of the numbers: ");
int a = int.Parse(Console.ReadLine());
int[] numbers = new int[a];
int even = 1;
int odd = 1;
for (int i = 0; i < a; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
if (numbers[i] % 2 == 0)
{
even *= numbers[i];
}
else if (numbers[i] % 2 !=0)
{
odd *= numbers[i];
}
}
Console.WriteLine(odd);
Console.WriteLine(even);
The way your application is written, it expects a single number to be entered (followed by the Enter key) indicating how many numbers in total will be read.
Then, it loops that many times, expecting a single number (followed by the Enter key) to be input for each loop.
That should be fine and work well. However, if you want to enter all of the numbers at once, you will need to restructure things a bit.
You don't need numbers to be an array. You never reference the value after you store it. You can use just an integer.
You are multiplying your count rather than adding it, e.g.
even *= numbers[i];
should be
even++;
if you want to count the number of even numbers, or
even += numbers[i];
if you want to sum them.
Same for tracking the odd number count.
Hi I have been told to "Write code that determines if a value, say “5”, is contained in the array from task 7(a random array) by going backwards through the array starting at the end and comparing the search value with the values in the array. After the search, if the value is found print “The value has been found” otherwise print “The value has not been found”."
I understand the creation of the random array but I am stuck on how to work backwards through it and locate the specific value.
Here is the code so far
class Program
{
static void Main(string[] args)
{
int[] myArray = new int[10];
Random rand = new Random();
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = rand.Next(19);
}
}
}
}
Use the loop starting from largest to smallest index.
bool found = false;
for (int i = myArray.Length - 1; i >=0 ; i--)
if(myArray[i] == 5)
found = true;
if(found)
{
}
else
{
}
To go backward just use a for loop with the iterator to i--.
for (int i = myArray.Length - 1; i >= 0; i---)
{
if(// Check if myArray[i] equals the value to find)
{
// If it is the case, you can get out from the for loop with break
break;
}
}
The for loop is splitted in 4 parts:
for (initializer; condition; iterator)
body
The initializer is executed before the first iteration in the loop (here you want to start at the last index in the array : myArray.Length - 1)
The condition is evaluated for each iteration, if this condition is true then it goes to 3 (you want to stay in the for loop while i >= 0) otherwise it quit the for loop
The body is executed for each iteration that satisfy the condition
The iterator is executed (here as you want to go backward you want to decrease i)
Then it go back to 2
the code below belongs to binary search algorithm,user enter numbers in textbox1 and enter the number that he want to fing with binarysearch in textbox2.i have a problem with it,that is when i enter for example 15,21 in textbox1 and enter 15 in textbox2 and put brakpoint on the line i commented below,and i understood that it doesnt put the number in textbox2 in searchnums(commented),for more explanation i comment in code.thanks in advance
public void button1_Click(object sender, EventArgs e)
{
int searchnums = Convert.ToInt32(textBox2.Text);//the problem is here,the value in textbox2 doesnt exist in searchnums and it has value 0.
int result = binarysearch(searchnums);
MessageBox.Show(result.ToString());
}
public int binarysearch(int searchnum)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first =0;
int last = nums.Length-1;
while (1<= nums.Length)
{
int mid = (int)Math.Floor(first+last / 2.0);
if (first > last)
{
break;
}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
return nums[mid];
}
}
return -1;
}
First, when you know you can place a breakpoint on a line, you sure know you can step through the whole program and see what values are in each variable or property. So, go ahead, and debug. Among other things you are probably missing data input validation in your program.
Second, your binary search implementation is missing mid recalculation after first or last is updated and a stop condition in case the number being looked for is not found in the array. You have to break the loop in case first == last, regardless if nums[mid] matches or not — nobody said the number from textbox2 must be in the array.
What does it have to do with binary search? The problem seems to be that you can't read the number out of a textbox. Are you sure it's the right textbox? What is it's Text? Also, if you put the breakpoint ON the line that assigns the value to searchnums, it will be 0, because it hasn't been assigned yet, put the breakpoint on the line AFTER.
OK, first of all, I hope you know that binary search won't work if nums isn't sorted.
That said, there are a few problems in the algorithm. First of all, you're not changing any of the key elements in the loop. You're only changing first and last in the loop and they aren't even used there, so the loop's state doesn't change.
So i guess you meant to have this line in the beginning of the loop:
mid = (first +last)/2;
Besides that, you need to check for the very likely event that the number doesn't exist. which means adding this in the beginning of the loop to:
if (last < first) break;
Which of course means that the first point of the array block has passed the last point, which means the block size is negative. first == last may be legal when you get to the last cell in the array.
And the last point is to initiate last as size-1:
int last = nums.Length - 1;
We're talking about array indexes after all.
I have a coding/maths problem that I need help translating into C#. It's a poker chip calculator that takes in the BuyIn, the number of players and the total amount of chips for each colour (there are x amount of colours) and their value.
It then shows you every possible combination of chips per person to equal the Buy In. The user can then pick the chipset distribution they would like to use. It's best illustrated with a simple example.
BuyIn: $10
Number of Players: 1
10 Red Chips, $1 value
10 Blue Chips, $2 value
10 Green Chips, $5 value
So, the possible combinations are:
R/B/G
10/0/0
8/1/0
6/2/0
5/0/1
4/3/0
2/4/0
1/2/1
etc.
I have spent a lot of time trying to come up with an algorithm in C#/.NET to work this out. I am stumbling on the variable factor - there's usually only 3 or 4 different chips colours in a set, but there could be any amount. If you have more than one player than you have to count up until TotalChips / NumberOfPlayers.
I started off with a loop through all the chips and then looping from 0 up to NumberOfChips for that colour. And this is pretty much where I have spent the last 4 hours... how do I write the code to loop through x amount of chips and check the value of the sum of the chips and add it to a collection if it equals the BuyIn? I need to change my approach radically methinks...
Can anyone put me on the right track on how to solve this please? Pseudo code would work - thank you for any advice!
The below is my attempt so far - it's hopeless (and wont compile, just an example to show you my thought process so far) - Might be better not to look at it as it might biased you on a solution...
private void SplitChips(List<ChipSuggestion> suggestions)
{
decimal valueRequired = (decimal)txtBuyIn.Value;
decimal checkTotal = 0;
ChipSuggestion suggestion;
//loop through each colour
foreach (Chip chip in (PagedCollectionView)gridChips.ItemsSource)
{
//for each value, loop through them all again
foreach (Chip currentChip in (PagedCollectionView)gridChips.ItemsSource)
{
//start at 0 and go all the way up
for (int i = 0; i < chip.TotalChipsInChipset; i++)
{
checkTotal = currentChip.ChipValue * i;
//if it is greater than than ignore and stop
if (checkTotal > valueRequired)
{
break;
}
else
{
//if it is equal to then this is a match
if (checkTotal == valueRequired)
{
suggestion = new ChipSuggestion();
suggestion.SuggestionName = "Suggestion";
chipRed.NumberPerPlayer = i;
suggestion.Chips.Add(chipRed);
chipBlue.NumberPerPlayer = y;
suggestion.Chips.Add(chipBlue);
chipGreen.NumberPerPlayer = 0;
suggestion.Chips.Add(chipGreen);
//add this to the Suggestion
suggestions.Add(suggestion);
break;
}
}
}
}
}
}
Here's an implementation that reads the number of chips, the chips (their worth and amount) and the buyin and displays the results in your example format. I have explained it through comments, let me know if you have any questions.
class Test
{
static int buyIn;
static int numChips;
static List<int> chips = new List<int>(); // chips[i] = value of chips of color i
static List<int> amountOfChips = new List<int>(); // amountOfChips[i] = number of chips of color i
static void generateSolutions(int sum, int[] solutions, int last)
{
if (sum > buyIn) // our sum is too big, return
return;
if (sum == buyIn) // our sum is just right, print the solution
{
for (int i = 0; i < chips.Count; ++i)
Console.Write("{0}/", solutions[i]);
Console.WriteLine();
return; // and return
}
for (int i = last; i < chips.Count; ++i) // try adding another chip with the same value as the one added at the last step.
// this ensures that no duplicate solutions will be generated, since we impose an order of generation
if (amountOfChips[i] != 0)
{
--amountOfChips[i]; // decrease the amount of chips
++solutions[i]; // increase the number of times chip i has been used
generateSolutions(sum + chips[i], solutions, i); // recursive call
++amountOfChips[i]; // (one of) chip i is no longer used
--solutions[i]; // so it's no longer part of the solution either
}
}
static void Main()
{
Console.WriteLine("Enter the buyin:");
buyIn = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the number of chips types:");
numChips = int.Parse(Console.ReadLine());
Console.WriteLine("Enter {0} chips values:", numChips);
for (int i = 0; i < numChips; ++i)
chips.Add(int.Parse(Console.ReadLine()));
Console.WriteLine("Enter {0} chips amounts:", numChips);
for (int i = 0; i < numChips; ++i)
amountOfChips.Add(int.Parse(Console.ReadLine()));
int[] solutions = new int[numChips];
generateSolutions(0, solutions, 0);
}
}
Enter the buyin:
10
Enter the number of chips types:
3
Enter 3 chips values:
1
2
5
Enter 3 chips amounts:
10
10
10
10/0/0/
8/1/0/
6/2/0/
5/0/1/
4/3/0/
3/1/1/
2/4/0/
1/2/1/
0/5/0/
0/0/2/
Break the problem down recursively by the number of kinds of chips.
For the base case, how many ways are there to make an $X buy-in with zero chips? If X is zero, there is one way: no chips. If X is more than zero, there are no ways to do it.
Now we need to solve the problem for N kinds of chips, given the solution for N - 1. We can take one kind of chip, and consider every possible number of that chip up to the buy-in. For example, if the chip is $2, and the buy-in is $5, try using 0, 1, or 2 of them. For each of these tries, we have to use only the remaining N - 1 chips to make up the remaining value. We can solve that by doing a recursive call, and then adding our current chip to each solution it returns.
private static IEnumerable<IEnumerable<Tuple<Chip, int>>> GetAllChipSuggestions(List<Chip> chips, int players, int totalValue)
{
return GetAllChipSuggestions(chips, players, totalValue, 0);
}
private static IEnumerable<IEnumerable<Tuple<Chip, int>>> GetAllChipSuggestions(List<Chip> chips, int players, int totalValue, int firstChipIndex)
{
if (firstChipIndex == chips.Count)
{
// Base case: we have no chip types remaining
if (totalValue == 0)
{
// One way to make 0 with no chip types
return new[] { Enumerable.Empty<Tuple<Chip, int>>() };
}
else
{
// No ways to make more than 0 with no chip types
return Enumerable.Empty<IEnumerable<Tuple<Chip, int>>>();
}
}
else
{
// Recursive case: try each possible number of this chip type
var allSuggestions = new List<IEnumerable<Tuple<Chip, int>>>();
var currentChip = chips[firstChipIndex];
var maxChips = Math.Min(currentChip.TotalChipsInChipset / players, totalValue / currentChip.ChipValue);
for (var chipCount = 0; chipCount <= maxChips; chipCount++)
{
var currentChipSuggestion = new[] { Tuple.Create(currentChip, chipCount) };
var remainingValue = totalValue - currentChip.ChipValue * chipCount;
// Get all combinations of chips after this one that make up the rest of the value
foreach (var suggestion in GetAllChipSuggestions(chips, players, remainingValue, firstChipIndex + 1))
{
allSuggestions.Add(suggestion.Concat(currentChipSuggestion));
}
}
return allSuggestions;
}
}
For some large combinations this is propably not solvable in finite time.
(It is a NP problem)
http://en.wikipedia.org/wiki/Knapsack_problem
There are also links with Code? that could help you.
Hope this helps a bit.