method to return largest integer c# - c#

I'm having trouble with this method return of the largest integer, compiler says no errors but it won't let me run it

I have no clear idea what you are asking for.. I think at one time you had code but it is now gone?
Anyway, here is a console example for making an array and displaying its max value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//Declare i
int i;
Console.WriteLine("Please enter 5 random numbers");
//Make some array
string[] numbers = new string[5];
for (i = 0; i < 5; i++)
{
Console.Write("\nEnter your number:\t");
//Storing value in an array
numbers[i] = Console.ReadLine();
}
//ta da your array is now completed.. lets see what is the largest..
var converted = numbers.Select(int.Parse);
int largest = converted.Max();
//ta da
Console.WriteLine("The largest number is..." + (largest));
}
}
}

Related

Lucky Dip Program

I was trying to make a lucky dip program where 6 random numbers,1-59, are chosen then printed out in an array. I managed to get this to work, however you needed to use an IndexOf method so that no same number was printed twice by checking if the new number is already in the array.
using System;
namespace LuckyDip
{
class Program
{
static void Main(string[] args)
{
int[] luckyNumbers = new int[6];
Random random = new Random();
for (int x = 0; x<6; x++)
{
num[x] = random.Next(1,59);
Console.WriteLine(num[x]);
}
Console.ReadLine();
}
}
}
It prints out numbers, but sometimes they are the same.
You state that you want to use IndexOf, but that method is used for strings (see docs). Your example has an int array so the solution below uses Contains. This solution adds a check within your loop and generates a new number if this number already exists within your array. If you really need to use IndexOf, create a string array and convert the numbers using String.valueOf(randomNumber)
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
int[] luckyNumbers = new int[6];
Random random = new Random();
for (int x = 0; x<6; x++)
{
int randomNumber = random.Next(1,59);
while (luckyNumbers.Contains(randomNumber))
{
randomNumber = random.Next(1,59);
}
luckyNumbers[x] = randomNumber;
Console.WriteLine(luckyNumbers[x]);
}
}
}
Another possible solution would be:
using System;
using System.Collections;
using System.Linq;
public class Program
{
public static void Main()
{
int arraySize = 6;
int[] luckyNumbers = Enumerable.Range(1,59).OrderBy(g => Guid.NewGuid()).Take(arraySize).ToArray();
for (int x = 0; x < luckyNumbers.Length; x++)
{
Console.WriteLine(luckyNumbers[x]);
}
}
}

Summing to an int variable from values of an event subcribed to in C#

I am not sure how to calculate a summation of numbers from an event that is subscribed to in C#.
I have created an int variable Summation1 and I am able to Console.Writeline() the value of Summation1, as well as the value of temp as temp is updated by the event.
Summation1 will always stay at 0 which is the value that it was initialized to. I would like Summation1 to have a running summation of the variable temp each time temp is updated (this will be later used to calculate an average of temp). The value of temp shows properly using Console.Writeline() but I am not sure how to get Summation1 to have the sum of all of the temp values up to that point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using tyllibrary;
using System.IO;
namespace SKTtest
{
class Program
{
static void Main(string[] args)
{
TYLSocket socket = new TYLSocket();
socket.Connect("188.2.2.112", 2800);
int Summation1 = 0;
socket.eventPool.Subscribe("flight", new EventHandler<flightArgs>((x, y) => Console.WriteLine(y.STR1.temp + " " + Summation1)));
socket.SubscribeEquip("gulfstream");
Console.ReadKey();
}
}
}
I did not understand exactly, but you can use the following code to calculate the average temperature. Total temperature divided by total the number of times the total temperature
static void Main(string[] args)
{
TYLSocket socket = new TYLSocket();
socket.Connect("188.2.2.112", 2800);
int Summation1 = 0;
int counter = 0;
socket.eventPool.Subscribe("flight", new EventHandler<flightArgs>((x, y) => {
counter++;
Summation1 += y.STR1.temp;
Console.WriteLine("average temp : " + (Summation1 / counter));
}));
socket.SubscribeEquip("gulfstream");
Console.ReadKey();
}

How can I pass an integer array to a method: Reflection C#

I am currently learning about Reflection in C#. I am calling 2 methods from a class using late binding. The first method (SumNumbers) works. The second method (SumArray) throws an exception saying "Parameter count mismatch". Can anyone kindly tell me how to pass an integer array to this method?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly1 = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType1 = executingAssembly1.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance1 = Activator.CreateInstance(calculatorType1);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod1 = calculatorType1.GetMethod("SumArray");
object[] arrayParams1 = new object[4];
arrayParams1[0] = 5;
arrayParams1[1] = 8;
arrayParams1[2] = 2;
arrayParams1[3] = 1;
int sum1;
//Call "SumArray" Method
sum1 = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams1);
Console.WriteLine("Sum = {0}", sum1);
Console.ReadLine();
}
}
}
Class containing the 2 methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectionWithLateBinding
{
public class Calculator
{
public int SumNumbers(int input1, int input2)
{
return input1 + input2;
}
public int SumArray(int[] input)
{
int sum = 0;
for (int i = 0; i < input.Length; i++)
{
sum += i;
}
return sum;
}
}
}
You're not passing an integer array to the reflected method, you're passing an object array with 4 integer values. This will cause reflection to want to find a method with 4 integer parameters. Instead, you want to pass the integer array as one of the values in your object array.
Change to this:
int[] numbers = { 5, 8, 2, 1 };
object[] arrayParams1 = { numbers };
I also want to point out that your Sum method isn't written correctly. You are just summing 0 to input.Length, and not the values present in the array.
You want
sum += input[i];
Finally, depending on why you want to do this, using dynamic in C# would be easier than using reflection and would ultimately result in the roughly the same type of exception scenarios (method not found on the object you are invoking the methods on).
dynamic calculatorInstance1 = Activator.CreateInstance(calculatorType1);
calculatorInstance1.SumArray(new int[] { 5,8,2,1 });
Edit, full working sample. The only thing I did was change your parameter array to my code above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly1 = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType1 = executingAssembly1.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance1 = Activator.CreateInstance(calculatorType1);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod1 = calculatorType1.GetMethod("SumArray");
int[] numbers = { 5, 8, 2, 1 };
object[] arrayParams1 = { numbers };
int sum1;
//Call "SumArray" Method
sum1 = (int)sumArrayMethod1.Invoke(calculatorInstance1, arrayParams1);
Console.WriteLine("Sum = {0}", sum1);
Console.ReadLine();
}
}
public class Calculator
{
public int SumArray(int[] input)
{
int sum = 0;
for (int i = 0; i < input.Length; i++)
{
sum += input[i];
}
return sum;
}
}
}

Finding the right value for amount of digits in binary numbers

I am trying to create a console application where the user inputs a base 10 number and the program outputs the number in binary.
I want to get the exact number of times to execute the for loop to get correct value (the value HERE in the code below).
I also have to reverse everything that the console is now outputting for everything to be correct but that I can do on my own later.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decimal_to_Binary
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
decimal Number = Decimal.Parse(NumberIn);
decimal[] Squared = new decimal[100];
for (int i = 0; i < HERE + 1; i++)
{
//Squared[i] = Math.Pow(2, i);
Squared[i] = 2 ^ i ;
if (Number == Squared[i])
{
Console.Write("1");
}
else
{
Console.Write("0");
}
}
Console.ReadKey();
}
}
}
A nice feature of logarithms is that they'll tell you the highest order bit (in the case of log2) or digit that is set for any number. You can use log2 to find out the highest order bit set and then shift the number repeatedly checking for the 0th bit and print the binary representation.
using System;
using System.Text;
namespace BinaryCount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
int Number = Int32.Parse(NumberIn);
double loopCount = Math.Log(Number, 2); // Log2 of a number will tell you the highest order bit that's set
StringBuilder s = new StringBuilder();
for (int i = 0 ; i < loopCount ; ++i)
{
if (Number % 2 == 1)
s.Append("1");
else
s.Append("0");
Number = Number >> 1;
}
StringBuilder done = new StringBuilder();
for (int i = s.Length - 1 ; i >= 0 ; i--)
{
done.Append(s[i]);
}
Console.WriteLine(done);
Console.ReadLine();
}
}
}

Bug when debugging code without breakpoints

Im getting a bug where i call for two ints to get randomly generated by the same method but they always return the same number when releasing the code in debug mode
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kortspil
{
public class Kort
{
public int FåKortNummer()//Get card number
{
System.Random KortNummer = new System.Random();
int kort = KortNummer.Next(1, 14);
ErKortTrukket(kort);//is drawn
return kort;
}
}
class Program
{
static void Main(string[] args)
{
Kort SpillerEt = new Kort();
Kort SpillerTo = new Kort();
int SpillerEtKort = SpillerEt.FåKortNummer();//random number 1
Console.WriteLine("Spiller et har trukket: " + SpillerEtKort.ToString());
int SpillerToKort = SpillerTo.FåKortNummer(); // random number 2
Console.WriteLine("Spiller to har trukket: " + SpillerToKort.ToString());
if (SpillerEtKort <= SpillerToKort)
{
Console.WriteLine("Spiller Et vandt denne runde");//player 1 won this round
}
else
{
Console.WriteLine("Spiller to vandt denne runde");//player 2 won this round
}
Console.WriteLine("Tryk Enter for at lukke...");
Console.ReadLine();
}
}
}
You're problem is that you are creating two different Random instances. By default, if you do not supply a seed number, the current time will be used as a seed. However, you're code is executing so quickly, that the same time is being used as a seed (because you're code is executing faster than the smallest resolution of the clock), so the number you receive is the same each time.
The best fix is to create only a single instance of Random. For example, you could change your code to:
public class Kort
{
public static System.Random KortNummer = new System.Random();
public int FåKortNummer()//Get card number
{
int kort = KortNummer.Next(1, 14);
ErKortTrukket(kort);//is drawn
return kort;
}
}

Categories