Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a List<int[]> that I populated by splitting an integer array into 4 groups. Now I need to get the difference of the two highest numbers in the array. I tried Array.Sort but I am stuck on how to continue.
What I have done so far?
public static void solution(int[] T)
{
List<int[]> splitted = new List<int[]>();//This list will contain all the splitted arrays.
int lengthToSplit = T.Length / 4;
int arrayLength = T.Length;
for (int i = 0; i < arrayLength; i = i + lengthToSplit)
{
int[] val = new int[lengthToSplit];
if (arrayLength < i + lengthToSplit)
{
lengthToSplit = arrayLength - i;
}
Array.Copy(T, i, val, 0, lengthToSplit);
splitted.Add(val);
}
//this is the part where I must get the difference between the two highest numbers in an integer array and put into another list.
foreach (int[] integerarray in splitted)
{
//get the difference of the two highest numbers per integer array and place it on another List<int>
}
}
get the difference between the two highest numbers in an integer array
and put into another list
You can use LINQ and Math.Abs:
List<int> differenceList = splitted
.Select(list => list.OrderByDescending(i => i).Take(2).ToArray())
.Select(highestTwo => Math.Abs(highestTwo[0] - highestTwo[1]))
.ToList();
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Let's say you have two numbers, 4 and 9. The numbers can't be less than 0 or more than 9.
I want to fill the gap between 4 and 9 with numbers in correct order like so:
456789
How does one exactly do so? I've been stuck on this problem for the past 2 hours.
Thank you.
I have tried putting the numbers into an array and using the array's length as a way to fill in the numbers.
I've tried numerous other things that I don't know how to explain.
Just create a loop and loop thru all the integers between your numbers and add each number to a string if that is your desired output:
string CreateNumberSequence(int start, int end){
var sb = new StringBuilder();
for(int i = start; i <= end; i++){
sb.Add(i.ToString());
}
return sb.ToString();
}
Note that 10-12 would produce 101112, so you might want to add some separator between numbers, or just create a list of numbers and do the formatting separatly. You could also use Enumerable.Range, but if you are new to programming it is useful to know how to use plain loops.
If you want a list of numbers, change StringBuilder to List<int>, remove all the .ToString() and change the return-type. Or just use the previously mentioned Enumerable.Range.
You can use Enumerable.Range
int start = 4, end = 10;
int[] range = Enumerable.Range(start, end - start + 1).ToArray();
// range: 4 5 6 7 8 9 10
You can use the range method. since you know the start and end of the sequence you can put the start as 4 and the difference to the end from counting all the way from start will be 6.
and for 10-12 it will be like
var number = Enumerable.Range(10, 3);
var number = Enumerable.Range(4, 6);
var result = string.Join("", number.Select(x => x.ToString()).ToArray());
With extension methods :
public static class Ext
{
public static bool ToIntValue(this IEnumerable<int> source, out int output)
{
string joinedSource = string.Join(string.Empty, source);
return int.TryParse(joinedSource, out output);
}
public static IEnumerable<int> NumbersBetween(this int start, int end)
{
if (start > 0 && end <= 9 && start <= end)
{
for (int i = start; i <= end; i++)
yield return i;
}
else
{
throw new ArgumentException("Start and end must be beetween 1 and 9 and end must be bigger than start.");
}
}
}
use case :
if (1.NumbersBetween(9).ToIntValue(out int result))
{
Console.WriteLine(result);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Hi I need to work out the average of 10 integers stored in a database.
This is what I've got so far.
private void getAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
average = 0;
int[] array;
for (int index = 0; index < 10 ; index++)
{
average += array[index];
}
average = average / 10;
averageBox.Text = average.ToString();
}
As you can see I have no idea what I'm doing... any pointers??
There are a couple of issues with your code, which I will address one by one:
You are always getting the data from row 11 of your data table (studentsDataSet.Students.Course[10]). That's probably not what you want.
You are declaring your array but you are not initializing it.
You need to fill the array before you loop over it.
You are repeating the number of courses (10) in many places in your code (e.g. the for loop and the divisor of the average). This will be a source of errors when the number of courses changes.
Be careful to choose good names for your variables. average should be sum (that's what it actually stores) and array is a poor choice, because it does not describe the content of the variable, but its format.
According to the C# naming convention methods are in PascalCase.
Here is some code that will do the job. I have added comments to explain exactly what is happening:
//The method that will add the average to the text box. You need to provide the row index.
//One common way to get the row index would be the SelectedIndex of your data grid
private void GetAverage(int rowIndex)
{
//Get the row whose data you want to process
DataRow courseMarks = studentsDataSet.Students.Rows[rowIndex];
//Initialize an array with the names of the source columns
string[] courseColumnNames = { "Course1", "Course2", "Course3", "Course4", "Course5",
"Course6", "Course7", "Course8", "Course9", "Course10" };
//Declare and initialize the array for the marks
int[] markValues = new int[courseColumnNames.Length];
//Fill the array with data
for (int index = 0; index < courseMarks.Length ; index++)
{
//Get the column name of the current course
string columnName = courseColumnNames[index];
//Copy the column value into the array
markValues[index] = (int)courseMarks[columnName];
}
//Calculate the sum
int sum = 0;
for (int index = 0; index < courseMarks.Length ; index++)
{
sum += markValues[index];
}
//Calculate the average from the sum
//Note: Since it's an integer division there will be no decimals
int average = sum / courseMarks.Length;
//Display the data
averageBox.Text = average.ToString();
}
Note that of course you could merge the two loops into one (and even drop the array, since you could just directly add to the sum variable). I have not done that to keep every step of the process clearly separated. You could also use the LINQ method Average, but that would quite miss the point here.
Instead of all your codes, you may try this:
private double GetAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
var average=courseMarks.Average(x =>(double) x["*YourDataColumnName*"]);
return average;
}
Where YourDataColumnName is the column of your row which contains the value you want to get average of that
You could do the following :
int average = studentsDataSet.Students.Course.Average();
You would have to add using System.Linq; for this to work.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am writing the beginning of my program which is to have the computer generate 3 random numbers on the console.
They need to be 1-9 (including both), no numbers can repeat, and I need to put this answer into an array. What's needed in the main method class vs the class.
You should try it out yourself first (site rules say so), but some hints may be provided:
1) integer random numbers can be generated using Random class. More details can be found here and an answer has been already provided about generation
2) to avoid duplicates each number should be tested against the existing list of numbers:
array.Contains(generatedNumber)
3) For your particular request, an elegant option is to generate all numbers between 1 and 9, shuffle the array and pick the first three elements:
var initArray = Enumerable.Range(1, 9).ToArray();
var randomArray = initArray.OrderBy(x => rnd.Next()).ToArray();
Get first three elements and those are random and distinct.
Generally, you can a subarray using the method specified here.
Try this:
Random rnd = new Random();
int[] arr = Enumerable.Range(0, 10).OrderBy(n => rnd.Next()).Take(3).ToArray();
foreach (var n in arr)
{
Console.WriteLine(n);
}
Try this code below :
//range set 0 to 9
int Min = 0;
int Max = 10;
//declare an array which store 3 random number
int[] arr = new int[3];
Random randNum = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = randNum.Next(Min, Max);
Console.WriteLine(arr[i]);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
C# beginner here...
I have
int[] numbers = new int[10];
I would like to add 50 numbers to this array. Once the array is full, the first added number will be removed and the new number will be added. I would like to display the last added number on the top of the array. Such as
[5,4,3,2,1...]
not
[1,2,3,4,5,...]
How can I achieve this?
Thanks in advance
This is what I have tried
....
dataArray = new int[10];
....
Queue<int> numbers = new Queue<int>();
....
if (numbers.Count == 10)
{
numbers.Dequeue();
}
numbers.Enqueue(i);
numbers.CopyTo(dataArray, numbers.Count);
I keep getting " Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" error
Array.Copy provides good performance for what you're trying to accomplish.
int[] newArray = new int[10];
newArray[0] = 4; // new value
Array.Copy(numbers, 0, newArray, 1, numbers.Length - 1);
Be careful with array lengths though with this as any bound issues with throw exceptions.
I think you should be using queue and then you can convert it into array if you want
class Program
{
static void Main(string[] args)
{
const int CAPACITY = 10;
Queue<int> queue = new Queue<int>(CAPACITY);
for (int i = 0; i < 50; i++)
{
if (queue.Count == CAPACITY)
queue.Dequeue();
queue.Enqueue(i);
}
queue.ToArray();
Console.WriteLine(queue.Count);
Console.ReadKey();
}
}
Take a look at the generic Queue class, that has the functionality that you are looking for with FILO structure. Doing this just with arrays...
int[] numbers=new int[50];
for(int i=0; i<numbers.length; i++) numbers[i]=i;
//fill the array with 1, 2, 3, 4...
//To reverse this order, swap elements in reverse
//numbers.length-1 is the last index of the array
// j<numbers.length/2,each time you swap you change two values, so only done half the length of the array
for(int j=numbers.length-1; j>numbers.length/2; j--) swap(numbers, j, numbers.length-j);
//swaps the values of different indexes in the array
void swap(int[] array, int index1, int index2) {
int temp=array[index1];
array[index1}=array[index2];
array[index2}=temp;
}
This should reverse the arrays
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've created my own list with a static int as length. How are these things done when you don't know the size of a collection and you want to construct it. I know there is a build in list but I want to build my own to understand the inner working of it. I defined it as size = int 5 in the constructor so it will output now 1 2 3 0 0 and I want to know how to resize it and using a constructor with undefined length. I can't figure it out myself some help is appreciated.
I fixed it. Thanks for the answers guys really fast and easy to understand I never heard from the .net reference so thanks for the site.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List l = new List();
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
foreach (int n in l)
{
Console.WriteLine(n);
}
Console.Read();
}
}
class List
{
private int _lLength;
private int[] _lArray;
private int _lPos;
public List()
{
/*
* Create an array with a default size
* If it doesn't fit anymore create a new one and copy it
* to a new array and double the size
*/
this._lArray = new int[2];
}
public List(int c)
{
this._lLength = c;
this._lArray = new int[this._lLength];
this._lPos = 0;
}
public void Add(int n)
{
if (this._lArray.Length <= this._lPos)
{
// So now is the array < then the array we want to return
int[] tmp = this._lArray;
this._lArray = new int[tmp.Length * 2];
Array.Copy(tmp, this._lArray, tmp.Length);
}
this._lArray[this._lPos++] = n;
}
public IEnumerator<int> GetEnumerator()
{
foreach (int n in this._lArray)
yield return n;
}
}
}
Internally, the List<T> object keeps an array with a default size (0, according to the reference source). When the array is full, a new array is created, double size of the previous one, and all items from the first array are moved to the new array.
So adding an item to this list (array size = 2):
item 1
item 2
Causes the array behind the list to become (array size = 4):
item 1
item 2
item 3
null
If you know the probable size of the list on beforehand, you could opt to pass the expected number to the constructor of List<T>. The array size will be set to that length, which may give you better performance overall, since it doesn't have to recreate arrays.