I am fairly new to this and trying to learn. I am struggling trying to make a loop to find the max value in an array. I am not sure what I am doing wrong. I have searched everywhere and seen several people do it the way i am but do not know what i am missing…
static void Main(string[] args)
{
int[] Numbs = new int[10];
Numbs[0] = 56;
Numbs[1] = 77;
Numbs[2] = 23;
Numbs[3] = 12;
Numbs[4] = 88;
Numbs[5] = 59;
Numbs[6] = 97;
Numbs[7] = 33;
Numbs[8] = 38;
Numbs[9] = 64;
string[] Names = new string[10] {"John", "George", "Henry", "Larry", "Bart", "Luke", "Tim",
"Frank", "Conor", "Joe"};
FindMax(Numbs[9],9);
}
static int FindMax(int arrayNumbs, int arrayNumbsLength)
{
int Greatest = -1;
for (int Count = 0; Count <= arrayNumbsLength; Count++)
if (arrayNumbs[Count] > Greatest)
{
Console.WriteLine(Count);
Greatest = arrayNumbs;
Console.WriteLine(Greatest);
}
return Greatest;
The most basic change would be:
static int FindMax(int[] arrayNumbs)
{
...
for (int Count = 0; Count < arrayNumbs.Length; Count++)
...
}
The rest is just fine. There are some ways to make it better, but I'm guessing this is a school assignment and you'll get there eventually.
I can see few things that are issues with your code:
Your method defines first parameter as an integer (int arrayNumbs), it should say int[] arrayNumbs since you're passing an array, not a single integer
in your function call FindMax(Numbs[9], 9) you pass an integer as the first argument instead of an array (which didn't give you an error since it's how you defined the method, see above). Second argument is a lie, your array's size is 10, not 9 (remember about first element having index [0])
Inside your method you want to assign the integer to your variable, not the whole array (which would give you an error). Should say Greatest = arrayNumbs[Count]
You can use a List() instead of the array type. A list is dynamic and will expand automatically. In the example below I create the numbs list and use LINQ to get the max value.
var numbs = new List<int>
{
56, 77, 23, 12, 88, 59, 97, 33, 38, 65
};
var max = numbs.Max();
Related
Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
I am writing code for Merge sort, I use object arrays with lists which are then sorted and merged, I know it's a bit strange and there is probably a better way to do it. When I recurse back to function in the code below, there a more elements than there should be, and I just don't get why it happens.
public static void RecurseSort(Array arr)
{
Array ForWork = arr;
if (ForWork.Length == 1)
{
MessageBox.Show("recurs finish");
}
else
{
List<object> ForRecurse = new List<object>();
Array arrCopy = new object[ForWork.Length / 2];
for (int i = 0; i < ForWork.Length - 1; i = i + 2)
{
List<int> r1 = (List<int>)ForWork.GetValue(i);
List<int> r2 = (List<int>)ForWork.GetValue(i + 1);
if (i == ForWork.Length - 3)
{
List<int> r3 =
(List<int>)ForWork.GetValue(ForWork.Length - 1);
r2.Add(r3[0]);
}
ForRecurse.Add(CompareAndMerge(r1, r2));
}
arrCopy = ForRecurse.ToArray();
RecurseSort(arrCopy);
}
}
So the arrCopy has the correct number of elements but literally when I press 'continue' in the visual studio debbuger, arr[3] has count of 3, when it should have been 2.
Divide and conquer - split it to smaller problems and solve them.
Copy
How do you copy data from array A to array B, for example what will be the result of:
int[] src = { 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270 };
int[] dest = { 17, 18, 19, 20 };
int length = 2;
Array.Copy(src, 4, dest, 2, length);
Arithmetics
How do you divide array to 2 - divide by 2, but if the size is uneven ex: 7, what will be the result of:
var length = 7;
var result = length / 2;
Type constraints
var length = 7d;
var result = length / 2;
Merging 2 sorted array
In merge sort you use another sort, for example insertion sort if you have only few elements left, ex: 20. So if you are given following insertion sort, how do you split array of 37 random numbers to 2 partisions, sort them and merge them.
static class InsertionSort<T> where T : IComparable {
public static void Sort(T[] entries, Int32 first, Int32 last) {
for (var index = first + 1; index <= last; index++)
insert(entries, first, index);
}
private static void insert(T[] entries, Int32 first, Int32 index) {
var entry = entries[index];
while (index > first && entries[index - 1].CompareTo(entry) > 0)
entries[index] = entries[--index];
entries[index] = entry;
}
}
In addition, debugger is your friend.
It is difficult to say as you did not provide the full text of the working example. But I suspect that you keeping references to objects in the array when you should not.
But most importantly I suggest you rewrite your code so it does not use casts. Try using List of List - List<List<int>> - it will be strongly typed and clear your algorithm. Also, I suggest writing it for concrete type to sort - int and later moving to Generic implementation with your method that will accept type <T> to sort.
I want to combine an integer array to a single integer value. So I have the following code that will combine the array to a single value.
int[] array = { 5, 6, 2, 4 };
int combine = 0;
for (int i = 0; i < array.Length; i++)
{
combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
this yield combine = 5624. Which is correct.
My issue is my array is not in the form of 0-9. So my array could be {51,62,23,44}
int[] array = { 51, 62, 23, 44 };
int combine = 0;
for (int i = 0; i < array.Length; i++)
{
combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
yielding combine as 574774, not 51622344. How would I correct this?
Do the following:
var number = int.Parse(string.Join("", array));
Explanation:
string.Join will take any enumeration of type T, call ToString() on each member and join them in a single string with the specified separator.
Once you have a string representing your number, you simply parse it to get the number itself.
Of course this is not safe and depending on your possible inputs, this could fail: {1, 4, -5, 4 }. Some error detection and int.TryParse is probably the best way to solve this, the example is simply to get the idea across.
Why not convert them to strings and then concatenate?
using System;
public class Program
{
public static void Main()
{
int[] intArray = { 5, 6, 2, 4 };
var result = string.Concat(intArray);
Console.WriteLine(result);
try {
int resultNumber = int.Parse(result);
}
catch(OverflowException) {
// this can occur if you exceed the maximum value of an int
long resultBigNumber = long.Parse(result);
}
}
}
Try using a StringBuilder, like this:
using System;
using System.Text;
public class Program {
public static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
int[] array = new Int[] { 51, 62, 23, 44 };
int combine = 0;
foreach(int single in array) {
string oneNum = single.ToString();
sb.Append(oneNum);
}
string final = sb.ToString();
combine = Convert.ToInt32(final);
}
}
This will convert the numbers in the array into a string, which then gets converted into a number.
Linq and some simple math can help here (without strings or Math.Pow). I'm also going to seed it with numbers of widely varying magnitude (i.e., not all single digit numbers or all 2-digit numbers). First some preliminary code:
private readonly int[] PowersOf10 = new [] {10, 100, 1000, 10000, 100000};
private int DecimalShiftAccumulate(int numToShift, int numToAdd)
{
var nextPowerOf10 = PowersOf10.First(x => x > numToAdd);
return (numToShift * nextPowerOf10) + numToAdd;
}
You can include more numbers in the PowersOf10 array; I got tired of counting zeros.
Then declare your int array and calculate the result:
var intArray = new[] { 1051, 7, 923, 44 };
var arrayResult = intArray.Aggregate((a, b) => DecimalShiftAccumulate(a, b));
I get arrayesult = 1051792344 (i.e. (using & as concatenation) 1051 & 7 & 923 & 44)
I have an array initialized as such:
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
I then have a for() loop searching the array for the highest value each time using:
int maxValue = myArray.Max();
int maxIndex = myArray.ToList().IndexOf(maxValue);
It obviously keeps finding 9 as the highest value.
I want it to first set the previously indexed value to a randomized value below the current maxValue but above -1 and continue searching the array for the next maxValue and print it to console.
(If all values reach a value == 0 then the simulation stops) <- this part I know how to do.
Is this possible? If so, how?
I guess this might be what you want. Let me know how it works for you.
using System;
using System.Linq;
public class Program
{
private static Random random = new Random();
public static void Main()
{
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
Simulate(myArray);
}
static void Simulate(int[] myArray)
{
int maxValue = myArray.Max();
Console.WriteLine(string.Join(" ",myArray));
var continueSimulation = true;
do{
int maxIndex = myArray.ToList().IndexOf(maxValue);
var randomValue = random.Next(0, maxValue);
myArray[maxIndex] = randomValue;
maxValue = myArray.Max();
if (maxValue == 0)
continueSimulation = false;
Console.WriteLine(string.Join(" ",myArray));
}while(continueSimulation);
}
}
You can check it out on this fiddle.
Hope this helps!
If you want to find the second max, you can mark the position of the first one and continue with your same approach. How can be done? 1- initialize an array of bool with the same length of the array where you want to find the max, then find the first max and mark that position in the second array with true, if you want the second max, make a loop through the array asking for the max and if that element is not marked in the second array of bool. Finally you will get the second max .
Another idea is taking the values in a list and once you find the max, remove the max from the list to continue with the same algorithm but with an array of less values
static int Max(int [] num)
{
int max = num[0];
for(int i = 0; i < num.Length; i ++)
{
if(num[i] > max)
max = num[i];
}
return max;
}
static int SecondMax(int[]a)
{
if(a.Length < 2) throw new Exception("....");
int count = 0;
int max = Max(a);
int[]b = new int[a.Length];
for(int i = 0; i < a.Length; i ++)
{
if(a[i] == max && count == 0)
{
b[i] = int.MinValue;
count ++;
}
else b[i] = a[i];
}
return Max(b);
}
Honestly, the question feels a bit unusual, so if you share why you're trying to do this, maybe someone could suggest a better approach. However, to answer your original question, you can just use .NET's random number generator.
int[] myArray = new int[] { 9, 8, 7, 3, 4, 5, 6, 2, 1 };
Random random = new Random();
for (int max = myArray.Max(); max > 0; max = myArray.Max())
{
int index = myArray.IndexOf(max);
DoSomething(max);
myArray[index] = random.Next(0, max);
}
From the MSDN doco on Random, the upper bound is exclusive, which means that it will generate a random number between 0 and max-1, unless max==0, in which case it will return 0.
I am using C# and i am trying to find the the average of 5 values but i can only use 2 variables.
How can you input 5 integers into one variable and display the average of said integers
You can use List like this:
var list = new List<int>(){ 1, 2, 3, 4, 5 };
var average = list.Average();
using Average you'll get average of all values in list
Here you have all functions of Enumerable, you can for e.g. sum all values with Sum
Use a collection like a List<int> and the extension method Enumerable.Average:
List<int> numbers = new List<int>{ 10, 20, 30, 40, 50 };
double average = numbers.Average(); // 30.0
Use List.Add to add single integers:
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// ...
Take the input values in a Integer list or array then use the following code
List<int> intlist=new List<int>();
intlist.Add(2);
intlist.Add(3);
..
..
var average= intlist.Average();
Using Average will computes the average of a sequence of all the integers in the list.
UPDATE: or if the case is to use integers only then you need to use the following code (Remember to validate the readline() entries)
public decimal Average()
{
int value = 0;
for(int i=0;i<5;i++)
{
value+=ConvertToInt32(Console.ReadLine());
}
return value/5;
}
What about using array? I think array is one variable in your case
int[] input = new int[5];
input[0] = 5;
input[1] = 40;
input[2] = 15;
input[3] = 50;
input[4] = 25;
int sum = 0;
foreach(int i in input)
{
sum = sum + i;
}
sum = sum / input.Length;
Console.WriteLine(sum.ToString());
#up Yeah that's better way!
You dont need arrays, or lists or anything remotely similar. Pseudo-code:
private int sum = 0;
private int count = 0;
while (user inputs valid number)
{
sum += userInput;
count++;
}
return sum / count;
Only two variables.
If you just want solution without List<int> then here it is
int[] arr=new int[5];
arr[0]=10;arr[1]=20;...arr[4]=50;
int sum=0;
foreach(int x in arr)
{
s+=x;
}
s=s/arr.Length;//s is average
If you want list
List<int> list = new List<int>(){ 1, 2, 3, 4, 5 };
var average = list.Average();