Create a new List based on another two Lists C# - 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

Related

How to append arrays in 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();

Duplicated elements from x array add into y array

I tried to find 2 or more same elements from array x and then that duplicate to add into new array Y
So if i have in x array number like: 2,5,7,2,8 I want to add numbers 2 into y array
int[] x = new int[20];
Random rnd = new Random();
int[] y = new int[20];
int counter = 0;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
for (int j=i+1; j< x.Length; j++)
{
if (x[i] == x[j])
{
y[counter] = x[i];
Console.WriteLine("Repeated numbers are " + y[counter]);
counter++;
}
else
{
Console.WriteLine("There is no repeated numbers, numbers that are in x are " + x[i]);
}
break;
}
}
But having problems with that, when it come to the if loop it doesn't want to proceed with executing if loop (even if condition is true)
If someone could give me some suggestion, that would be helpful, thank you
There are various logical errors in your use of for. You should work more on your logic, because while libraries can be learnt by rote, logical errors are more something that is inside you.
int[] x = new int[20];
Random rnd = new Random(5);
// You don't know the length of y!
// So you can't use arrays
List<int> y = new List<int>();
// First initialize
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
}
// Then print the generated numbers, otherwise you won't know what numbers are there
Console.WriteLine("Numbers that are in x are: ");
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
// A blank line
Console.WriteLine();
// Then scan
for (int i = 0; i < x.Length; i++)
{
for (int j = i + 1; j < x.Length; j++)
{
if (x[i] == x[j])
{
y.Add(x[i]);
Console.WriteLine("Repeated numbers is " + x[i]);
}
}
}
// Success/failure in finding repeated numbers can be decided only at the end of the scan
if (y.Count == 0)
{
Console.WriteLine("There is no repeated numbers");
}
I've put some comments in the code (plus the changes)
And for debugging purpose, I suggest you use a fixed Random sequence. new Random(5) (or any other number) will return the same sequence every time you launch your program.
Note that if there are multiple repetitions of a number, like { 4, 4, 4 } then the y array will be { 4, 4 }
at first:
why do u use the 'break;' ?
second:
in the first for - loop u assign a random number to x[i]
but then in the nested second loop
u already ask x[j] to check for same values (but that doesn't exist yet)
there are so many ways to check if values are equal,
but i like your approach:
so what i would suggest:
make a for - loop and assign all the random numbers to int[] x
then think again how u can evaluate
x[0] = x[1] or x[2] or x[3] ...
Try to use Linq to find the duplicate in the Array
int[] x = new int[] { 2, 5, 7, 2, 8 };
int[] y;
var result = x.GroupBy(item => item)
.Select(grp => new { key = grp.Key, Count = grp.Count() });
y = result.Where(res => res.Count > 1).Select(res => res.key).ToArray();
int[] array = new int[5] {1,2,3,4,4};
List<int> duplitcateList = array.Where(x => array.Where(y => y == x).Count() > 1).Distinct().ToList();
or you can replace last line of above code with below.
List<int> duplitcateList = array.
GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
above code is using Linq.
suppose your first array (in question x) is array.
Linq will first check for all elements in to list which occur more then once, and select them distinctly and store it to duplicateList
if you need an array at the, you can simply convert this list to array by doing this,
int[] yArray = duplitcateList.ToArray();
Make use of linq in your code , as below
//first populate array x
var duplicates= xArray.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToArray();
linq query above make use of groupby and find duplicate i.e. element occuring more then one time in you array and then you select those element and return result
I think this will will be the most understandable solution without complicated extension methods:
int[] x = new int[20];
// there can be at most 10 duplicates in array of length of 20 :)
// you could use List<int> to easily add elements
int[] y = new int[10];
int counter = 0;
Random rnd = new Random();
// fill the array
for (int i = 0; i < x.Length; i++)
x[i] = rnd.Next(1, 15);
// iterate through distinct elements,
// otherwise, we would add multiple times duplicates
foreach (int i in x.Distinct())
// if the count of an elements is greater than one, then we have duplicate
if(x.Count(n => n == i) > 1)
{
y[counter] = i;
counter++;
}

Storing arrays withing arrays in C#

I'm working on a project right now that requires me to work with and store millions of different doubles. So I figure the most effective way to store all of these values would be in sets of arrays within arrays. but i have no idea how to do this. Plus i have to feed values into the lower level arrays and don't yet know an effective way of doing this.
The below is an attempt at explaining what I'm going for (This is not code, but the website thought it was):
L01 = [1,2,3]
L02 = [3,2,1]
L03 = [2,3,1]
L04 = [1,3,2]
L11 = [L01,L02]
L12 = [L03,L04]
L2 = [L11,L12]
So far I have only come up with this, and you should see why it doesn't work. I'm still pretty new to programming so please explain what I should be doing:
//Stores the weight values attached to an individual neuron
public double[] NeuronWeights = new double[321];
//Stores the NeuronWeights[] for an individual layer with incoming weights
public double[][] LayerWeight = new double[321][];
//Stores all of the LayerWeight[] in the network
public double[][][] TotalWeights = new double[11][][];
public void InitializWeights()
{
for (int i = 0; i < TotalWeights.Length; i++)
{
for(int j = 0; j < LayerWeight.Length; j++)
{
for(int k = 0; k < NeuronWeights.Length; k++)
{
Random r = new Random();
//Creating randome values to fill first level
if (r.Next(0, 2) > 0)
{
NeuronWeights[k] = r.NextDouble() * 2 - 1;
}
else NeuronWeights[k] = 0.0;
}
LayerWeight[j][] = NeuronWeights[];
}
TotalWeights[i][][] = LayerWeight[][];
}
}
}
To add more detail; I'm trying to generate and store 321 doubles ,within the range of (-1, 1), 321 time per "layer". Then do that for all 11 "layers". this information then needs to be called on to assign values for 321 other doubles, 11 times.
Multi-dimensional arrays are not the same as arrays of arrays. Try using List<> instead:
var L01 = new List<int> { 1,2,3 };
var L02 = new List<int> { 3,2,1 };
var L03 = new List<int> { 2,3,1 };
var L04 = new List<int> { 1,3,2 };
var L11 = new List<List<int>> { L01,L02 };
var L12 = new List<List<int>> { L03,L04 };
var L2 = new List<List<List<int>>> { L11,L12 };
But depending on what you are trying to accomplish, maybe you don't need to nest your Lists like that.
It looks like you are trying to create a structure where there are 11 layers, each with 321 neuron weights? That doesn't seem to make sense with your initial goal of storing and working with millions of doubles.
If you simply wanted to store a variable number of layers, each with a variable number of recorded weights, you'd set up something like this:
List<List<double>> weightData = new List<List<double>>();
You can think of a List as a variable-sized array that is expandable as you are going along in your process. So for each Layer, you'd
List<double> currentLayer = new List<double>();
weightData.add(currentLayer);
Then for each weight you wanted to add to the layer you'd do something like:
double neuronWeight = 17.0;
currentLayer.add(neuronWeight);
at the end of the day, weightData will have all your layers and weights within the layers. If you plan to manipulate the data after loading it, you will need to come up with a scheme to reference the various layers and weights, but I'm not sure what your use case for that is.
Good luck!
What about something like this, which uses one multi-dimensional array?
int totalWeightLength = 11;
int layerWeightLength = 321;
int neuronWeights = 321;
double[,,] TotalWeights = new double[totalWeightLength, layerWeightLength, neuronWeights];
void InitializWeights()
{
for (int i = 0; i < totalWeightLength; i++)
{
for (int j = 0; j < layerWeightLength; j++)
{
for (int k = 0; k < neuronWeights; k++)
{
Random r = new Random();
//Creating randome values to fill first level
if (r.Next(0, 2) > 0)
{
TotalWeights[i,j,k] = r.NextDouble() * 2 - 1;
}
else TotalWeights[i,j,k] = 0.0;
}
}
}
}
InitializWeights();
Console.WriteLine(TotalWeights[1,34,23]);
Console.WriteLine(TotalWeights[2,84,123]);
Console.WriteLine(TotalWeights[3,39,24]);
Console.WriteLine(TotalWeights[4,27,36]);

How to minus something from every value in array c#

I would like to ask how to minus some value from all values in an array c#?
List<int> array = new List<int>();
array.Add(4,5,3)
array minus 1;
for (int z = 0; z < N; z++)
{
Console.WriteLine(array[z]);
}
Console.ReadLine();
In output I would like to have this: 3,4,2
Actually I would like to do it in a way that I can work with the changed array not just to print out array minus 1.
I would like to rename the variable first, a list of integers with a name array is not good. so let me call the variable as ListInt. instead of using -1 it is better to use a variable called someValue. now see the code and how it works:
List<int> ListInt = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int someValue = -1;
ListInt = ListInt.Select(x => x - someValue).ToList();
// now the ListInt contains all the values as required
// Print the values using
Console.WriteLine(String.Join(",",ListInt));
Multiple approaches:
a plain foreach-loop:
foreach(int i in array)
Console.WriteLine(i - 1);
a for-loop:
for(int i = 0; i < array.Count; i++)
Console.WriteLine(array[i] - 1);
List.ForEach:
array.ForEach(i => Console.WriteLine(i - 1));
LINQ:
var arrayMinusOne = array.Select(i => i - 1);
foreach(int i in arrayMinusOne)
Console.WriteLine(i);
You can use this arrayMinusOne query multiple times (but note that it will be executed every time you use it). Or you could create a new collection with arrayMinusOne.ToList() or ToArray. If you want to modify the original list you can use the for-loop:
for (int i = 0; i < array.Count; i++)
array[i] = array[i] - 1;
or reassign arrayMinusOne.ToList() to the array variable. Note that a list is not an array.
Following your style to help you understand, this will display what you want:
for (int z = 0; z < array.Length; z++)
Console.WriteLine(array[z]-1);
But this will actually subtract 1 from the data before displaying the resulted data:
for (int z = 0; z < array.Length; z++)
array[z]--;
for (int z = 0; z < array.Length; z++)
Console.WriteLine(array[z]);
This code is in VB.Net, but have the logic:
Dim array As New List(Of Integer)()
array.Add(4)
array.Add(5)
array.Add(3)
Dim resta = -1
For index = 0 To array.Count - 1
array(index) = array(index) - 1
Console.WriteLine(array(index))
Next
Console.ReadLine()
List<int> array = new List<int>();
array.Add(2);
array.Add(3);
array.Add(4);
for (int z = 0; z < array.Count; z++)
{
array[z] = array[z] - 1;
}
Console.WriteLine(array[0]);
Console.ReadLine();
Linq solution:
List<int> array = new List<int>() {
4, 5, 3,
};
// "3, 4, 2"
Console.Write(String.Join(", ", array.Select(item => item - 1)));
Console.ReadLine();
In case you want to put each item on the separate line
// 3
// 4
// 2
Console.Write(String.Join(Environment.NewLine, array.Select(item => item - 1)));

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