Bug fix in a matrix - c#

I am doing a unity project and I use mapMatrix(matrix of chars) as a map tool to tell which gameObject to instantiate as an environment.
Firstly, I call function populateMapMatrix and writeTextFile to create a txt file with content of a matrix. But now, I need to read from that file into a matrix and then instantiate the environment. I debugged the project and some elements of matrix get '\n' even if I have a way of dealing with that chars. Can someone help me?
Here's the code:
using UnityEngine;
using System.Collections;
using System.IO;
public class EnviromentBuilder : MonoBehaviour {
const int NUMBER_OF_ROWS = 50;
const int NUMBER_OF_COLUMNS = 50;
const char GRASS_MATRIX_FIELD = 'G';
const char TREE_MATRIX_FIELD = 'T';
const string pathToFile = "C:\\Users\\Darko\\Desktop\\Unity\\WAR GAME\\enviromentMapMatrix.txt";
public char[,] mapMatrix;
public GameObject grass;
public GameObject tree;
// Use this for initialization
void Start ()
{
mapMatrix = new char[NUMBER_OF_ROWS, NUMBER_OF_COLUMNS];
//populateMapMatrix ();
readTextFile();
InstantiateEnviroment ();
//writeTextFile ();
}
bool isGrassMatrixField(int i, int j)
{
return mapMatrix [i, j] == GRASS_MATRIX_FIELD ? true : false;
}
bool isTreeMatrixField(int i, int j)
{
return mapMatrix [i, j] == TREE_MATRIX_FIELD ? true : false;
}
void populateMapMatrix()
{
for (int i = 0; i < NUMBER_OF_ROWS; i++)
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
mapMatrix[i,j] = 'G';
if (i > 28 && i < 45 && j > 20 && j < 38) {
mapMatrix[i,j] = 'T';
}
}
}
void InstatiateGrassField(int i, int j)
{
if (isGrassMatrixField(i,j))
{
Instantiate (grass, new Vector3 (i, 0, j), Quaternion.identity);
}
}
void InstantiateTreeField(int i, int j)
{
if (isTreeMatrixField(i,j)) {
Instantiate (tree, new Vector3 (i, 0, j), Quaternion.identity);
}
}
void InstantiateEnviroment()
{
for (int i = 0; i < NUMBER_OF_ROWS; i++)
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
//Instantiate a grass prefab
InstatiateGrassField(i, j);
//Instantiate a tree prefab
InstantiateTreeField(i, j);
}
}
void writeTextFile()
{
using (StreamWriter streamWriter = new StreamWriter (pathToFile))
{
for (int i = 0; i < NUMBER_OF_ROWS; i++)
{
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
streamWriter.Write (mapMatrix [i, j]);
//streamWriter.Write (' ');
}
streamWriter.WriteLine();
}
}
}
void readTextFile()
{
using (StreamReader streamReader = new StreamReader(pathToFile))
{
for (int i = 0; i < NUMBER_OF_ROWS; i++)
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
char karakter = (char)streamReader.Read ();
if (karakter == '\n')
{
karakter = (char)streamReader.Read ();
}
mapMatrix [i, j] = karakter;
}
}
}
}

Related

How to Break a For Loop From an If Statement Inside the Loop (C#)

I am working on an A* Pathfinding method that uses a custom class instead of nodes, but am having issues with my loops. The first for loop using int i is able to go up to 3 (Player1.instance.movement = 3), but I need to use an if statement inside of that loop to check if the target position has already been found. I am wondering if it is possible to break my for loop when my If statement is false.
public void GetNeighbors(Tile originTile)
{
Tile originalTile = originTile;
nextTile.Clear();
int minX = 0;
int minY = 0;
var originCostFunc = Mathf.Infinity;
for (int i = 0; i < Player1.instance.movement; i++)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x != y && y != x)
{
var costX = Mathf.Abs((originTile.transform.position.x + x) - originalTile.transform.position.x);
var costY = Mathf.Abs((originTile.transform.position.y + y) - originalTile.transform.position.y);
var distanceX = Mathf.Abs(targetPos.transform.position.x - (originTile.transform.position.x + x));
var distanceY = Mathf.Abs(targetPos.transform.position.y - (originTile.transform.position.y + y));
var costFunc = costX + costY + distanceX + distanceY;
if (costFunc <= originCostFunc)
{
originCostFunc = costFunc;
minX = x;
minY = y;
Debug.Log($"x: {x}, y: {y}");
}
}
}
}
nextTile.Add(GridManagerHandPlaced.instance.GetTileAtPosition(new Vector2(originTile.transform.position.x + minX, originTile.transform.position.y + minY)));
if (nextTile[i] != targetPos)
{
originTile = nextTile[i];
}
else
{
break;
}
}
DisplayPath();
}
You can break loop several times by condition.
bool breakLoop = false;
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
breakLoop = nextTile == target;
if (breakLoop)
break;
}
if (breakLoop)
break;
}
if (breakLoop)
break;
}
Or move search logic to separated method and return a value from any number of nested loops
string path = FindPath();
Display(path);
string FindPath()
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
if (nextTile == target)
return nextTile;
}
}
}
return null;
}
Never use goto operator.
This is one of the few valid cases where I'd use goto. In-fact, this is the example given in the docs for when it should be used.
void CheckMatrices(Dictionary<string, int[][]> matrixLookup, int target)
{
foreach (var (key, matrix) in matrixLookup)
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == target)
{
goto Found;
}
}
}
Console.WriteLine($"Not found {target} in matrix {key}.");
continue;
Found:
Console.WriteLine($"Found {target} in matrix {key}.");
}
}
Note the syntax for the label is simply myLabel: and you can place it anywhere in procedurally executable code.
For sake of covering other ways of handling this situation, here is the boolean solution.
bool breakLoops = false;
for (int i = 0; i < length1; i++)
{
for (int ii = 0; ii < length2; ii++)
{
for (int iii = 0; iii < length3; iii++)
{
if (breakingCondition)
{
breakLoops = true;
break;
}
}
if (breakLoops) break;
}
if (breakLoops) break;
}
Simple and straightforward, but requires a break condition check at the end of each loop that you want to break out of.

Merge sort 2d array c#

I have task to create merge sort algorithm in c# for 2d array. Array looks like that
X1 Y1
X2 Y2
…
Xn Yn
I need to take array from file and sort the lines in ascending x order, also the program should check for the absence of pairs of coordinates with the same X values and at the same time different Y values, when array was sorted, the programm should write it in the file.
I had created algorithm for 1d array, but can't understand how to rewrite it for 2d array, here is my code, please help me
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
class Program
{
//array merging
static void Merge(int[] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left] < num[right])
{
tempArray[index] = num[left];
left++;
}
else
{
tempArray[index] = num[right];
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
for (var i=0;;) {
tempArray[index] = num[j];
index++; }
}
for (var j = right; j <= highIndex; j++)
{
for (var i = 0; ;)
{
tempArray[index] = num[j];
index++;
}
}
for (var j = 0; j < tempArray.Length; j++)
{
for(var i=0; ;)
{
num[lowIndex + j] = tempArray[j];
}
}
}
//merge sorting
static int[] MergeSort(int[] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
return num;
}
public static int[] MergeSort(int[] num)
{
return MergeSort(num, 0, num.Length - 1);
}
static void Main(string[] args)
{
Console.WriteLine("Merge sorting");
string[] lines = File.ReadAllLines(#"C:\Users\glebk\source\repos\ConsoleApp18\ConsoleApp18\file.txt");
int[,] num = new int[lines.Length, lines[0].Split(' ').Length];
for (int i = 0; i < lines.Length; i++)
{
string[] temp = lines[i].Split(' ',',');
for (int j = 0; j < temp.Length; j++)
{
num[i, j] = Convert.ToInt32(temp[j]);
Console.Write(num[i, j]+" ");
}
Console.ReadKey();
}
Console.WriteLine("Sorted array: {0}", string.Join(",", MergeSort(num)));
}
}`
The most direct way of doing it is replacing
tempArray[index] = num[left];
with something like this
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
here is the whole code
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
//array merging
static void Merge(int[,] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1, num.GetLength(1)];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left, 0] < num[right, 0])
{
CopyLine(tempArray, index, num, left);
left++;
}
else
{
CopyLine(tempArray, index, num, right);
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = right; j <= highIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = 0; j < tempArray.GetLength(0); j++)
{
CopyLine(num, lowIndex + j, tempArray, j);
}
}
//merge sorting
static void MergeSort(int[,] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
}
public static void MergeSort(int[,] num)
{
MergeSort(num, 0, num.GetLength(0) - 1);
}
static void WriteArray(string description, int[,] arr)
{
Console.WriteLine(description);
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[,] num = new int[,] { { 3, 5 }, { 1, 10 }, { 7, 3 }, { 2, 1 }, { 5, 2 } };
WriteArray("Original array:", num);
MergeSort(num);
WriteArray("Sorted array:", num);
Console.ReadKey();
}
There are also other options, you can fuse two int values into one long value and sort it as 1D array. But it would need additional steps.

How should weights be optimized with gradient descent algorithm in order to work?

I have a neural network in visual studio. for the loss function I am using a basic cost function (pred-target)**2 and after I finish an epoch I optimize the parameter functions afterwards, but the algorithm doesn't work.
No matter what is my network configuration, the predictions are not write (it is the same output for all the inputs) and the loss function is not optimized. It stays the same through all the epochs.
void calc_lyr(int x, int y, int idx, float target) // thus function calculates the neuron value based on the previous layer
{
if (x == -1 || y == 0) // if its the first layer, get the data from input nodes
{
for (int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for (int j = 0; j < inputTypes.Count; j++)
{
sum += weights[x+1][j][i] * training_test[idx][j];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
else
{
for(int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for(int j = 0; j < neurons[x]; j++)
{
sum += weights[x+1][j][i] * vals[x+1][j] + biases[y][i];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
}
void train()
{
log("Proces de antrenare inceput ----------------- " + DateTime.Now.ToString());
vals = new List<List<float>>();
weights = new List<List<List<float>>>();
biases = new List<List<float>>();
Random randB = new Random(DateTime.Now.Millisecond);
Random randW = new Random(DateTime.Now.Millisecond);
for (int i = 0; i <= nrLayers; i++)
{
progressEpochs.Value =(int)(((float)i * (float)nrLayers) / 100.0f);
vals.Add(new List<float>());
weights.Add(new List<List<float>>());
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
vals[i].Add(0);
}
}
else
{
biases.Add(new List<float>());
for (int j = 0; j < neurons[i-1]; j++)
{
vals[i].Add(0);
float valB = (float)randB.NextDouble();
biases[i-1].Add(valB - ((int)valB));
}
}
}
float valLB = (float)randB.NextDouble();
biases.Add(new List<float>());
biases[nrLayers].Add(valLB - ((int)valLB));
for (int i = 0; i <= nrLayers; i++)
{
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
else if (i == nrLayers)
{
for (int j = 0; j < neurons[i-1]; j++) {
weights[i].Add(new List<float>());
weights[i][j].Add(0);
}
}
else
{
for (int j = 0; j < neurons[i - 1]; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
}
Random rand = new Random(DateTime.Now.Millisecond);
log("\n\n");
for (int i = 0; i < epochs; i++)
{
log("Epoch " + (i + 1).ToString() + " inceput ---> " + DateTime.Now.ToString());
int idx = rand.Next() % training_test.Count;
float target = outputsPossible.IndexOf(training_labels[idx]);
for (int j = 0; j < nrLayers; j++)
{
calc_lyr(j - 1, j, idx, target);
}
float total_val = 0;
for(int x = 0; x < neurons[nrLayers - 1]; x++)
{
float val = relu(weights[nrLayers][x][0] * vals[nrLayers][x] + biases[nrLayers][0]);
total_val += val;
}
total_val = sigmoid(total_val);
float cost_res = cost(total_val, target);
log("Epoch " + (i+1).ToString() + " terminat ----- " + DateTime.Now.ToString() + "\n");
log("Eroare epoch ---> " + (cost_res<1?"0":"") + cost_res.ToString("##.##") + "\n\n\n");
float cost_der = cost_d(total_val, target);
for (int a = 0; a < weights.Count; a++)
{
for (int b = 0; b < weights[a].Count; b++)
{
for (int c = 0; c < weights[a][b].Count; c++)
{
weights[a][b][c]-=cost_der*learning_rate * sigmoid_d(weights[a][b][c]);
}
}
}
for (int a = 0; a < nrLayers; a++)
{
for (int b = 0; b < neurons[a]; b++)
{
biases[a][b] -= cost_der * learning_rate;
}
}
}
hasTrained = true;
testBut.Enabled = hasTrained;
MessageBox.Show("Antrenament complet!");
SavePrompt sp = new SavePrompt();
sp.Show();
}
How can it be changed to optimize the weights, biases and loss function? For now, when I try to debug, the weights are changing, but it is the same value for the loss function.
I solved it by using AForge.NET: link

how to make use of subclass in c#

So Im making tetris and I need to make 7 blocks. The problem is is that I have to copy paste the code in 7 different classes(and then changing the grid) so I thought maybe using subclass would be much easier. The problem is I dont know how to do that.
this is my general block class:
public class Block
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
Texture2D block;
float FallTimer;
public bool FallingBlock = false;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iBlock = new IBlock();
public void HandleInput()
{
if (Tetris.inputHelper.KeyPressed(Keys.Down))
{
FallTimer = 0;
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++) ;
// blokvorm[i, j] += 15;
}
}
}
public void speed(GameTime gameTime)
{
double SpeedCounter = 3;
int LevelCounter = 1;
if (LevelCounter < Tetris.GameWorld.level)
{
SpeedCounter -= 0.5;
LevelCounter++;
}
FallTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (Math.Round(FallTimer, 1) == SpeedCounter)
{
FallTimer = 0;
//BlockPosition.Y += 15;
}
}
public bool[,] blokvorm
{
get
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
{
vorm[i, j] = false;
}
int r = Random.Next(7);
if (r == 0)
{
vorm = ZBlock.zblock();
}
else if (r == 1)
{
vorm = TBlock.tblock();
}
else if (r == 2)
{
vorm = SBlock.sblock();
}
else if (r == 3)
{
vorm = OBlock.oblock();
}
else if (r == 4)
{
vorm = JBlock.jblock();
}
else if (r == 5)
{
vorm = LBlock.lblock();
}
else if (r == 6)
{
vorm = IBlock.iblock();
}
return vorm;
}
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iBlock; }
}
public void Draw(SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
spriteBatch.Begin();
if (!FallingBlock)
{
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++)
if (blokvorm[i, j])
spriteBatch.Draw(block, new Vector2(30 + (i * 15), 30 + (j * 15)), Color.White);
}
spriteBatch.End();
}
}
}
}
So How can I use this class to create other 7 block classes(T, L, I, O etc) easily?
Edit: My block all looks like this:
{
const int x = 4;
const int y = 4;
public bool[,] tblock()
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j <y; j++)
{
vorm[i, j] = false;
vorm[0, 1] = true;
vorm[1, 1] = true;
vorm[1, 0] = true;
vorm[2, 1] = true;
}
Color = Color.Indigo;
return vorm;
}
public void RotationLinks(InputHelper inputhelper)
{
bool[,] nieuw = new bool[x, y];
if (inputhelper.KeyPressed(Keys.Left))
{
for (int a = 0; a < 4; ++a)
for (int b = 0; b < 4; ++b)
nieuw[a, b] = vorm[x - a - 1, b];
vorm = nieuw;
}
}
}
}
So to make other 6 I copied theh whole code and change the grid value. Is there a possible way to make it easier using bock class?

How to sort a 2D array filld with random numbers

I'm doing a class assignment,
I need to create an 2D array of random numbers and sort them either bubble or other sorting codes. I'm fine with single array, but the problem is a 2D array filled with random numbers, I just don't get it.
Random numbers should be made of (-I,I) interval it's a user input. Sorry for bad english, haven't gotten any degree. In working on visual C# windows form.
looking for simple couple cicles method.
example. : A[MxN] ->>> B[MxN] (Sorted 1.....n)
Getting the random numbers is trivial:
Random rnd;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
array[y][x] = l - rnd.Next(2 * l + 1);
Random.Next() will return a random value between 0 and the given parameter (excluding the parameter; which is the reason for the + 1).
A 2D array can be sorted just like a 1D array, it only depends how you want to handle multiple lines, e.g. is it just for display or do you want to sort every line for itself, etc.
Here's a solution which first sorts each row's columns into order, then sorts each row comparing by first column, then second, etc:
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
double[,] data = GenerateData();
OutputData(data, "Before");
SortData(ref data);
OutputData(data, "After");
}
double[,] GenerateData()
{
Random randomGenerator = new Random(DateTime.UtcNow.Millisecond);
double[,] data = new double[5, 5];
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
data[i, j] = (randomGenerator.NextDouble() * 2) - 1;
}
}
return data;
}
void OutputData(double[,] data, string message)
{
Console.WriteLine("=====================");
Console.WriteLine(message);
Console.WriteLine("=====================");
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
Console.Write(data[i, j]);
Console.Write("\t");
}
Console.WriteLine();
}
}
void SortData(ref double[,] data)
{
//sort sub arrays
SortDataRows(ref data);
//sort this array
for (int i = 0; i < data.GetLength(0)-1; i++)
{
for (int j = i; j < data.GetLength(0); j++)
{
for (int k = 0; k < data.GetLength(1); k++)
{
if (data[i, k].CompareTo(data[j, k]) < 0) //if already in order exit loop
{
break;
} else if (data[i, k].CompareTo(data[j, k]) > 0) //if out of order switch and loop
{
SwapRows(ref data, i, j);
break;
}//else orders are equal so far; continue to loop
}
}
}
}
void SortDataRows(ref double[,] data)
{
for (int row = 0; row < data.GetLength(0); row++)
{
for (int i = 0; i < data.GetLength(1) - 1; i++)
{
for (int j = i; j < data.GetLength(1); j++)
{
if (data[row, i].CompareTo(data[row, j]) > 0)
{
Swap<double>(ref data[row, i], ref data[row, j]);
}
}
}
}
}
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
void SwapRows(ref double[,]data, int i, int j)
{
for (int k = 0; k < data.GetLength(1); k++)
{
Swap<double>(ref data[i, k], ref data[j, k]);
}
}
}
}
The code's not the best (haven't had a cup of tea yet), but should do what you're after.
Here's a better solution (not using a 2D array as such, but using a structure which can easily be converted to/from such an array):
sing System.Diagnostics;
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
List<List<double>> data = GenerateData(5, 5).ToList<List<double>>();
OutputData(data,"Before");
foreach (List<double> item in data)
{
item.Sort();
}
data.Sort(CompareListOfDoubles);
OutputData(data,"After");
}
private IEnumerable<List<double>> GenerateData(int index1, int index2)
{
Random rnd = new Random(DateTime.UtcNow.Millisecond);
List<double> result;
for (int i = 0; i < index1; i++)
{
result = new List<double>(index2);
for (int j = 0; j < index2; j++)
{
result.Add(rnd.NextDouble() * 2 - 1);
}
yield return result;
}
}
private void OutputData(List<List<double>> data, string message)
{
Console.WriteLine(message);
foreach (List<double> list in data)
{
foreach (double datum in list)
{
Console.Write(datum);
Console.Write("\t");
}
Console.WriteLine();
}
}
static int CompareListOfDoubles(List<double> a, List<double> b)
{
for (int i = 0; i < a.Count; i++)
{
if (i > b.Count) return -1;
if (a[i] > b[i]) return -1;
if (a[i] < b[i]) return 1;
}
if (b.Count > a.Count) return 1;
return 0;
}
double[,] ConvertListListDoubleTo2DArray(List<List<double>> data)
{
double[,] result = new double[data.Count, data[0].Count];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = data[i][j];
}
}
return result;
}
}

Categories

Resources