Imagine we have 4 vertices (1,2,3,4), and I save them in array that way:
var vertices = new[] { 1, 2, 3, 4 };
var edges = new[]{Tuple.Create(1,2), Tuple.Create(2,4), Tuple.Create(4,3), Tuple.Create(4,1), Tuple.Create(3,2), Tuple.Create(3,1) };
Now it will look like this:
but what if I have more vertices, say 100? How should i generate it? will the loop be linear or not?
if i use something like this:
List<Tuple<int,int>> edges = new List<Tuple<int, int>>();
for (int i=1; i<vertices.Length-1; i++)
{
edges.Add(Tuple.Create(i, i+1));
}
I will eventually just get outline of the graph right?
I can't figure out how to make intersections, like 1 to 3, 2 to 4.
Or if i have graph that is 100 vertices in width and 50 vertices in height, or is not necessarily rectangle?
If you will need some more information i will add it.
i use something like this…I will eventually just get outline of the graph right?
Correct.
How should i generate it?
If I understand your question correctly, you just want all the possible combinations of vertexes. This is simple:
List<Tuple<int,int>> edges = new List<Tuple<int, int>>();
for (int i = 1; i < vertices.Length - 1; i++)
{
for (int j = i + 1; j < vertices.Length; j++)
{
edges.Add(Tuple.Create(i, j));
}
}
In other words, this is just a variation on the Handshake Problem.
will the loop be linear or not?
As you can see above, definitely not. It is O(n^2).
Related
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:
I am trying to complete a game over condition for a peg solitaire game i am writing.
I have all of the movements and pieces removing as they should.
Each piece is held within a 2d array as an Ellipse UI Ellement and when a piece is taken it is replaced with a border Ui Element.
I have started to use a method adapted from a Stackoverflow post that scans the 8 adjacent squares around the array element.
public static IEnumerable<T> AdjacentElements<T>(T[,] arr, int row, int column)
{
int rows = arr.GetLength(0);
int columns = arr.GetLength(1);
for (int j = row - 1; j <= row + 1; j++)
for (int i = column - 1; i <= column + 1; i++)
if (i >= 0 && j >= 0 && i < columns && j < rows && !(j == row && i == column))
yield return arr[j, i];
}
}
The method called once a piece is taken.
var results = AdjacentElements(grid, 3, 3);
foreach (var result in results)
Debug.WriteLine(result);
When it encounters an ellipse it should check the squares directly above,below,left and right of the Ellipse, at the moment is all 8 squares, i only need four (top, bottom, left and right).
I am using grid reference 3,3 to test at the moment and it is printing out as expected but for all 8 squares.
If any of the four squares in turn encounter and ellipse the next square in a straight line should be a Border in order to be a possible move.
For example:
Circle 1 is the Ellipse being checked.
The circles below,left and right are ignored.
The Cirle 2 is chosen as Square 3 is empty.
This would produce a valid move so the game would continue.
If no valid move is found the game will end.
I not sure how to proceed with this, I was thinking of putting the method call inside a nested for loop to go over every element but I'm thinking it would be very inefficient.
var results = AdjacentElements(grid, i, j);
foreach (var result in results)
//condition here
I don't think i truly understand what you want to do. However, yes you could do nested loops. but sometimes its just easier to poke at it
Given some array x, y
var x = 23;
var y = 3;
Exmaple
var checks = List<Point>();
checks.Add(new Point(x+1,y));
checks.Add(new Point(x-1,y));
checks.Add(new Point(x,y+1));
checks.Add(new Point(x,y-1));
foreach(var check in checks)
//If Bounds check
//do what you need to do
I'd like to know how to write a program in 2D array to exchange the elements of main diagonal with secondary diagonal then print the result
like this
3 2 7
4 5 3
2 8 9
and the result show like this
7 2 3
4 5 3
9 8 2
Actually it's not a very specific problem, but as I don't see the part where you're stuck I'll try to explain a whole example to you:
static int[,] GetDiagonallySwitched(int[,] oldMatrix)
{
var newMatrix = (int[,])oldMatrix.Clone();
for (var i = 0; i < oldMatrix.GetLength(0); i++)
{
var invertedI = oldMatrix.GetLength(0) - i - 1;
newMatrix[i, i] = oldMatrix[i, invertedI];
newMatrix[i, invertedI] = oldMatrix[i, i];
}
return newMatrix;
}
First of all I'm cloning the old matrix, because a few values actually remain the same. Then I switch the values from the left side to the right side. I'm doing this with the invertedI, which basically is i from the other side - so that in the end the cross is mirrored and it seems as though the lines switched. This is working for any size of the matrix.
For the printing: If you actually want to print it bold, you'll have to use a RTB in WinForms, but I don't guess this was part of your question. Otherwise you could use this code to print the matrix:
static void Print(int[,] switched)
{
for (var y = 0; y < switched.GetLength(0); y++)
{
for (var x = 0; x < switched.GetLength(1); x++)
Console.Write(switched[y, x]);
Console.WriteLine();
}
}
I hope I could help you.
I was wondering if there is a method to order intersection points in a list based on the direction of the intersected line.
Here is a picture to get the idea:
The red numbers are the polygon lines which exist in a List.
Then I have another List with lines which are parallels of one polygon line intersecting the polygon at a certain offset (image shows parallels of poly line nr. 4).
Iterating through them I get the intersections points displayed in black numbers.
My problem now is that I would like to have the intersection points ordered like shown in the picture. But when iterating through every parallel the order of the intersections found changes at the 22nd intersection point.
Because the algorithm finds the intersection at poly line 1 first because I'm going through the list.
I hope you know what I mean.
I would like to find the intersection points always in the same pattern like shown.
The only idea I came up with is to transform the current line on the coordinate axis and then sort the 2 intersections by x-value but I assume that this is very bad...
I'd appreciate every answer which leads me to the solution.
Thanks in advance
Here's my code snippet:
for (int i = 0; i < parallelLines.Count; i++)
{
for (int j = 0; j < polyLines.Count; j++)
{
var actual = ber.LineSegementsIntersect(
parallelLines[i].v1,
parallelLines[i].v2,
polyLines[j].v1,
polyLines[j].v2,
out intersection);
// if intersection is found
if (actual)
{
intersections.Add(intersection);
}
}
}
iterate through the lines first in an outer loop, then for each line get the 2 points in the specific order you want.
Modify your code to put the two found itxns in temporary list, instead of directly into intersections collection - then, in between the inner and outer loop add those two intx objects to the intersections collection in the proper order ((the one with smaller x value first, or whatever rule you want)
like this: (Assume IntersectionType is the declared type of your Intersection object)
for (int i = 0; i < parallelLines.Count; i++)
{
var pair = new List<IntersectionType>();
for (int j = 0; j < polyLines.Count; j++)
{
var actual = ber.LineSegementsIntersect(
parallelLines[i].v1,
parallelLines[i].v2,
polyLines[j].v1,
polyLines[j].v2,
out intersection);
// if intersection is found
if (actual) pair .Add(intersection);
}
intersections.Add(pair.OrderBy(i=>i.XValue).First());
intersections.Add(pair.OrderByDescending(i=>i.XValue).First());
}
oh, by the way, the variable actual, if it is what I think it is, should be renamed as found, or, better, refactor as:
for (int i = 0; i < parallelLines.Count; i++)
{
var pair = new List<IntersectionType>();
for (int j = 0; j < polyLines.Count; j++)
if(ber.LineSegementsIntersect(
parallelLines[i].v1, parallelLines[i].v2,
polyLines[j].v1, polyLines[j].v2,
out intersection))
pair .Add(intersection);
intersections.Add(pair.OrderBy(i=>i.XValue).First());
intersections.Add(pair.OrderByDescending(i=>i.XValue).First());
}
I've been thinking about trying to create a RPG game, a simple game with movement, pick up items, and open doors.
I've been thinking for a long time about the tile map engine, but i can't find anything that works :/
Basically what i'm trying to accomplish is i have an enum, like:
public enum tileSort { Dirt, Grass, Stone, Empty }
And when the engine runs through the array, which will have 0's, 1's, etc, I'm thinking about a switch statement, something like:
switch(tileSort)
{
case '0': tileList.Add(Content.Load<Texture2D>("Tiles/grass"))
}
The problem is that I have no idea on how to make this possible, all that I've been able to create is an engine that runs through and generates depending on which content you load first into the game.
I know this is confusing, as I'm not good at explaining myself.
Thanks in advance.
You can use some tools to help you:
http://jdevh.com/2012/06/01/griddy2d/
http://github.com/zachmu/tiled-xna
http://xnafantasy.wordpress.com/2008/11/22/xna-map-editor-version-30-released/
I'm sure you can find many others.
About the snippets of code you wrote, you don't want to call
Content.Load<Texture2D>("Tiles/grass")
multiple times for a single texture. Load each texture only once and print the same resource multiple times. You could have something like this:
var tileList = new List<Texture2D>();
string[] tiles = { "dirt", "grass", "stone", "empty" };
foreach (var s in tiles) {
tileList.Add(Content.Load<Texture2D>("Tiles/" + s));
}
Now each texture is loaded only once, and you can access it using tileList[index].
The next step is to print the tiles on the screen. I'll assume you have loaded your tiles into a 2 dimensional array with the tile indexes.
int[,] tileMap = {{1, 2, 0}, {0, 1, 2}, {3, 3, 1},};
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
spriteBatch.Draw(tileList[tileMap[i, j]], new Vector2D(50*i, 50*j), Color.White);
// Assuming the tiles are 50x50 pixels
This tutorial teaches what you want with more details: http://www.xnaresources.com/?page=Tutorial:TileEngineSeries:1