Read a matrix from a text file in c# - c#

I need to read a text file that contains the matrix, instead of having it on the code like I have, but I tried and I can't figure it out.
I have the matrix on a text file like I have on the code, but without the comas
This is a dijkstra program that reads the matrix in order to find the shortest path, thank you
{
private static int MinimumDistance(int[] distance, bool[] shortestPathTreeSet, int verticesCount)
{
int min = int.MaxValue;
int minIndex = 0;
for (int v = 0; v < verticesCount; ++v)
{
if (shortestPathTreeSet[v] == false && distance[v] <= min)
{
min = distance[v];
minIndex = v;
}
}
return minIndex;
}
private static void Print(int[] distance, int verticesCount)
{
Console.WriteLine("Vertex Distance from source");
for (int i = 0; i < verticesCount; ++i)
Console.WriteLine("{0}\t {1}", i, distance[i]);
}
public static void DijkstraAlgo(int[,] graph, int source, int verticesCount)
{
int[] distance = new int[verticesCount];
bool[] shortestPathTreeSet = new bool[verticesCount];
for (int i = 0; i < verticesCount; ++i)
{
distance[i] = int.MaxValue;
shortestPathTreeSet[i] = false;
}
distance[source] = 0;
for (int count = 0; count < verticesCount - 1; ++count)
{
int u = MinimumDistance(distance, shortestPathTreeSet, verticesCount);
shortestPathTreeSet[u] = true;
for (int v = 0; v < verticesCount; ++v)
if (!shortestPathTreeSet[v] && Convert.ToBoolean(graph[u, v]) && distance[u] != int.MaxValue && distance[u] + graph[u, v] < distance[v])
distance[v] = distance[u] + graph[u, v];
}
Print(distance, verticesCount);
}
static void Main(string[] args)
{
int[,] graph = {
{ 0, 6, 0, 0, 0, 0, 0, 9, 0 },
{ 6, 0, 9, 0, 0, 0, 0, 11, 0 },
{ 0, 9, 0, 5, 0, 6, 0, 0, 2 },
{ 0, 0, 5, 0, 9, 16, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 0, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 16, 0, 2, 0, 1, 6 },
{ 9, 11, 0, 0, 0, 0, 1, 0, 5 },
{ 0, 0, 2, 0, 0, 0, 6, 5, 0 }
};
DijkstraAlgo(graph, 0, 9);
}
}
}
and here is the text file matrix:
0 6 8 12 0 0 0 0 0 0
6 0 0 5 0 0 0 0 0 0
8 0 0 1 0 0 0 0 0 0
12 5 1 0 9 10 14 16 15 0
0 0 0 9 0 0 3 0 0 0
0 0 0 10 0 0 0 0 13 0
0 0 0 14 3 0 0 3 0 6
0 0 0 16 0 0 3 0 1 4
0 0 0 15 0 13 0 1 0 7
0 0 0 0 0 0 6 4 7 0

If i understand you correctly.
You are after a way to read a space deliminated ints from a file and convert it into a multidimensional (square) array of int. e.g int[,]
You could do something like this
Given
public static class Extensions
{
public static T[,] ToRectangularArray<T>(this IReadOnlyList<T[]> arrays)
{
var ret = new T[arrays.Count, arrays[0].Length];
for (var i = 0; i < arrays.Count; i++)
for (var j = 0; j < arrays[0].Length; j++)
ret[i, j] = arrays[i][j];
return ret;
}
}
Usage
var someArray = File.ReadAllLines("myAwesomeFile") // read from File
.Select(x => x.Split(' ').Select(int.Parse).ToArray()) // split line into array of int
.ToArray() // all to array
.ToRectangularArray(); // send to multidimensional array

Related

C# locate value in a array and move it to right

My task is to find a element in the array that is the same as given value, and then take it to right while maintaining the order of other elements. An example (Test Case):
{1, 2, 0, 1, 0, 1, 0, 3, 0, 1} for value = 0 => {1, 2, 1, 1, 3, 1, 0, 0, 0, 0}
While my code could do that above example, what it could not do is a very specific case: if the element in array equals value and the next element also equals value it will not shift the element. Again a example:
{ 1, int.MinValue, int.MinValue, int.MaxValue, int.MinValue, -1, -3, -9, 1 }, value = int.MinValue
Expected result: { 1, int.MaxValue, -1, -3, -9, 1, int.MinValue, int.MinValue, int.MinValue }
Result with my code: { 1, int.MinValue ,int.MaxValue, -1, -3, -9, 1, int.MinValue, int.MinValue }
I thought shifting is the one solution, is it? I am having a lot of problems with it, I also tried Array.Copy but there were problems the result was always out of range.
How can I make it so that it will shifts/rotates correctly in all cases?
Code:
static void Main(string[] args)
{
int[] source = new int[] { 1, int.MinValue, int.MinValue, int.MaxValue, int.MinValue, -1, -3, -9, 1 };
int value = int.MinValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] == value)
{
LeftShiftArray(source, i);
}
}
for (int i = 0; i < source.Length; i++)
{
Console.WriteLine(source[i]);
}
}
public static void LeftShiftArray(int[] source, int i)
{
var temp1 = source[i];
for (var j = i; j < source.Length - 1; j++)
{
source[j] = source[j + 1];
}
source[source.Length - 1] = temp1;
}
Now this
I have a simple approach to solve this problem. Run a loop, You keep on counting the numbers which are not equal to your number. And keep assigning to arr[count]. Then increment the count. And then finally you will be left to assign all the remaining numbers with the given number.
static void MoveToEnd(int []arr, int n)
{
int count = 0;
    for (int i = 0; i < arr.Length; i++)
        if (arr[i] != n)
         arr[count++] = arr[i];
    while (count < arr.Length)
        arr[count++] = n;
}
Please note I have typed this answer from phone, so please avoid typing mistakes.
This is a classic off by one error. Think about it like this:
Let's say you are moving all 0s to the back (value = 0). When you find a zero at some position, let's say source[2], you turn your array from this:
1 1 0 0 1 1
source[2] ^
To this:
1 1 0 1 1 0
source[2] ^
Now that you've shifted the array, the next step in your code is to increase i by 1. That means the next comparison you make will be with source[3]. In the above array, that looks like this:
1 1 0 1 1 0
source[3] ^
Do you see the problem? Let me know if not and I can explain further.
PS. There are a couple of issues with the other code that was posted that will probably stop you from getting full points if you were to turn it in for an assignment :)

IndexError in array PYTHON

I am tring to write this C# function in Python, unfortunatly I have this ERROR: IndexError: list assignment index out of range in Population.BinaryX.insert([i][j], dec) line. Can anyone tell me how can I fix this problem?! What`s wrong I did?
C# CODE:
public class Population
{
public float[] CodedX = new float[20];
public float[,] BinaryX = new float[10, 8];
}
private void BinaryTranslating()
{
int dec;
int j = 0;
for (var i = 0; i < 10; i++)
{
while (Population.CodedX[i] > 1 & j < 8)
{
dec = (int)Population.CodedX[i] % 2;
Population.BinaryX[i, j] = dec;
Population.CodedX[i] /= 2;
j++;
}
j = 0;
}
}
private void DecimalTranslating()
{
for (var i = 0; i < 10; i++)
{
Population.CodedX[i] = Population.BinaryX[i, 7] * 128 + Population.BinaryX[i, 6] * 64 +
Population.BinaryX[i, 5] * 32 + Population.BinaryX[i, 4] * 16 +
Population.BinaryX[i, 3] * 8 + Population.BinaryX[i, 2] * 4 +
Population.BinaryX[i, 1] * 2 + Population.BinaryX[i, 0];
}
}
Python CODE:
class Population:
CodedX = []
BinaryX = [[], []]
class Application:
#staticmethod
def binary_translating():
j = 0
for i in range(10):
while Population.CodedX[i] > 1 & j < 8:
dec = int(Population.CodedX[i]) % 2
Population.BinaryX.insert([i][j], dec)
Population.CodedX[i] /= 2
j += 1
j = 0
#staticmethod
def decimal_translating():
for i in range(10):
new_item = Population.BinaryX[i][7] * 128 + Population.BinaryX[i][6] * 64 + Population.BinaryX[i][5] * 32 +\
Population.BinaryX[i][4] * 16 + Population.BinaryX[i][3] * 8 + Population.BinaryX[i][2] * 4 +\
Population.BinaryX[i][1] * 2 + Population.BinaryX[i][0]
Population.CodedX.insert(i, new_item)
Consider the [i][j] expression in Population.BinaryX.insert([i][j], dec). That expression creates a 1 item list containing the value of i and then tries to take the jth item from that list.
>>> i=1
>>> j=2
>>> [i][j]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Python lists are one dimensional and if you want a multidimensional list, you need to create a list of lists or use some other structure such as a numpy or pandas array.
One option is to preallocate the array with a known value so that you can simply index it later
#staticmethod
def binary_translating():
Population.BinaryX = [[None] * 8 for _ in range(10)]
j = 0
for i in range(10):
while Population.CodedX[i] > 1 & j < 8:
dec = int(Population.CodedX[i]) % 2
Population.BinaryX[i][j] = dec
Population.CodedX[i] /= 2
j += 1
j = 0
Another option is to insert into the sublist:
#staticmethod
def binary_translating():
Population.BinaryX = []
j = 0
for i in range(10):
Population.BinaryX.insert([])
while Population.CodedX[i] > 1 & j < 8:
dec = int(Population.CodedX[i]) % 2
Population.BinaryX[i].insert(j, dec)
Population.CodedX[i] /= 2
j += 1
j = 0
please make sure that Population.BinaryX is a valid entity and has at least 10 element in it because you are running the loop 10 times. Same goes for CodedX.
If either of them do not have at least 10 elements, you will get
IndexError: list assignment index out of range
Try..
class Population:
CodedX = [0 for i in range(10)]
BinaryX = [[0 for i in range(10)] for j in range(10)]
This is preallocating as mentioned by tdelaney.
If you look at each functions in the Application class, they try to use either BinaryX or CodedX arrays but if these arrays do not have any elements in them, then how will python index into them?
What I mean is before calling the decimal_translating() function, the Population.BinrayX must have elements in it. It cannot be empty array.
Similarly, before calling the binary_translating() function, Population.CodedX must have elements in it.
[edit #1]
After your comments and trying to understand your code.Here is what I have:-
class Population(object):
def __init__(self):
self.CodedX = [0 for i in range(10)] # as per your C# code
self.BinaryX = []
# debug code to fill CodedX array - remove it
for i in range(10):
self.CodedX[i] = int(761)
def binary_translating(self):
for i in range(10):
j = 0
self.BinaryX.append([0 for k in range(10)])
while (self.CodedX[i] > 0) and (j < 10):
dec = int(self.CodedX[i] % 2)
self.BinaryX[i][j] = dec # this will append at j
self.CodedX[i] = int(self.CodedX[i] / 2)
j += 1
# debug code to print - remove it
print(self.BinaryX)
# debug code to clear CodedX - remove it
for i in range(10):
self.CodedX[i] = int(0)
def decimal_translating(self):
for i in range(10):
value = self.BinaryX[i][7] * 128 + self.BinaryX[i][6] * 64 + self.BinaryX[i][5] * 32 + \
self.BinaryX[i][4] * 16 + self.BinaryX[i][3] * 8 + self.BinaryX[i][2] * 4 + \
self.BinaryX[i][1] * 2 + self.BinaryX[i][0]
self.CodedX[i] = value
print(self.CodedX)
pop = Population()
pop.binary_translating()
pop.decimal_translating()
I have added some debug code to have some starting values in CodedX and print statements for you to see the output.
generates the output:
[[1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1, 0, 1]]
[249, 249, 249, 249, 249, 249, 249, 249, 249, 249]
[edit #2]

what is wrong with using List.AddRange(Array) method in c#?

program in c# ,create a new array(temp) has different size from mp4v(large array) then copy this array(temp) to List (a)
program is:
{
int size; int i = 0;
Int32 [] mp4v=new Int32 [10]{1,12,1,2,11,1,10,4,1,5};
List<Int32> a = new List<Int32>();
Int32[] sz = new Int32[] { 3, 3, 4 };
for (int k = 0; k < 3; k++)
{
size = sz[k];
Int32[] temp = new Int32[size];
Array.Copy(mp4v, i, temp, 0, size);
a.AddRange(temp);
i = i + size;
}
for ( i = 0; i < a.Count; i++)
Console.WriteLine("0", a[i]);
}
output :
0
0
0
0
0
0
0
0
0
0
what is wrong in this program, the result must be like this:
1
12
1
2
11
1
10
4
1
5
It should be Console.WriteLine( "{0}", a[i] ). The string "0" will output 0 everytime, and to use parameter replacement the syntax is {x} where x is the parameter index in the list

Closed path in the two-dimensional array

There is two-dimensional array of zeros and ones. Need algorithm (the implementation) that determines whether in this array closed path of ones, that surround the zeros
Example:
there EXISTS a closed path(center):
1 0 0 0 0
0 0 1 0 0
0 1 0 1 0
0 0 1 1 0
0 0 1 0 0
there is NO
0 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 0 1 0 1
0 1 0 1 0
You can look at Connected Components Labeling algorithms, e.g. in Wikipedia or google for them. These algorithms are used e.g. to separate foreground pixels from background pixels in a digital white/black image. To apply them to your specific problem, you can think of your matrix as a digital image where 0 means foreground and 1 means background (or vice versa according to your needs). The algorithm finds largest connected foreground regions (containing only 0) that are surrounded by the background (1's). So, if you found such a foreground region you know there is a cycle of 1's surrounding it. When the foreground region is at the boundary you can decide whether you consider it as surrounded or not.
It's homework so I'll just give a general sketch. Construct an undirected graph; each 1 is a node, adjacent 1s have an edge between them. Google for undirected graph cycle detection to find closed paths. Then you have to go back to the original matrix and make sure there's at least one 0 inside.
Another idea would be to flood-fill starting at each 0 bounded by 1s. If it doesn't reach an edge, it's surrounded.
Here is sample code i tried. test it through
Logic i tried is loop through all the rows except first and last row.
if you find 0 then check it neighbour to left,right,top and bottom if all the neighbours are 1 then closed.
private void Form1_Load(object sender, EventArgs e)
{
int[,] graph = new int[5, 5] {
{ 1, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 0 },
{ 0, 0, 1, 0, 0 }
};
int[,] graph1 = new int[5, 5] {
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 1, 0, 1, 0 }
};
isClosed(graph1);
}
private bool isClosed(int[,] graph)
{
for (int i = 1; i < graph.GetUpperBound(0); i++)
{
for (int j = 1; j < graph.GetUpperBound(1); j++)
{
if (graph[i, j] == 0)
{
if (graph[i - 1, j] == 1 && graph[i + 1, j] == 1 && graph[i, j - 1] == 1 && graph[i, j + 1] == 1)
{
return true;
}
}
}
}
return false;
}

Rotate 2D Array by 45 degrees

How can I rotate a 2D rectangular array of integers that has odd number of rows by 45 degrees?
So something like
int[] myArray = new int[,]
{
{1, 0 ,1},
{0, 1 ,0},
{0, 0 ,0},
}
into
int[] rotatedArray = new int[,]
{
{0, 1 ,0},
{0, 1 ,1},
{0, 0 ,0},
}
for any dimension (3x3, 5x5, 7x7, etc.).
5x5
0 0 0 0 0
2 0 0 0 0
1 1 1 1 1
0 0 0 0 0
0 0 0 0 0
into
1 2 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
5x5
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
into
0 0 0 0 0
0 0 0 0 3
0 0 0 3 0
0 0 3 3 0
0 3 0 0 0
This is a code written by me and a friend that solves this:
public static class ArrayExtensions
{
public static Point RoundIndexToPoint(int index, int radius)
{
if (radius == 0)
return new Point(0, 0);
Point result = new Point(-radius, -radius);
while (index < 0) index += radius * 8;
index = index % (radius * 8);
int edgeLen = radius * 2;
if (index < edgeLen)
{
result.X += index;
}
else if ((index -= edgeLen) < edgeLen)
{
result.X = radius;
result.Y += index;
}
else if ((index -= edgeLen) < edgeLen)
{
result.X = radius - index;
result.Y = radius;
}
else if ((index -= edgeLen) < edgeLen)
{
result.Y = radius - index;
}
return result;
}
public static T[,] Rotate45<T>(this T[,] array)
{
int dim = Math.Max(array.GetLength(0), array.GetLength(0));
T[,] result = new T[dim, dim];
Point center = new Point((result.GetLength(0) - 1) / 2, (result.GetLength(1) - 1) / 2);
Point center2 = new Point((array.GetLength(0) - 1) / 2, (array.GetLength(1) - 1) / 2);
for (int r = 0; r <= (dim - 1) / 2; r++)
{
for (int i = 0; i <= r * 8; i++)
{
Point source = RoundIndexToPoint(i, r);
Point target = RoundIndexToPoint(i + r, r);
if (!(center2.X + source.X < 0 || center2.Y + source.Y < 0 || center2.X + source.X >= array.GetLength(0) || center2.Y + source.Y >= array.GetLength(1)))
result[center.X + target.X, center.Y + target.Y] = array[center2.X + source.X, center2.Y + source.Y];
}
}
return result;
}
}
You can try this library:
Math.NET Project for matrices operations... http://numerics.mathdotnet.com/
This code appears to be useful too:
http://www.drunkenhyena.com/cgi-bin/view_net_article.pl?chapter=2;article=28#Rotation
Don't forget the DirectX managed and unmanaged namespaces and classes. Lots
and lots of good stuff there to check.
For example:
Matrix..::.Rotate Method (Single, MatrixOrder)
I think we have these rules:
Imagine the matrix as a set of "frames or boxes without centers" within each other like "Russian dolls".
Elements at the center of a side (top/left/right/bottom) move towards the nearest corner clockwise.
Corners move towards the next center clockwise.
Elements that are not corners nor centers move to the next spot (clockwise) that is the same distance from a corner as they currently are.
I've started writing some code but I don't think it's trivial and I haven't had time to test.
You can see my solution for the matrix rotation in codesignal

Categories

Resources