Skip to content

Instantly share code, notes, and snippets.

@msarchet
Created January 25, 2011 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msarchet/795561 to your computer and use it in GitHub Desktop.
Save msarchet/795561 to your computer and use it in GitHub Desktop.
Calculates the center of gravity from an input file
//This was written as an exercise for a friend for a CFD class
using System;
using System.Collections.Generic;
using System.IO;
namespace CenterOfGravity
{
class Program
{
static void Main(string[] args)
{
//dataFile is a FileInfo that represent the File at the given Location
FileInfo dataFile = new FileInfo(@"C:\inputFile.txt");
//This makes a collection of Particle objects
List<Particle> particles = new List<Particle>();
//This part opens the dataFile into fileStream which lets the file be read
using (StreamReader fileStream = dataFile.OpenText())
{
//make a string called line to store each line in as it's read
string line = "";
//This makes an array of items to split the file lines along
string[] splits = new string[1];
splits[0] = " ";
//While there are still lines to be read set line equal to that line
while ((line = fileStream.ReadLine()) != null)
{
//split up the current line into a Array of strings
string[] part = line.Split(splits, StringSplitOptions.RemoveEmptyEntries);
//add a new particle to the Collection of particles
//Set that particles properties equal to the values found in the string array
particles.Add(new Particle
{
Mass = Double.Parse(part[0]),
XPosition = Double.Parse(part[1]),
YPosition = Double.Parse(part[2]),
ZPosition = Double.Parse(part[3])
});
}
}
//This part does the math
double xcenter = 0.0;
double ycenter = 0.0;
double zcenter = 0.0;
double totalMass = 0.0;
//Loop through all of the particles in the collection of particles and find the total mass
foreach (Particle particle in particles)
{
totalMass += particle.Mass;
}
//Perform the summation of the weighted positions
foreach (Particle particle in particles)
{
xcenter += (particle.Mass * particle.XPosition) / totalMass;
ycenter += (particle.Mass * particle.YPosition) / totalMass;
zcenter += (particle.Mass * particle.ZPosition) / totalMass;
}
//Write Out the output file
using (StreamWriter outputFile = new StreamWriter(@"C:\output.dat", false))
{
outputFile.WriteLine("Total Mass = " + totalMass);
outputFile.WriteLine("Center of Gravity");
outputFile.WriteLine("x = " + xcenter);
outputFile.WriteLine("y = " + ycenter);
outputFile.WriteLine("z = " + zcenter);
}
}
}
//A Class representing the particle object.
class Particle
{
public double XPosition { get; set; }
public double YPosition { get; set; }
public double ZPosition { get; set; }
public double Mass { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment