How to append arrays in c# - c#

I would like to get the output of this to be [1,2,3,4,...,200]. Any suggestions for how to go about this?
var Laser_data = 0;
var i = 0;
var j = 1;
int[] LaserData_200 = new int[200];
for (i = 0; i < LaserData_200.Length; i++)
{
Laser_data += j;
LaserData_200[i] = Laser_data;
Console.WriteLine(" " + LaserData_200[i]);
}
Current output:
1
2
3
4
ect.

Your array initialization and element assignment can be simplified massively. Your array is just the numbers 1 through 200 (inclusive). Enumerable.Range can generate that for you, then save it as an array.
int[] myArray = Enumerable.Range(1, 200).ToArray();
To print it all, string.Join it using a comma as a seperator.
Console.WriteLine($"[{string.Join(',', myArray)}]");
// [1,2,3,4,5,6,7,8,9,10,11,12,13, .... 200]

I see the title has nothing to do with the posted code.
So I am answering the question in the title.
Say you have two arrays a and b and you want to create a third array that combines the two arrays, then you write code like
int[] c = Enumerable.Concat(a, b).ToArray();
or you have and array a and you want to keep adding values to it in loop. When arrays are fixed size (a.IsFixedSize = true always) so you can do this efficiently.
The best solution is to use List<T> instead of an array
List<int> a = new List<int>()
for(int i=0; i<200; i++)
{
a.Add( i+1 );
}
and if you want an array in the end, you just do
int[] c= a.ToArray();

Related

Create a new List based on another two Lists C#

i'm trying to write a desktop app using c# .NET , but currently i'm stuck in the following problem:
Assume you have two Lists:
List1=[1,2,3,4]
List2=[1,4,1,3]
And i want a new list that is filled with "n" zeros between two consecutive elements of list1, been "n" the "i" element of list2, the new list should look like this:
List3=[1,0,2,0,0,0,0,3,0,4,0,0,0]
My Code:
List<int> idID = new List<int>();
idID.Add(1);
idID.Add(2);
idID.Add(3);
idID.Add(4);
List<int> Nevent = new List<int>();
Nevent.Add(1);
Nevent.Add(4);
Nevent.Add(1);
Nevent.Add(3);
int total = Nevent.Count;
for (int j = 0; j < total; j++)
{
for (int i = 1; i <= Nevent[j]; i++)
{
idID.Insert(i, 0); //modify (____,0) of this line???
}
}
string IDS = String.Join(",", idID);
Console.WriteLine(IDS);
I think that i should change the part with idID.Insert(i, 0); and replace the i with some kind of sequence form like N0,N0+N1,N0+N1+N2,... been Ni the i element of list2 (that i name Nevent in the code) but i do not know how to do that.
How should I proceed? or there is a better way to achive what i want?
Thank you in advance.
If we assume the lists are the same length, you can make use of Zip to zip the 2 arrays together, and then a bit of LINQ to build up and select the resulting array
var result = idID.Zip(Nevent,
(x,y) => new[]{ x }.Concat(Enumerable.Repeat(0,y)) )
.SelectMany(x => x);
result is
1,0,2,0,0,0,0,3,0,4,0,0,0
Live example: https://dotnetfiddle.net/PvtOVv
If you want/need to have result as a list just tag ToList() on the end
Create new list, and treat idID and Nevent as input only. With LINQ we can use Enumerable.Repeat, otherwise we would have to use inner loop to add zeros.
using System.Linq;
...
List<int> result = new List<int>();
for (int j = 0; j < idID.Count; j++)
{
result.Add(idID[j]);
result.AddRange(Enumerable.Repeat(0, Nevent[j]));
}
Another approach is to process the list backwards. Like this the inserted zeroes do not alter the indexes of elements to be processed.
var idID = new List<int> { 1, 2, 3, 4 };
var Nevent = new List<int> { 1, 4, 1, 3 };
for (int i = idID.Count - 1; i >= 0; i--) {
for (int n = 0; n < Nevent[i]; n++) {
idID.Insert(i + 1, 0);
}
}
Console.WriteLine(String.Join(",", idID));
prints
1,0,2,0,0,0,0,3,0,4,0,0,0

Getting a 1D array from a 3D array C#

I have a 8x8x3 array with some values. What I want to do is make a list of just the 1D arrays.
What I've got so far:
int[] packIt(int[,,] data, int factor) {
List<int[]> toReturn = new List<int[]>();
int[] test = data[0, 0];
So unless I'm missing something, I make a list of one dimensional arrays and try to fit in the one dimensional array at data[0, 0] (the test is just a placeholder so far). The error I'm getting is "Wrong number of indices", however if I follow the data[0,0,0] (which gives no error) I'll just get the 1 value at the location. I could do it manually, but am just wondering if there is an implementation for the functionality that I'm trying to do, as I will be using it a lot. Thanks a bunch.
You don't need to do anything specific to turn a 3D array into a 1D one; you can just enumerate it:
foreach(var x in multiDim)
...
This will print 1 to 8:
var x = new int[2,2,2];
x[0,0,0] = 1;
x[0,0,1] = 2;
x[0,1,0] = 3;
x[0,1,1] = 4;
x[1,0,0] = 5;
x[1,0,1] = 6;
x[1,1,0] = 7;
x[1,1,1] = 8;
foreach(int i in x)
Console.WriteLine(i);
To this end you can just straight enumerate your array in chunks of whatever:
var out = new List<int[]>();
var arr = new int[chunkSize];
out.Add(arr);
var idx = 0;
foreach(var x in miltiDimArray){
if(idx == chunkSize){
out.Add(arr = new int[chunkSize]);
idx = 0;
}
arr[idx++] = i;
}
Note that I don't try to make the ticks array smaller if the chunk size doesn't divide into the number of elements. idx will have a residual value you can use to work out what to resize the last array by if that is important

How do I shift all of the elements of an array from the left side to the right side in c#

I am trying to swap the elements of an array from the far left all the way to the far right.
So the array looks like this: 1234567
And I want the output to be like this: 7654321
I have tried this but all it does is move only the last digit on the left side to the right side and no other digits.
static int[] ShiftArray(int[] array)
{
int[] temp = new int[array.Length];
for (int index = 0; index < array.Length; index++)
{
temp[(index + 1) % temp.Length] = array[index];
}
return temp;
}
Thanks for any suggestions!
If you want to change the order in the array itself (without creating a new array), you can use the following:
Array.Reverse(array);
If you don't want to use any pre-built .NET functions, you can try the following:
using System;
public class Program
{
public static void Main()
{
int[] array = new int[]{1, 2, 3, 4, 5, 6, 7};
int start = 0;
int end = array.Length - 1;
while (start < end)
{
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
Console.WriteLine("Result: {0}", String.Join("", array));
}
}
Whenever you swap elements in an array, you need a temp variable to hold an element while the swap is being performed.
The start and end variables are to track where you're at in the array. Once they cross each other, you're done swapping elements around.
RESULT
Result: 7654321
DEMO
.NET Fiddle
You can use the method Reverse from System.Linq.
return array.ToList().Reverse().ToArray();
Why don't you just iterate through the array in decreasing order?
for(int i = array.length - 1; i >= 0; i--)
{
// do something
}

C#, how to save frequency of elements from one array in another, two-dimensional array?

So here's my problematic code. When I try to pass an array with N arguments, let's say {2,1,2,2,5} in result I want to get two-dimensional secArray[element,frequency of the element]. The problem is I get more than that and in this particular case I get an array like this:
23
11
22
21
52
Console.WriteLine("Enter number of elements: ");
int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
for (int i = 0; i < array.Length; i++)
{
Console.Write("Array[{0}]: ", i);
array[i] = int.Parse(Console.ReadLine());
}
//problematic code begins
int[,] secArray = new int[n,2];
for(int i = 0;i<n;i++)
{
for(int j = 0; j<n;j++)
{
if(array[i] == secArray[j,0])
{
secArray[j, 1] += 1;
}
else
{
secArray[i, 0] = array[i];
secArray[i, 1] = 1;
}
}
}
//problematic code ends
//printing - works good
Console.WriteLine("How many same elements?");
for (int row = 0; row < secArray.GetLength(0); row++)
{
for (int col = 0; col < secArray.GetLength(1); col++)
{
Console.Write(secArray[row, col]);
}
Console.WriteLine();
}
If anyone has a clue how to fix this I'll be really grateful. It frustrates me that I don't know where the actual problem lies.
The first problem concerns the very first statement.
int[,] secArray = new int[n,2];
You don't know how many unique elements you have in your array until you traverse it. You can't use n, because n is the total number of arguments, which can be greater than the number of unique elements.
Next, the nested for loops are very inefficient. Your algorithm traverses the array for every element in the array- so it will run in O(n^2) time.
Think: do you have to traverse the array more than once? Why not just use a hashtable (dictionary in C#) to keep track of counts as you traverse the array? A hashtable uses a very efficient lookup mechanism to tell you if you've already seen the element, and the value can be used to keep track of count.
Consider replacing your problematic code with the following, and understanding how it works.
Dictionary<int, int> elementCounts = new Dictionary<int, int>();
for(int i = 0; i < n; i++)
{
int element = array[i];
if (elementCounts.ContainsKey(element))
elementCounts[element]++;
else
elementCounts.Add(element, 1);
}
Console.WriteLine("How many same elements?");
foreach(KeyValuePair<int,int> count in elementCounts)
{
Console.WriteLine("Element: {0} Count: {1}", count.Key, count.Value);
}
Then, if you want to copy the results in the hashtable (Dictionary) to a two-dimensional array, you can do the following.
int numberOfUniqueElements = elementCounts.Count;
int[,] secArray = new int[numberOfUniqueElements, 2];
int j = 0;
foreach (KeyValuePair<int, int> count in elementCounts)
{
secArray[j, 0] = count.Key;
secArray[j, 1] = count.Value;
j++;
}
I would use Linq's GroupBy to do this
var array = new int[] { 2, 1, 2, 2, 5 };
var result = array.GroupBy(x => x).Select(x => new[] { x.Key, x.Count() }).ToArray();
Why don't you use a hash table. Let the number in the array be the hash entry key, and let the value of the hash entry be the count. Then just iterate through the array once. While iterating through the array check if hash entry exists if so add 1 to it, if not create it.
Something like
for(int i = 0; i<n;i++) {
if(hashTable.containsKey(array[i])) {
hashTable[array[i]]++];
} else {
hashTable.add(array[i],1);
}
}
Please note that this is quedocode and will require to lookup the methods and implement it correctly.

C# variable or array with number range (example. 1 - 100)

I'm fairly new to C# and I'm doing a school project, i need to figure out how to get a variable or an array with numbers from 1 to 100 without entering every single number in an array for example int[] numbersArray {1,2,3,4,5,6,7,8,9,10...}; because that takes a long time and doesn't look very efficient.
I'm using C# Visual Studio Express 2010. It would mean alot to me if you could answer this for me. I'm gonna be using it in an if statement like so:
if(numbersArray.Contains(numbersInput))
{
Console.WriteLine("numbersInput was a number from 1 to 100")
}
You can use Enumerable.Range to create a range of numbers:
int[] arr = Enumerable.Range(1, 100).ToArray();
If you're assignment is just to print a message if the input is within a range you simply can do this:
if (numbersInput >= 1 && numbersInput <= 100)
Console.WriteLine("numbersInput was a number from 1 to 100");
But if you really need to create an array with numbers 1..100 you can use a for-loop:
var numbersArray = new int[100];
for (var i = 1; i <= 100; i++)
numbersArray[i - 1] = i;
Or simply use a little Linq:
var numbersArray = Enumerable.Range(1, 100).ToArray();
you could just use a for loop with the iterator of the loop as the counter:
int[] numbersArray = new int[100] // initialise array to 100 elements.
for (int i = 1; i <= 100; i++)
{
numbersArray[i - 1] = i; // note we are using 0-based indexing to access elements of the array
}
Other way...
int[] arr = new int[100];
for(int i = 0; i < arr.Length; ++i)
{
arr[i]=i+1;
}

Categories

Resources