Array numbers in order [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my main I have this array with random numbers
static void Main(string[] args)
{
int [] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
Console.WriteLine("The scores are: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
Console.ReadLine();
}
I need to make a static method in a class that would rearrange these numbers so that they are in order and I'm not sure how to do this. I need to swap these numbers.

Use Array.Sort to sort your original array:
Array.Sort(numbers);
Or Enumerable.OrderBy to create new sorted sequence, which you can save to array:
int[] sorted = numbers.OrderBy(i => i).ToArray();

Array class has a Sort method (Array) which takes array as a parameter.
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.
Here am example with LINQPad;
void Main()
{
int [] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
ReturnSortedArray(numbers);
foreach (var element in numbers)
{
element.Dump();
}
}
static void ReturnSortedArray(Array a)
{
Array.Sort(a);
}
Output will be;
1
2
3
4
5
6
7
8
9
10
11
12

To answer the question which was how do I create a static method to sort the Array you can use the code below.
public static void Main(string[] args)
{
int[] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
Console.WriteLine ("The scores are: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine (numbers [i]);
}
Console.WriteLine ("The scores in order are: ");
SortArray (numbers);
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine (numbers [i]);
}
Console.ReadLine ();
}
public static int[] SortArray(int[] arrayIn)
{
Array.Sort (arrayIn);
return arrayIn;
}
OUTPUT
The scores are:
1 6 4 11 2 5 9 3 7 10 12 8
The scores in order are:
1 2 3 4 5 6 7 8 9 10 11 12

you can sort in here
Array.Sort(numbers);

Related

What causes IndexOutOfRangeException here? [closed]

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 1 year ago.
Improve this question
I had a programming exam where at the end, I always had an IndexOutOfRangeException for the code below (for the if statement, exactly).
The task was to remove numbers in 21..32 range from the list then print out the new list. nums is a List<int> with exactly 6 numbers given by the user.
I've been programming for 4 years now and I can't find a single problem :D
Here's the code.
// nums is a List<int> with exactly 6 elements in it.
List<int> changedNums = new List<int>(nums);
for (int k = 0; k < 6; k++)
if (changedNums[k] >= 21 && changedNums[k] <= 32)
changedNums.RemoveAt(k);
I didn't put brackets here because it's a one-liner.
The issue here is that you modifying the length of the list while iterating. After you deleted at least one item from changedNums list, its length is less than the initial 6 (so you get IndexOutOfRangeException). Also, once you deleted k-th item, you should decrement k. I modified your sample code to work as follows:
static void Main()
{
List<int> nums = new List<int>() { 1, 22, 30, 4, 5, 6 };
List<int> changedNums = new List<int>(nums);
var currentLength = changedNums.Count;
for (int k = 0; k < currentLength; k++)
{
if (changedNums[k] >= 21 && changedNums[k] <= 32)
{
changedNums.RemoveAt(k);
--k;
--currentLength;
}
}
Console.WriteLine(string.Join(" ", changedNums));
}
This will print: 1 4 5 6
Edit:
As pointed by #derpirscher and #Jon Skeet in comments, index manipulations can be easily avoided by iterating the array from end to start:
List<int> nums = new List<int>() { 1, 22, 30, 4, 5, 6 };
List<int> changedNums = new List<int>(nums);
for (int k = changedNums.Count - 1; k >= 0 ; k--)
if (changedNums[k] >= 21 && changedNums[k] <= 32)
changedNums.RemoveAt(k);
Console.WriteLine(string.Join(" ", changedNums));
An even easier solution to your problem can be achieved using LINQ:
var changedNums = nums.Where(num => num < 21 || num > 32).ToList();
All the solutions will produce the same result 1 4 5 6

Have N elemnts of sum of a list and repeat until the end of the list [closed]

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 2 years ago.
Improve this question
I'm facing a problem when trying to play with C# list. Currently I have a list of integer. And I'm looking for a way to sum up every 5 integer, until the end of the list.
For example I have a list like this:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
How to sum up every N elements (let's say 5) in the list and become:
[ 15, 40 ]
FYI, the list consist of hundred and thousand int elements.
Thanks.
Since noone's mentioned the simple way yet...
Note that if the input is not divisible by the group size, any extra elements will be ignored. For example, if the input is 11 elements, and the group size is 5, this will give 2 sums of 5 elements and then ignore the 11th input element.
public static int[] SumEvery(int[] input, int groupSize)
{
// The number of groups we have
int numGroups = input.Length / groupSize;
int[] result = new int[numGroups];
// For each group of numbers...
for (int group = 0; group < numGroups; group++)
{
// ... loop through each number in that group, adding to the sum ...
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
// ... then store that sum in our array of results
result[group] = sum;
}
return result;
}
int[] input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] result = SumEvery(input, 5);
If you want to stream the results as an IEnumerable<int>, rather than collecting them all into an array, then:
public static IEnumerable<int> SumEvery(int[] input, int groupSize)
{
int numGroups = input.Length / groupSize;
for (int group = 0; group < numGroups; group++)
{
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
yield return sum;
}
}
You could do this with a bit of Linq
var ints = new []{1,2,3,4,5,6,7,8,9,10};
var result = ints.Select((x,i) => new{Num = x,Index = i}) // Project to a list with the index and number
.GroupBy (i => i.Index/5) // group by the int division by 5
.Select(g => g.Sum(a => a.Num)); // sum the numbers in each group
Live example: https://dotnetfiddle.net/BabP5N
Note that is is by far the least efficient way - and with a large data set will not perform well. But for a small dataset will work fine. This code is possibly the clearest interpretation of the problem.

C#: loop through array of numbers and put consecutive numbers in one array, and all other numbers else in other array

I have an unsorted array of numbers. Most numbers in this array are consecutive (1, 2, 3, 4, 5,...) but sometimes there's a number in it that's higher than the rest.
int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;
foreach (int number in arr) {
if (number > highestNumber) {
secondHighestNumber = highestNumber;
highestNumber = number;
}
else if (number > secondHighestNumber) secondHighestNumber = number;
}
When I run the code, it'll tell me 9001 is the highest number and 9000 the second highest. But I want to change it so that I get an array of all the numbers from 1 to 11, with all the consecutive numbers that only have a difference of one, and a second array with all the larger numbers: 1207, 1803, 9000 and 9001.
9000 and 9001 shouldn't be in the first array, because the difference between these numbers and the rest is too high. So the end result should look like this:
int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };
Some background info on what the purpose of this is:
Cient creates articles and each article has an article number that is created by looking up what the highest article number is in the "articles" table so far (e.g. 20), then the number of the new article is that number + 1 (e.g. 21); So an increment per number. However the client wishes to be able to sometimes add articles and input the article number he desires for the article, so let's say for the last article he created he inputted 7000 as article number. If he he then creates another article after that, I have to continue with that list of incrementing numbers. So unless the client changes the value of the next article again, the next new article should have 22 as article number (and not 7001).
Any help would be greatly appreciated as I've been stuck on trying to figure this out for a while now.
I'm not sure if you are just wanting to get the next number you should use or you want the 2 sets. If you want the two sets, I would do this:
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();
foreach (int number in arr) {
if(l1.Count==0 || l1[l1.Count-1] == (number -1))
l1.Add(number);
else
l2.Add(number);
}
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, 9000, 9001 };
// Sort the array
Array.Sort(arr);
// Start at the beginning and check if the index matches the actual number.
// Computer begins at 0, so fix that
for (int index=0;index<arr.Length; index++)
{
if (arr[index] != index+1)
{
Console.WriteLine("Next ID is " +(index+1));
break;
}
}

Array returning only end value in c#

I'm trying to return the entire path traced by Djikstra's algorithm using an array but somehow it's returning only the end node, but when i print the value in the same method it's printing correct values.
public int[] PrintPath(int[] path, int j, int src)
{
int[] trace = new int[14];
int i = 0;
if (path[j] == -1)
return path;
PrintPath(path, path[j], src);
Console.Write("{0}", j + 1);
trace[i] = j + 1;
i++;
return trace;
}//PrintPath
source node: 1, destination node: 10
expected output: 1 13 7 9 10
actual array output: 0 10 10 10 10 10 10 10 10 10 10 10 10 10
Your question is definitely not clear.
If you just want to print the path why don't you use String.Join(" ", path) ?
i.e.
int[] path = new int[] {1, 13, 7, 9, 10 };
Console.WriteLine(String.Join(" ", path));
Or please explain well what is your goal.

Multidimensional List of ints C#

First of all i searched through the questions and I haven't found the thing I need , maybe it doesn't exist haha but i'll give it a shot.I am new to C# and I am coming from C++, got highschool experience.
In C++ I had Vector<int> T[]; so I could create a list with a size that it wasn't know; and make something like this and not wasting space; to be more exact
T[0][....];
T[1][...];
1 2 3 4 5
1 2 3
2 4 1 5
0 0 0 0 0 0
I am trying to do this in C# and It doesn't seem to work; I have tried this so far:
public class myints
{
public int x { get; set; }
}
public List<myints[]> T = new List<myints[]>();
T[i].Add(new myints() { x = i });
I wanna be able to add stuff and then use Count() in a for to see how many elemts I have in a T[i]. like T[i].size()... Is this possible?
the program says System.Array does not contain a definition for Add
This example creates a list with a number of sublists of varying length and should serve as a good starting point for what you want to do.
List<List<int>> mainlist = new List<List<int>>();
List<int> counter = new List<int>() { 5, 4, 7, 2 };
int j = 0;
// Fill sublists
foreach(int c in counter)
{
mainlist.Add(new List<int>(c));
for(int i = 0; i < c; i++ )
mainlist[j].Add(i);
j++;
}
You could also add initialized lists to the main list
List<List<int>> mainlist = new List<List<int>>();
mainlist.Add(new List<int>() { 1, 5, 7 });
mainlist.Add(new List<int>() { 0, 2, 4, 6, 8 });
mainlist.Add(new List<int>() { 0, 0, 0 });

Categories