Calculate the distance for each x and y coordinate - c#

I am writing a function that calculates distance from x and y coordinate. I have a two dimensional array that has bunch of x and y coordinates.
Function returns a list of x and y coordinates in the order of distance from a point. To calculate the distance from each point there is a formula(Square root of sum of coordinates).
I can calculate the distance for each x and y coordinate. I am adding that to list. How do I store distance as another property as it is for that particular coordinate and then sort it.
public static List<List<int>> calculateDistance(int[,] Coordinates)
{
List<List<int>> result = new List<List<int>>();
int bound0 = Coordinates.GetUpperBound(0);
List<double> distance = new List<double>();
for (int i = 0;i <= bound0; i++)
{
distance.Add(Math.Sqrt(Coordinates[i, 0]) + Coordinates[i,1]));
}
return result;
}
}

Based on your description you don't need to create a calculateDistance method. Formula to calculate distance can be given with lambda expression. Anywhere in your code you can create the list you need and get it sorted with Linq.
Example
var list = Enumerable
.Range(0, Coordinates.GetLength(0))
.Select(i => new { X = Coordinates[i, 0], Y = Coordinates[i, 1], D = Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2)) });
Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2)) is used here for demonstration. Instead use your own expression to calculate the distance.
To sort this you can simply use
var list2 = list.OrderBy(a => a.D);

It would be more helpful if you try to define proper data structures for your inputs and your output. It could be something as simple as a tuple, or something more idiomatic like a struct or a class.
struct Coordinate {
public Coordinate(int x, int y) {
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
}
Then define a result structure, something like:
struct Result {
public Result(Coordinate coordinate, double distance) {
Coordinate = coordinate;
Distance = distance;
}
public Coordinate Coordinate { get; }
public double Distance { get; }
}
Then you can create a list of those result items like:
public List<Result> ComputeDistances(List<Coordinate> coordinates) {
List<Result> results = new List<Result>();
foreach (var coordinate in coordinates) {
double distance = Math.Sqrt(coordinate.X + coordinate.Y); // *
results.Add(new Result(coordinate, distance));
}
return results;
}
(*) Note that the specified distance function is a little bit odd. Normally you would like to sum the squares of the X and Y coordinate
If you like a more functional style, you can change that code quite a bit:
public IEnumerable<Result> ComputeDistances(IEnumerable<Coordinate> coordinates) {
return from coordinate in coordinates
let distance = Math.Sqrt(coordinate.X + coordinate.Y)
select new Result(coordinate, distance);
}
Changing from List to IEnumerable allows you with the proper care, to delay the execution of the computation.
After you have the sequence of results, the easiest way to sort them is using the OrderBy extension method.
public IEnumerable<Result> SortByDistance(IEnumerable<Result> results)
{
return results.OrderBy(result => result.Distance);
}
And then combine all:
List<Coordinate> coordinates = .... // get the list of coordinates somehow;
IEnumerable<Result> distances = ComputeDistances(coordinates);
IEnumerable<Result> sortedByDistance = SortByDistance(distances);
// if you want to get back a list, in order to avoid enumerating multiple times
List<Result> results = sortedByDistance.ToList();

Related

Check if an stl file may contain two models

An stl file may contain 2 3D models. Is there any way I can detect if there are 2 or more models stored in one stl file?
In my current code, it can detect that there are 2 models in the example, but there are instances that it detects a lot of model even though it only has one.
The Triangle class structure has Vertices that contains 3 points (x, y, z)..
Sample STL File:
EDIT: Using #Gebb's answer this is how I implemented it:
private int GetNumberOfModels(List<TopoVertex> vertices)
{
Vertex[][] triangles = new Vertex[vertices.Count() / 3][];
int vertIdx = 0;
for(int i = 0; i < vertices.Count() / 3; i++)
{
Vertex v1 = new Vertex(vertices[vertIdx].pos.x, vertices[vertIdx].pos.y, vertices[vertIdx].pos.z);
Vertex v2 = new Vertex(vertices[vertIdx + 1].pos.x, vertices[vertIdx + 1].pos.y, vertices[vertIdx + 1].pos.z);
Vertex v3 = new Vertex(vertices[vertIdx + 2].pos.x, vertices[vertIdx + 2].pos.y, vertices[vertIdx + 2].pos.z);
triangles[i] = new Vertex[] { v1, v2, v3 };
vertIdx += 3;
}
var uniqueVertices = new HashSet<Vertex>(triangles.SelectMany(t => t));
int vertexCount = uniqueVertices.Count;
// The DisjointUnionSets class works with integers, so we need a map from vertex
// to integer (its id).
Dictionary<Vertex, int> indexedVertices = uniqueVertices
.Zip(
Enumerable.Range(0, vertexCount),
(v, i) => new { v, i })
.ToDictionary(vi => vi.v, vi => vi.i);
int[][] indexedTriangles =
triangles
.Select(t => t.Select(v => indexedVertices[v]).ToArray())
.ToArray();
var du = new XYZ.view.wpf.DisjointUnionSets(vertexCount);
// Iterate over the "triangles" consisting of vertex ids.
foreach (int[] triangle in indexedTriangles)
{
int vertex0 = triangle[0];
// Mark 0-th vertexes connected component as connected to those of all other vertices.
foreach (int v in triangle.Skip(1))
{
du.Union(vertex0, v);
}
}
var connectedComponents =
new HashSet<int>(Enumerable.Range(0, vertexCount).Select(x => du.Find(x)));
return connectedComponents.Count;
}
In some cases, it produces the correct output, but for the example image above, it outputs 3 instead of 2. I am now trying to optimize the snippet #Gebb gave to use float values since I believe that the floating points are necessary to the comparisons. Does anyone have a way to do that as well? Maybe I need another perspective.
You could do this by representing vertices and connections between them as a graph and finding the number of connected components of the graph with the help of the Disjoint-set data structure.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Vertex = System.ValueTuple<double,double,double>;
namespace UnionFindSample
{
internal class DisjointUnionSets
{
private readonly int _n;
private readonly int[] _rank;
private readonly int[] _parent;
public DisjointUnionSets(int n)
{
_rank = new int[n];
_parent = new int[n];
_n = n;
MakeSet();
}
// Creates n sets with single item in each
public void MakeSet()
{
for (var i = 0; i < _n; i++)
// Initially, all elements are in
// their own set.
_parent[i] = i;
}
// Finds the representative of the set
// that x is an element of.
public int Find(int x)
{
if (_parent[x] != x)
{
// if x is not the parent of itself, then x is not the representative of
// his set.
// We do the path compression by moving x’s node directly under the representative
// of this set.
_parent[x] = Find(_parent[x]);
}
return _parent[x];
}
// Unites the set that includes x and
// the set that includes x
public void Union(int x, int y)
{
// Find representatives of two sets.
int xRoot = Find(x), yRoot = Find(y);
// Elements are in the same set, no need to unite anything.
if (xRoot == yRoot)
{
return;
}
if (_rank[xRoot] < _rank[yRoot])
{
// Then move x under y so that depth of tree remains equal to _rank[yRoot].
_parent[xRoot] = yRoot;
}
else if (_rank[yRoot] < _rank[xRoot])
{
// Then move y under x so that depth of tree remains equal to _rank[xRoot].
_parent[yRoot] = xRoot;
}
else
{
// if ranks are the same
// then move y under x (doesn't matter which one goes where).
_parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
_rank[xRoot] = _rank[xRoot] + 1;
}
}
}
internal class Program
{
private static void Main(string[] args)
{
string file = args[0];
Vertex[][] triangles = ParseStl(file);
var uniqueVertices = new HashSet<Vertex>(triangles.SelectMany(t => t));
int vertexCount = uniqueVertices.Count;
// The DisjointUnionSets class works with integers, so we need a map from vertex
// to integer (its id).
Dictionary<Vertex, int> indexedVertices = uniqueVertices
.Zip(
Enumerable.Range(0, vertexCount),
(v, i) => new {v, i})
.ToDictionary(vi => vi.v, vi => vi.i);
int[][] indexedTriangles =
triangles
.Select(t => t.Select(v => indexedVertices[v]).ToArray())
.ToArray();
var du = new DisjointUnionSets(vertexCount);
// Iterate over the "triangles" consisting of vertex ids.
foreach (int[] triangle in indexedTriangles)
{
int vertex0 = triangle[0];
// Mark 0-th vertexes connected component as connected to those of all other vertices.
foreach (int v in triangle.Skip(1))
{
du.Union(vertex0, v);
}
}
var connectedComponents =
new HashSet<int>(Enumerable.Range(0, vertexCount).Select(x => du.Find(x)));
int count = connectedComponents.Count;
Console.WriteLine($"Number of connected components: {count}.");
var groups = triangles.GroupBy(t => du.Find(indexedVertices[t[0]]));
foreach (IGrouping<int, Vertex[]> g in groups)
{
Console.WriteLine($"Group id={g.Key}:");
foreach (Vertex[] triangle in g)
{
string tr = string.Join(' ', triangle);
Console.WriteLine($"\t{tr}");
}
}
}
private static Regex _triangleStart = new Regex(#"^\s+outer loop");
private static Regex _triangleEnd = new Regex(#"^\s+endloop");
private static Regex _vertex = new Regex(#"^\s+vertex\s+(\S+)\s+(\S+)\s+(\S+)");
private static Vertex[][] ParseStl(string file)
{
double ParseCoordinate(GroupCollection gs, int i) =>
double.Parse(gs[i].Captures[0].Value, CultureInfo.InvariantCulture);
var triangles = new List<Vertex[]>();
bool isInsideTriangle = false;
List<Vertex> triangle = new List<Vertex>();
foreach (string line in File.ReadAllLines(file))
{
if (isInsideTriangle)
{
if (_triangleEnd.IsMatch(line))
{
isInsideTriangle = false;
triangles.Add(triangle.ToArray());
triangle = new List<Vertex>();
continue;
}
Match vMatch = _vertex.Match(line);
if (vMatch.Success)
{
double x1 = ParseCoordinate(vMatch.Groups, 1);
double x2 = ParseCoordinate(vMatch.Groups, 2);
double x3 = ParseCoordinate(vMatch.Groups, 3);
triangle.Add((x1, x2, x3));
}
}
else
{
if (_triangleStart.IsMatch(line))
{
isInsideTriangle = true;
}
}
}
return triangles.ToArray();
}
}
}
I'm also using the fact that System.ValueTuple implements Equals and GetHashCode in an appropriate way, so we can easily compare vertices (this is used implicitly by HashSet) and use them as keys in a dictionary.

Sorting Coordinate string in c#

I currently have a list of coordinates that I need sorted. Each line represents Longitude, Latitude. I need to sort only on the Longitude.
It is stored in an string array:
string[] coords = fpdp.Coordinates.ToArray();
Here is the original list:
**LongLat**
98.63,85.02
43.08,79.07
26.97,70.88
18.8,62.3
13.47,53.5
8.57,44.8
3.58,36.35
-1.63,28.2
-6.93,20.33
-12.12,12.63
-17.17,5.02
-22.63,-2.25
-28.22,-9.43
-34.98,-15.7
-42.67,-21.08
-51.18,-25.62
-60.55,-29.12
-70.7,-31.12
-81.2,-31.18
-91.42,-29.72
-101.02,-26.97
-109.62,-22.85
-117.3,-17.83
-123.9,-11.9
-129.32,-5.05
-133.55,2.47
-136.9,10.3
-140.45,17.78
-144.75,24.98
-148.6,32.53
-152.02,40.37
-155.85,48.28
-160.8,56.27
-165.75,64.48
-172.62,72.78
171.35,80.83
98.93,85.17
Here is what I need it to look like. It is sorted by Large to small for positive numbers, and small to large for negative numbers. Only focusing on the first longitude coordinate:
**LongLat-Sorted**
171.35,80.83
98.93,85.17
98.63,85.02
43.08,79.07
26.97,70.88
18.8,62.3
13.47,53.5
8.57,44.8
3.58,36.35
-1.63,28.2
-6.93,20.33
-12.12,12.63
-17.17,5.02
-22.63,-2.25
-28.22,-9.43
-34.98,-15.7
-42.67,-21.08
-51.18,-25.62
-60.55,-29.12
-70.7,-31.12
-81.2,-31.18
-91.42,-29.72
-101.02,-26.97
-109.62,-22.85
-117.3,-17.83
-123.9,-11.9
-129.32,-5.05
-133.55,2.47
-136.9,10.3
-140.45,17.78
-144.75,24.98
-148.6,32.53
-152.02,40.37
-155.85,48.28
-160.8,56.27
-165.75,64.48
-172.62,72.78
How can I accomplish this in code? Any help would be great.
SOLUTION:
I tweaked this to the following, and it's working. Thanks a lot! :)
public class LongLatSort : IComparer
{
int IComparer.Compare(Object x, Object y)
{
string[] longLatParts1 = Convert.ToString(x).Split(',');
string[] longLatParts2 = Convert.ToString(y).Split(',');
var var1 = double.Parse(longLatParts1[0]);
var var2 = double.Parse(longLatParts2[0]);
if (var1 > var2)
{
return -1; // flipped for descending
}
else if (var1 < var2)
{
return 1; // flipped for descending
}
// secondary sort on latitude when values are equal
return var1 > var2 ? -1 : 1; // flipped for descending
}
}
Just finished tested this, seems to work.
class SimplePoint
{
public SimplePoint(string coord)
{
var coords = coord.Split(',').Select(s => double.Parse(s, System.Globalization.CultureInfo.InvariantCulture)).ToArray();
X = coords[0];
Y = coords[1];
}
public double X;
public double Y;
public override string ToString()
{
return X.ToString() + "," + Y.ToString();
}
}
static class LongLatParseAndSort
{
public static string SortedLongLat(string unsorted)
{
return unsorted
.Split(' ')
.Select(c => new SimplePoint(c))
.OrderByDescending(sp => sp.X)
.Select(sp => sp.ToString())
.Aggregate((a, b) => a += b);
}
}
How is this data stored? An array of Strings? or a 2-dimensional array or floats? or an Array of some structure with a lat and long? I'll assume its an array of LongLat since thats how you worded it.
EDIT I realized your subject title said string, so I added a constructor to convert from string to a LongLat.
Your desired result looks sorted descending on Longitude.
This code is untested, forgive me if it's not 100% but you get the idea.
// This is pretending to be the data structure you are using
public class LongLat {
private float mLongitude;
private float mLatitude;
// constructor from string for convenience
public LongLat(string longLatString ) {
string[] longLatParts = longLatString.Split(',');
mLongitude = float.Parse(longLatParts[0]);
mLatitude = float.Parse(longLatParts[1]);
}
public float Longitude {get; set; }
public float Latitude {get; set; }
}
// The sorter
public class LongLatSort : IComparer {
public int IComparer.Compare(object a, object b) {
LongLat o1=(LongLat)a;
LongLat o2=(LongLat)b;
if (o1.Longitude > o2.Longitude) {
return -1; // flipped for descending
} else if ( o1.Latitude < o2.Longitude ) {
return 1; // flipped for descending
}
// secondary sort on latitude when values are equal
return o1.Latitude > o2.Latitude ? -1 : 1; // flipped for descending
}
}
// now you should be able to use the sorter something like this?
// though best to not instantiate the Comparer every time but you get the idea
// EDIT: create your array of LongLats from strings first
Arrays.Sort( yourArrayofLongLats, new LongLastSort() );

Point Classification in a set of Bounding Boxes

I have a set of bounding boxes(rectangular) in a 3D space. The bounds of each box are computed and stored in a dictionary named "RegionBounds". Also, a set of points are populated in a List named "PointsToCategorize" Given a point(x,y,z) coordinates from the List populated and a bounding box to be checked in, i can check if the point is inside the box or not. The problem is, this is a big dataset. The number of points to be checked are like 1000 and the no of bounding boxes are like 250-300. So, if i loop through each bounding box for each given point; the total time it takes is like 5-6 minutes. Is there any efficient method that would do the process quicker ? If possible, a small code to do so would be great
public struct iBounds {
public double x1, x2;
public double y1, y2;
public double z1, z2;
}
public struct iPoint {
public double x,y,z
}
Dictionary<String, iBounds> RegionBounds = new Dictionary<String, iBounds>();
List<iPoint> PointsToCategorize = new List<iPoint>();
int no_of_bounding_boxes = 300;
int no_of_points_to_categorize = 1000;
for (int i = 1; i <= no_of_bounding_boxes; i++)
{
String boundingBoxName = "bound_" + i;
iBounds boundingBox = new iBounds
{
x1 = Computed By Some Other method and Formulas,
x2 = Computed By Some Other method and Formulas,
y1 = Computed By Some Other method and Formulas,
y2 = Computed By Some Other method and Formulas,
z1 = Computed By Some Other method and Formulas,
z2 = Computed By Some Other method and Formulas
};
RegionBounds.Add(boundingBoxName, boundingBox);
}
////////////Start of Output section /////////////////////////
for(int i= 1; i < = PointsToCategorize.Count; i++){
foreach(var pair in RegionBounds)
{
String myboxNmame = pair.Key;
iBounds myboxBounds = pair.Value;
Console.WriteLine(PointInside(PointsToCategorize[i],myboxBounds).ToString());
}
}
////////////// End of Output section //////////////////
private bool PointInside(iPoint mypoint, iBounds boxToBeCheckedIn)
{
if (mypoint.x > boxToBeCheckedIn.x1) && (mypoint.x < boxToBeCheckedIn.x2){
if (mypoint.y > boxToBeCheckedIn.y1) && (mypoint.y < boxToBeCheckedIn.y2){
if (mypoint.z > boxToBeCheckedIn.z1) && (mypoint.z < boxToBeCheckedIn.z2){
return true;
}
}
}else{
return false;
}
}
You may want to use a OcTree or a kD-tree data structure, which is way more efficient than iterating through all the boxes.
See also this article at the section 2-D orthogonal range searching, it has a very good resume of available techniques and algorithms, which are easily extendable to 3D

Algorithm: Checking for conditions in 3D array

This one is hard to explain! Sorry for that, but here goes...
I have a 3D array of some data [X][Y][Z], and I like to check for about 10 different combination conditions and keep only data when it's a match... Example:
X Y Z
//myData[1..1000000][1..10][1..10].foo // foo is an int
X[i].Y[ii].Z[iii].foo; // X is a container, Y= 1 to 10 levels. And Z= objects
//I want to apply a "filter" to the Z objects...
Lets say I want to find all combinations where the sum of "foo" is smaller and larger than two numbers, and only keep those Z objects
For next iteration i want to find lets say only where "foo" is a prime number, still keeping only Z objects
And so on for more conditions, resulting in smaller and smaller list.
It doesn't matter in wich order they are performed.
I sort of know how to do it, but I end up in some really nasty loops...
Any Ideas? Maybe adding to another list is faster than deleting from original list?
Thanks in advance!
When you want to chain together logic like this, I think you really want to use Linq. Unfortunately, it can be cumbersome to use Linq on multidimensional arrays. With some helper methods, though, we can convert the data array into something more usable. First, let's build a wrapper class for any object that has 3 dimensions associated with it:
public class ThreeDimensionalArrayExtension<T> {
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public T Value { get; set; }
}
Next, let's write a helper method that converts 3-dimsensional arrays to IEnumerables of the new type:
public static class ThreeDimensionalArrayExtensionMethods {
public static IEnumerable<ThreeDimensionalArrayExtension<T>> ConvertArray<T>(this T[,,] foos) {
for(var x = 0; x < foos.GetLength(0); x++) {
for (var y = 0; y < foos.GetLength(1); y++) {
for (var z = 0; z < foos.GetLength(2); z++) {
yield return new ThreeDimensionalArrayExtension<T> { X = x, Y = y , Z = z, Value = foos[x, y, z] };
}
}
}
}
}
Note that since we are using an iterator block (the yield-return pattern), calling this method does not actually perform any computation.
Now we can use the power of Linq on your 3-dimensional array to filter it however we want!
myData.ConvertArray().Where(d => d.Value.Foo > 5)
.Where(d => IsPrime(d.Value.Foo))
.Where(...);
Edit:
I see that you're using 3 nested classes and not a multidimensional array which I assumed you were using. The goal should still be to convert that object to an IEnumerable upon which you can very easily chain Linq queries to filter or project the data. In your case, you can do:
public static class ThreeDimensionalArrayExtensionMethods {
public static IEnumerable<ThreeDimensionalArrayExtension<X>> ConvertArray(this X[] foos) {
for(var x = 0; x < foos.Count(); x++) {
for (var y = 0; y < foos[x].Count(); y++) {
for (var z = 0; z < foos[x][y].Count(); z++) {
yield return new ThreeDimensionalArrayExtension<T> { X = x, Y = y , Z = z, Value = foos[x][y][z] };
}
}
}
}
}
And then use the same call to ConvertArray followed by the filtering Where clauses described above.
If you don't care about the X/Y/Z indices, you can also just use SelectMany to project the multidimensional list onto a single dimensional list:
X.SelectMany(y => y.SelectMany(z => z)).Where(z => z.Foo > 5);

Problems with double array?

I am required to create a program which reads in data from a .cvs file, and use these (x, y and z) values for a series of calculations.
I read in the file as a string, and then split this into 3 smaller strings for x, y and z.
The x, y and z coordinates represents the x and y coordinates of the contours of a lake, and the depth (z).
One of the calculations which I have to do, is to calculate the surface area of the lake, using the formula (x[i]*y[i+1])-(x[i+1]*y[i]), where z(depth) = 0.
I can get my code to run perfectly, up until the x[i+1] and y[i+1], where it keeps giving me a value of 0.
Can someone please tell me how to fix this?
Here is my code;
{
string[] ss = File.ReadAllLines(#"C:File.csv");
for (int i = 1; i < ss.Length; i++)
{
string[] valuesAsString = ss[i].Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
double[] X = new double[valuesAsString.Length];
double[] Y = new double[valuesAsString.Length];
double[] Z = new double[valuesAsString.Length];
for (int n = 0; n < 1; n++)
{
X[n] = double.Parse(valuesAsString[0]);
Y[n] = double.Parse(valuesAsString[1]);
}
do
{
double SurfaceArea = (X[n] * Y[n + 1]) - (X[n + 1] * Y[n]);
Console.WriteLine(SurfaceArea);
}
while (Z[n] == 0);
}
}
Ok, im not sure if i got it right, so you if you would take a look to what i did and tell me if its of any help.
After reviewng it a little i came up with the following:
A class for the values
public class ValueXyz
{
public double X { get; set; }
public double Y { get; set; }
public int Z { get; set; }
}
A class to manange the calculation:
public class SurfaceCalculator
{
private ValueXyz[] _valuesXyz;
private double _surface;
private readonly string _textWithValues;
public SurfaceCalculator(string textWithValues)
{
_textWithValues = textWithValues;
SetValuesToCalculate();
}
public double Surface
{
get { return _surface; }
}
public void CalculateSurface()
{
for (var i = 0; i < _valuesXyz.Length; i++)
{
if (_valuesXyz[i].Z == 0)
_surface = (_valuesXyz[i].X*_valuesXyz[i + 1].Y) - (_valuesXyz[i + 1].X*_valuesXyz[i].Y);
}
}
private void SetValuesToCalculate()
{
var valuesXyz = _textWithValues.Split(' ');
_valuesXyz = valuesXyz.Select(item => new ValueXyz
{
X = Convert.ToDouble(item.Split(',')[0]),
Y = Convert.ToDouble(item.Split(',')[1]),
Z = Convert.ToInt32(item.Split(',')[2])
}).ToArray();
}
}
So now your client code could do somethin like:
[TestMethod]
public void TestSurfaceCalculatorGetsAValue()
{
//var textWithValues = File.ReadAllText(#"C:File.csv");
var textWithValues = "424.26,424.26,0 589.43,231.46,0 720.81,14.22,1";
var calculator = new SurfaceCalculator(textWithValues);
calculator.CalculateSurface();
Assert.IsNotNull(calculator.Surface);
}
I'm not very sure i got the idea correct of how to implement the formula, but i just wanted to expose an alternative you can use, you can never have to many ways of doing one thing :).
Cheers.
By the way part of the intent i had, was not tying up your funcionality to the csv in case your source for the text in the future would change.
Step through your code in the debugger. Pay special attention to tbe behavior of the line
for (int n = 0; n < 1; n++)
This loop will execute how many times? What will the value of n be during each iteration through the loop?
Well, one thing i noticed is when you're setting your X, Y, Z vars, you're setting it to the Length of the array object instead of it's value - is that intentional?
Put a debug break on the line with:
double SurfaceArea = (X[n] * Y[n + 1]) - (X[n + 1] * Y[n]);
and check the datatype of "X", "Y" and "Z"
I've had problems in the past where it tries to calculate them as strings (because it took it out of the data source as strings). I ended up fixing it by adding CInt() to each of the variables (or Convert.ToInt32();).
Hope this helps.
As this looks like it might be a homework problem, I am trying not to give a direct solution in my answer, but I see a number of questionable parts of your code that you should examine.
Why are X, Y, Z arrays? You are creating a new array each time through the outer loop, setting the length of the array to the number of elements in the line, then only assigning a value to one element of X and Y, and never assigning Z to anything.
As phoog suggests in his answer, what is the purpose of: for (int n = 0; n < 1; n++)?
What are you trying to accomplish with the do-while loop? As it has been mentioned in the comments by Mr Skeet, X[n], Y[n], Z[n] don't exist because n does not exist outside of the loop it is declared for. Even if it did exist Z[n] will always be zero because you never assign anything to the Z array after it is initialized, so the do-while loop will run forever.

Categories

Resources