Combination by using factorial function method - c#

I cannot combinate 20 and 17, the program says that the result is 1. Why?? I'm sure my code is right but i just cannot combinate big numbers.
using System;
namespace question
{
class beat_That
{
static int Factorial(int m)
{
int result = 1;
for (int i = 1; i <= m; i++)
{
result *= i;
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine("enter number of objects in the set: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter number to be chosen: ");
int k = Convert.ToInt32(Console.ReadLine());
int combination = Factorial(n) / (Factorial(n - k) * Factorial(k));
Console.WriteLine("C(" + n + ", " + k + ") = " + combination);
Console.ReadKey();
}
}
}

I'm guessing this is a homework assignment? Here are some tips that will hopefully get you going in the right direction:
(1) Typically, .NET classes are Pascal Case, so for example: comb should be Comb. Also, it's better to assign descriptive class names instead of short abbreviations. For clarity I'm going to assume you at least rename comb to Comb so it isn't confused with a variable name, but another option might be Calculator for example.
(2) Check your syntax and any compiler errors. For example, the compiler should be complaining about this line of code:
Console.WriteLine("the combination of {0} and {1} is {2}. "),a1,b1,;
(3) Your methods Factorial and Combination are static methods (as opposed to instance methods). This changes how you call these methods. Static methods are called without an instance, for example: Comb.Combination(..)
(4) Make sure you test various inputs! Your implementation of Combination is not quite correct, but I'll leave that as an exercise to figure out why.

Related

Trying to fix counting in c#

So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!

c# Roll Dice simulation to return how many times every side landed

My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}

C# Get NZEC error parsing input on HackerEarth

I want to learn C# so I started to use hackerearth and solve problems from their website but I got into some kind of problem. So I have the following code
using System;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
long N, i, answer = 1;
do
{
N = Convert.ToInt32(Console.ReadLine());
} while (N < 1 && N > 1000);
long[] A = new long[N];
for (i = 0; i < N; i++)
{
do
{
A[i] = Convert.ToInt32(Console.ReadLine());
} while (A[i] < 1 && A[i] > 1000);
}
for(i = 0; i < N; i++)
{
answer = (answer * A[i]) % (1000000007);
}
Console.WriteLine(answer);
}
}
}
When I compile it I get the correct answer and everything it's fine but when I submit it to hackerearth compiler it gives me the NZEC error. I thought I'm missing something since I just started C# some days ago so I wrote it again but in C++ and it gave me the maximum score on the website. I know that there might be some problems in my variable declarations since I didn't understand exactly how to read numbers and I hope you can help me solve this problem. Thank you!
Assuming you are stuck on the Find Product problem, as you've suspected, the input of the data is one line for N, and then one line for ALL N numbers that you need to multiply, separated by a space. You can parse the line of numbers quickly with LINQ (I would suggest you get stuck into LINQ as quickly as possible - this will get you away from the C++ imperative mindset).
How about:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
var N = Convert.ToInt32(Console.ReadLine()); // Less than 2^31 integers to be read
var A = Console.ReadLine() // Read the line of space delimited numbers
.Split(' ') // Split out by the separator
.Select(n => Convert.ToInt64(n)) // Parse each number to long
.ToArray(); // Convert to a materialized array
Debug.Assert(A.Length == N, "Site lied to us about N numbers");
long answer = 1; // or var answer = 1L;
for(var i = 0; i < N; i++)
{
answer = (answer * A[i]) % (1000000007);
}
Console.WriteLine(answer);
}
}
}
Some notes:
The do..while has no effect - they will always exit after one pass - this because a value cannot be < 1 and > 1000 simultaneously
Note that Convert.ToInt32 parses a 32 bit int. You've defined a long (which is ALWAYS 64 bit in C#, unlike C++), so this should be Convert.ToInt64
The problem does however constrain A[i] under 10 ^ 3, so A[] can be int[], although the product could be larger, so long or even System.Numerics.BigInteger can be used for the product.
NZEC is a site specific error - it means the app crashed with a non zero process ecit code. The site also prints the actual error and stack trace further down the page.
Since you say you want to learn C# (and not just convert C code to C#), you can also LINQify the final for loop which calculates the answer from the array using .Aggregate. Aggregate supports both a seeded overload (i.e. a left fold, as it allows the return type to differ), and an unseeded overload (i.e. reduce where the return type must be the same as the input enumerable). In your case, you don't actually need to seed the answer with 1L since it can be seeded with A[0] and the next multiplication will be with A[1] since any number multiplied by 1 will be number.
var answer = A.Aggregate((subtotal, next) => (subtotal * next) % (1000000007));

Creating a c# function to compare int results

This will be so easy for some of you programming geniuses out there but I am a student who recently began learning about C# (and programming in general) and I find myself.... stuck.
This is an assessment I am working on so I am not looking for a copy/paste answer, it would be preferable if I could find out where I am going wrong/where to start so I can fix it myself.
The aim of the assessment is to:
use the random number generator to generate 4 numbers - 2 for player 1 and 2 for the dealer.
Add players 2 numbers together, add dealers 2 numbers together (show results on screen)
this is where I become stuck...
I need to create a function that basically says:
If DealerResult is > PlayerResult display: Dealer Wins.
If PlayerResult > DealerResult, display: You win.
If DealerResult == PlayerResult display: it is a draw.
So far I have the following code. As you will see, I can generate the numbers, add them together and display the results on screen.
using System;
namespace Assessment
{
class MainClass
{
public static void Main (string[] args)
{
//Decalre Variables
Random r = new Random ();
int PlayerNumber1 = r.Next (6, 25);
int PlayerNumber2 = r.Next (6, 25);
int DealerNumber1 = r.Next (6, 25);
int DealerNumber2 = r.Next (6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine ("Welcome!");
Console.ReadLine ();
Console.WriteLine ("Your total is: " + PlayerTotal);
Console.ReadLine ();
Console.WriteLine ("Dealer total is: " + DealerTotal);
Console.ReadLine ();
}
}
}
From here, I am stuck. Suggestions would be so appreciated as to how I should proceed to compare the numbers and display the appropriate result/s through a function.
As mentioned earlier, this is an assessment so I am not looking for a quick fix or final answer. Also, the assessment requires the use of a FUNCTION to generate the result, not a loop or any other type of programming magic that some of you super-geniuses may be aware of. (And I say that with envy - I wish I was half as smart as some of the people I see posting on here). :)
You just need simple if statements, and put them into a function:
private static void DisplayResult(int playerTotal, int dealerTotal)
{
if(playerTotal > dealerTotal)
{
Console.WriteLine("You win!");
}
else if(playerTotal < dealerTotal)
{
Console.WriteLine("Dealer wins!");
}
else
{
Console.WriteLine("Draw!");
}
}
Explanation: We create a function that takes two int parameter.One of them is playerTotal, another is dealerTotal.The function compare these values and display the proper result in the console according to this comparison.After you create your function all you need to do is pass PlayerTotal and DealerTotal variables to your function like this:
DisplayResult(PlayerTotal, DealerTotal);
Note: You should put this method into MainClass
To start you will need a function. Functions look like this:
<access modifier> <return type> <Name> ( <parameters> )
{}
A quick example:
private bool GetResult (int playerValue, int dealerValue)
{
}
What this means is that the function will return a bool, and it takes two int parameters.
To return nothing, return void. To call the function, use its name and pass the parameters inside the parenthesis:
bool result = GetResult(1, 2);
Now to do a comparison, we use the if statement:
if (<expression> <comparator> <expression>)
{}
Another quick example:
if (playerScore > dealerScore)
{
Console.WriteLine("Player wins!");
}
Which says, "If PlayerScore is greater than DealerScore, do what is inside the brace" (a print in this case).
I'm trying to explain the basics, instead of give an actual answer, as you requested. Please let me know if I can clarify anything better, and good luck learning programming in C#!
Another variation demonstrating function returning result as a string.
using System;
namespace Assessment
{
class MainClass
{
public static void Main(string[] args)
{
//Decalre Variables
Random r = new Random();
int PlayerNumber1 = r.Next(6, 25);
int PlayerNumber2 = r.Next(6, 25);
int DealerNumber1 = r.Next(6, 25);
int DealerNumber2 = r.Next(6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine("Welcome!");
Console.ReadLine();
Console.WriteLine("Your total is: " + PlayerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(DisplayResult(PlayerTotal, DealerTotal));
Console.ReadLine();
}
private static string DisplayResult(int playerTotal, int dealerTotal)
{
var result = "An unhandled exception has occured ";
if (playerTotal > dealerTotal)
{
result = "You win!";
}
else if (playerTotal < dealerTotal)
{
result = "Dealer wins!";
}
else
{
result = "Draw!";
}
return result;
}
}
}

I am getting this error when compiling my program. Operator " + " cannot be applied to operands of "System.Random" and "System.Random"

I am trying to generate random numbers for math problems. When the program is compiled the error Operator " + " cannot be applied to operands of type 'System.Random' and 'System.Random. I really dont know how to fix this error.
Random num1 = new Random(0);
Random num2 =new Random(0);
int rand;
Console.Write("What is");
Console.Write(num1);
Console.Write( " - ");
Console.Write( num2);
Console.Write( "?");
int answer = Console.Read();
if (num1 + num2 == answer) ERROR {
Console.Write(" Your are Correct!\n");
correctCount++;
}
else
Console.Write( "Your answer is wrong" );
Console.Write(num1);
Console.Write(" + ");
Console.Write(num2);
Console.Write("should be ");
Console.Write(num1 + num2); ERROR
count++;
}
}
}
}
Now i am able to compile the program without any errors, but it is not generating any numbers. Does anyone see what i may have donwe wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Jagtutor
{
[Activity(Label = "Addition")]
public class AdditionsActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
SetContentView(Resource.Layout.Second);
var label = FindViewById<TextView>(Resource.Id.screen3Label);
label.Text = Intent.GetStringExtra("ModuleData") ?? "Data not available";
{
int correctCount = 0;
int count = 0;
while (count < 10);
{
Random gen = new Random();
int num1 = gen.Next();
int num2 = gen.Next();
Console.Write("What is");
Console.Write(num1);
Console.Write( " - ");
Console.Write( num2);
Console.Write( "?");
int answer = Int32.Parse(Console.ReadLine());
if (num1 + num2 == answer) {
Console.Write(" Your are Correct!\n");
correctCount++;
}
else
Console.Write( "Your answer is wrong" );
Console.Write(num1);
Console.Write(" + ");
Console.Write(num2);
Console.Write("should be ");
Console.Write(num1 + num2);
count++;
}
}
}
}
}
You misunderstood the way Random is used: it is not a number, it is a class that can be used to generate random numbers.
Try this:
// Make a generator
Random gen = new Random();
// Now we can use our generator to make new random numbers like this:
int num1 = gen.Next();
int num2 = gen.Next();
Every time you call gen.Next() you get a new random number. If you would like the sequence of random numbers to be repeatable, pass a number (any number) to the constructor of the Random. Beware that every time you run your program the result will stay the same.
There are quite a few issues with the code snippet you pasted. I'd suggest (if you haven't already) investing in a decent beginning C# book. Generating random numbers, in fact, is one of the most popular "example programs" you find in those kinds of books. However, to get you started, here's some key points:
When you paste sample code to a site like this, make sure it is a short, self-contained, correct example. Even if we fix the compiler error in your code, there are several other issues with it, including unbalanced and/or missing braces. Start simple and build your example up until you get the error, then paste that code. Note that a good 75% of the time this will help you fix the error yourself. For example, if you removed the lines of code that did not compile, and just ran the first part, it would print out "What is System.Random - System.Random?", which should give you a pretty clear idea that your num1 and num2 are not what you thought they were.
As the rest of the answers here have pointed out, you have a fundamental misunderstanding of how the C# Random class works. (Don't feel bad, computer-generated "random numbers" make no sense to anyone until someone explains them to you.) The solution provided in those answers is correct: Random is a random number generator, and you need to call one of the Next functions on your instance to get an integer from it. Also, you usually will not want multiple instances of Random unless you actually want to produce the same random sequence more than once. The MSDN article has a very thorough example.
While not "wrong" per-se, you're not being very efficient with your console output. Console's read and write functions operate entirely on string objects, and they have built-in composite formatting capabilities. For example, your first few lines of code could be rewritten as:
var random = new Random();
var x = random.Next();
var y = random.Next();
Console.Write("What is {0} + {1}? ", x, y);
As I mentioned in my comment, Console.Read() is not the correct function to read in complete user input; it returns data a single UTF-16 character at a time. For example, if the user typed in 150 you would get 49, 53, and 48, in that order. Since you presumably want to allow the user to type in more than one digit at a time, you should instead called Console.ReadLine(), which returns the entire string, then convert that to an integer using Int32.Parse() or some similar function.
You are trying to add two random generators not random numbers, use this:
Random randomGenerator = new Random(0);
var num1 = randomGenerator.Next();
var num2 = randomGenerator.Next();
You need to call one of the overloads of Random.Next() http://msdn.microsoft.com/en-us/library/9b3ta19y.aspx to get the actual random number.

Categories