C# Displaying Two Lists in Console Window - c#

I'm working on a algorithm that will have an array of populations which will then each have a list of 60 weights that are randomly generated numbers. This goes through the neural network and produces a result for each population member which is being stored in a list called results. I've done all that and I now want to display both the list of results and the array of lists called populationWeights in the console window so that there will be numbers going down from 1 to 60 and the next to that will be the corresponding result from the list called results. What is the easiest way to do this in c# based on the code i have currently?
Quick note populationWeights is an array of lists so there is 60 lists in an array (the population) and then those lists contain 60 random numbers (the weights).
var populationSize = 60;
var weights = 60;
List<double>[] populationWeights = new List<double>[populationSize];
List<double> results = new List<double>();
for (int i = 0; i < populationSize; i++)
{
populationWeights[i] = new List<double>();
for(int j = 0; j < weights; j++)
{
populationWeights[i].Add(((_rand.NextDouble() * 2) - 1));
}
}
for(int i = 0; i < populationWeights.Length; i++)
{
results.Add(GetResults(populationWeights[i]));
Console.WriteLine(results[i]);
}
Console.ReadLine();
I want the console window to look this this.
This far left hand side being the number of the index in the array for each list e.g list[0] in array of lists populationWeights. And then the right hand side being the results.
0 0.00000343
1 0.00000034
2 0.34984387
3 0.34734934
4 0,03470943
...

You could use string interpolation to format:
Console.WriteLine($"{i},{results[i]}");
More on MSDN:

Related

How to make a one dimensional array to display multiples of seven

I am attempting to code a one dimensional array to display code allowing me to display multiples of seven, I'm not sure how to go through with this, thank you.
I hope I understood your question. You can use generate multiples of 7 using Linq as follows.
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
Enumerable.Range allows you to generate a sequence of values in specified range (First parameter is the first number in sequence, the second parameter is number of items), while the Select statement (x=>x*7, multiply each value in generated sequence with 7) ensures you get the multiples of 7.
Complete Code:
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadLine();
Due to the vagueness of the question, my answer may not be applicable, but I will attempt to answer based on my assumption of what you are asking.
If you have an array of int and you want to multiply the values of the individual array objects, you would do something like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]*7);
}
//outputs 21,35,56
If you want to multiply based on the index of the array object, you would do it like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(i*7);
}
//outputs 0,7,14
//or if you need to start with an index of 1 instead of 0
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine((i+1)*7);
}
//outputs 7,14,21
Anu Viswan also has a good answer, but depending on what it is you are trying to do, it may be better to rely on loops. Hope my answer helps.

Check against two separate array values and grabbing the smallest one to insert into a new array the CW new array values

I am working with Arrays and conditionals statements, little lost right now and was hoping for some input.
So, I created two Arrays
int[] one = new int[] {
4160414, 6610574, 2864453, 9352227, -4750937, -3132620, 2208017,
-2226227, -8415856, -9834062, -3401569, 7581671, 8068562, 7520435,
-9277044, -7821114, -3095212, 966785, 6873349, -8441152, -7015683,
-6588326, -282013, 4051534, 9930123, -3093234 };
int[] two = new int[] {
1099626, 6083415, 8083888, -8210392, 2665304, -8710738, -8708241,
8859200, -1255323, 5604634, 2921294, -7260228, 7261646, 1137004,
5805162, 4883369, 8789460, 9769240, 319012, -7877588, -1573772,
5192333, 1185446, 1302131, 4217472, -3471445};
My next step what i was thinking is i am going to have to loop through each array
for (int i = 0; i < one.Length; i++)
{
int xValue = one[i];
for (int j = 0; j < two.Length; j++)
{
int yValue = two[j];
}
}
Now that i have the index of each Array i need to check wether the index of xValue is less than the index of yValue
if (xValue < yValue)
{
// dO SOMETHING HERE
}
if (yValue < xValue)
{
// Do Something HERE
}
Where i am getting confused at, is with C# from my understanding you can not push new values into an Array, it needs to be a new instance of the array and copy?
So i tried doing
if (xValue < yValue)
{
Array.Copy(one, x, 13);
}
if (yValue < xValue)
{
Array.Copy(two, x, 13)
}
Both Arrays have 26 values, so a new array of 13 would need to be created to insert the checked value, but Array.Copy seems to not be working getting an array out of bounds check lower bounds.
I'm just confused on checking the values of both arrays at their index, then grabbing the smallest value of the checked values then taking that small value and inserting it into a new array, then use a foreach-loop to iterate over it and print the values to the console. FacePalm
You can use LINQ's Zip to achieve this:
int[] smallest = one.Zip(two, (o, t) => Math.Min(o,t)).ToArray();
Essentially, Zip will provide both items to the lambda expression, allowing you to combine them how you see fit. In this case, we just choose the minimum and return it.
Try it online
Basically, you need to define the size of the new array when you declare it. Make it the same size as one. Then add the smallest item from one or two on each iteration by comparing the items in each array at index i.
int[] smallest = new int[one.Length];
for (int i = 0; i < one.Length; i++)
{
if (one[i] < two[i])
{
smallest[i] = one[i];
}
else
{
smallest[i] = two[i];
}
}

how to create a random int[] [duplicate]

This question already has answers here:
Most efficient way to randomly "sort" (Shuffle) a list of integers in C#
(13 answers)
Closed 5 years ago.
I need to create a random array of int with certain parameters.
int[] test = new int[80];
Random random = new Random();
I need to assign 1's and 0's, randomly to the array. I know how to do that.
test[position] = Random.Next(0,2);//obviously with a for loop
But I need to have exactly 20 1's, but they need to be randomly positioned in the array. I don't know how to make sure that the 1's are randomly positioned, AND that there are exactly 20 1's. The rest of the positions in the array would be assigned 0.
I think you need to turn your thinking around.
Consider:
var cnt = 20;
while (cnt > 0) {
var r = Random.Next(0, 80);
if (test[r] != 1) {
test[r] = 1;
cnt--;
}
}
Expanding explanation based on comments from CodeCaster. Rather than generate a random value to place in the array, this code generates and index to set. Since C# automatically initializes the test array to 0 these values are already set. So all you need is to add your 1 values. The code generates a random index, tests it to see if it isn't 1, if so it sets the array element and decrements a count (cnt). Once count reaches zero the loop terminates.
This won't properly function if you need more values than 0 and 1 that is true. Of course the questions explicitly stated that these were the needed values.
"This causes horrible runtime performance". What!? Can you produce any prove of that? There is a chance that the index generated will collide with an existing entry. This chance increases as more 1's are added. Worst case is there is a 19/80 (~23%) chance of collision.
If you know you need exactly 20 of one value, a better way to go about this is to pre-populate the array with the required values and then shuffle it.
Something like this should work:
int[] array = new int[80];
for (int i = 0; i < 80; i++)
{
int val = 0;
if (i < 20)
{
val = 1;
}
array[i] = val;
}
Random rnd = new Random();
int[] shuffledArray = array.OrderBy(x => rnd.Next()).ToArray();
You can do
for (int i = 0; i < 20; i++)
{
var rand = random.Next(0,80);
if (test[rand] == 1)
{
i--;
continue;
}
test[rand] = 1;
}
Remaining are automatically zero.

How do I sort each row of a 2D array separately?

I want to make a program where users have to enter a list of 100 numbers.
The outcome has to be a 2 dimensional matrix with with 34 rows and 3 columns (where the last row has only 1 number of course).
Now I want to: first sort the array by ascending order. Then I want to sort each row separately by descending order.
I'll demonstrate with a two dimensional array containing 10 elements
If these are the numbers the user enters: 2, 4, 6, 9, 5, 2, 3, 4, 9, 7
I want the array to look like this:
3 2 2
5 4 4
9 7 6
9
I think it's easier to start with a 1D array which you can later copy to a 2D array if you really have to.
Array.Sort(input); //input is an int[100]
//Now, sort each row in descending order
var comparer = Comparer<int>.Create((a, b) => b.CompareTo(a));
for (int row = 0; row < 99; r+=3) {
Array.Sort(input, row, 3, comparer);
}
It's straightforward if you do the sorting and restructuring as separate steps:
Collect the results in a flat (i.e. one-dimensional) array.
Sort the flat array (e.g. with Array.Sort(...)).
Build up your new data structure by looping through the flat array. You don't need to do any further sorting here. Each time just take [arr[n+2], arr[n+1], arr[n]] as the row in the new 2D array and jump forward to n = n + 3.
I also favour creating the output structure by looping over the sorted input structure. The following will achieve what you want. It will take any size array of integers and the required number of columns for the two-dimensional output array and return the result as you defined it.
public static int?[,] SortInput(int[] input, int requiredColumnCount)
{
// Guard conditions.
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input.Length < 1)
throw new ArgumentOutOfRangeException(nameof(input));
if (requiredColumnCount < 1)
throw new ArgumentOutOfRangeException(nameof(requiredColumnCount));
var inputLength = input.Length;
// Sort the input array in ascending order.
Array.Sort(input);
// Dimension the output array.
var requiredRowCount = (int)Math.Ceiling((decimal)inputLength / requiredColumnCount);
var output = new int?[requiredRowCount, requiredColumnCount];
// Setup variables to check for special handling of last output row.
var lastRowIndex = output.GetUpperBound(0);
var columnCountForLastRow = inputLength % requiredColumnCount;
// Populate the output array.
for (var inputIndex = 0; inputIndex < inputLength; inputIndex += requiredColumnCount)
{
var rowIndex = inputIndex / requiredColumnCount;
// Special handling may be required if there are insufficient
// input values to fully populate the last output row.
if ((rowIndex == lastRowIndex) && (columnCountForLastRow != 0))
requiredColumnCount = columnCountForLastRow;
for (var columnIndex = 0; columnIndex < requiredColumnCount; columnIndex++)
{
output[rowIndex, columnIndex] = input[inputIndex + requiredColumnCount - columnIndex - 1];
}
}
return output;
}

Random selection for a variable set with a guarantee of every item at least once

I am working on a game in c# but that detail is not really neccessary to solve my problem.
At I high level here is what I want:
I have a set that could have any number of items in it.
I want to randomly select 10 items from that set.
If the set has less than 10 items in then I expect to select the same
item more than once.
I want to ensure every item is selected at least once.
What would be the algorithm for this?
Sorry I'm not sure if this is an appropriate place to ask, but I've got no pen and paper to hand and I can't quite get my head round what's needed so appreciate the help.
In addition I might also want to add weights to the items to
increase/decrease chance of selection, so if you are able to
incorporate that into your answer that would be fab.
Finally thought I should mention that my set is actually a List<string>, which might be relevent if you prefer to give a full answer rather than psuedo code.
This is what I use to randomize an array. It takes an integer array and randomly sorts that list a certain amount of times determined by the random number (r).
private int[] randomizeArray(int[] i)
{
int L = i.Length - 1;
int c = 0;
int r = random.Next(L);
int prev = 0;
int curr = 0;
int temp;
while (c < r)
{
curr = random.Next(0, L);
if (curr != prev)
{
temp = i[prev];
i[prev] = i[curr];
i[curr] = temp;
c++;
}
}
return i;
}
If you look for effective code, my answer isnt it. In theory, create some collection you can remove from that will mirror your set. Then select random member of the object from it ...and remove, this will garantee items wont repeat(if possible).
Random rnd = new Random();
List<int> indexes = new List<int>(items.Count);
for (int i = 0; i < items.Count; i++)
indexes.Add(i);
List<string> selectedItems = new List<string>(10);
int tmp;
for(int i = 0; i < 10; i++)
{
tmp = rnd.Next(1,10000); //something big
if(indexes.Count > 0)
{
selectedItems.Add(yourItems[indexes[tmp%indexes.Count]]);
indexes.RemoveAt(tmp%indexes.Count);
}
else
selectedItems.Add(yourItems[rnd.Next(0,9)]); //you ran out of unique items
}
where items is your list and yourItems is list of selected items, you dont need to store them if you want process them right away
Perhaps shuffle the collection and pick elements from the front until you have the required amount.
Once you've gone through all the elements, you should perhaps shuffle it again, so you don't just repeat the same sequence.
The basic algorithm for shuffling: (in pseudo-code)
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
With the above algorithm (or a minor variation), it's possible to just shuffle until you reach the required number of elements, no need to shuffle the whole thing.

Categories