Linked List: Insert item btween current and current.next - c#

Currently I am learning how to build my own linked list in C#. I have created a function called AddTrees that adds a tree to the end of the list. User create their trees through textboxes input:tree_name, tree_height, tree_price and tree_instock. I am requesting help with my InsertTree which is not inserting a tree between current and current.next_tree? But instead of instead of inserting it between, it adds it to the top of the list.
namespace Tree_farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class TheTrees
{
private string tree_type = " ";
private int tree_height = 0;
public double tree_price = 0;
private int tree_instock = 0;
public TheTrees next_tree;
public TheTrees(string newtree, int newheight, int newinstock, double newprice)
{
tree_type = newtree;
tree_height = newheight;
tree_price = newprice;
tree_instock = newinstock;
next_tree = null;
}
public override string ToString()
{
return tree_type + " " + tree_height + " " + tree_price + " " + tree_instock;
}
}
public class ListForTrees
{
public TheTrees first_tree;
public TheTrees last_tree;
public int count = 0;
public ListForTrees(TheTrees new_tree)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
public ListForTrees()
{
}
public void InsertTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void AddTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void ClearTrees()
{
first_tree = null;
count = 0;
}
}
ListForTrees mainlist = new ListForTrees();
private void Form1_Load(object sender, EventArgs e)
{
}
private void BtnInsertTree_Click(object sender, EventArgs e)
{
//Insert Code
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeinsert = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.InsertTree(treeinsert);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
private void BtnAddTree_Click(object sender, EventArgs e)
{
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeadd = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.AddTree(treeadd);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
}
}

First, I think your expected result is wrong. It appears you want the linked list sorted in order of price (lowest to highest). If so, Cypress should actually go at the end of your list, not in the middle (80.00 > 50.00 > 2.00).
Secondly, I believe the issue rests in your while loop.
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
I believe what you're trying to do is walk down your linked list. What you're actually doing is mucking up your linked list by changing current.next_tree to point to itself. Changing it to the following is a positive first step towards correcting your algorithm:
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
EDIT: It should be noted that I do not get the same error that you get in your original post. When I insert items in the same order that you claim to, I get the list in correct sorted order. This is due to the fact that Cypress goes to the end, as expected. How did you get the result that you claim in the question?

Related

Why is my C# Array changing without anything being assigned to it?

I have a small winforms program for a task which is to create a Recipe book. The application has two windows, but my bug pertains to only one.
I have two main classes: Recipe.cs and RecipeManager.cs, the idea is that the RecipeManager holds an array of Recipes. (For this task we weren't allowed to use Linq or ArrayLists)
Now, when I fill in the form and click "Add Recipe", the first one works successfully and the listBox populates correctly, however the second time I "Add Recipe" the recipeList array seems to get rewritten with the new Recipe entirely, and I have no idea why this is happening. The recipeList seems to change before my Add method even adds it to the array!
See gif of problem in question:
https://i.imgur.com/sIMICcG.gifv
Recipe.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace programmingTask4
{
public class Recipe
{
private string[] ingredientArray;
private string name;
private FoodCategory category;
private string description;
private const int maxNumOfIngredients = 20;
public string Name
{
get { return name; }
set { name = value; }
}
public FoodCategory Category
{
get { return category; }
set { category = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public string[] Ingredient
{
get { return ingredientArray; }
set { ingredientArray = value; }
}
public int MaxNumOfIngredients
{
get { return ingredientArray.Length; }
}
public Recipe(int maxNumOfIngredients)
{
Console.WriteLine("Recipe constructor was called!");
ingredientArray = new string[maxNumOfIngredients];
DefaultValues();
}
public void DefaultValues()
{
for (int i = 0; i < ingredientArray.Length; i++)
{
ingredientArray[i] = string.Empty;
name = string.Empty;
category = FoodCategory.Vegetarian;
description = string.Empty;
}
}
public int FindVacantPosition()
{
int results;
for (int i = 0; i < ingredientArray.Length; i++)
{
if(ingredientArray[i] == string.Empty)
{
results = i;
return results;
}
}
return -1;
}
public bool AddIngredient(string value)
{
bool ok;
int next = FindVacantPosition();
if(next >= 0)
{
ok = true;
ingredientArray[next] = value;
}
else {
ok = false ;
}
return ok;
}
public bool CheckIndex(int index)
{
bool check = false;
if(index <= ingredientArray.Length && index >= 0)
{
check = true;
}
return check;
}
public int GetCurrentNumOfIngredients()
{
int count = 0;
for (int i = 0; i < ingredientArray.Length; i++)
{
if (!string.IsNullOrEmpty(ingredientArray[i]))
{
count++;
}
}
return count;
}
public override string ToString()
{
int chars = Math.Min(description.Length, 15);
string descriptionText = description.Substring(0, chars);
if (string.IsNullOrEmpty(descriptionText))
descriptionText = "NO DESCRIPTION";
string textOut = string.Format("{0, -20} {1,4} {2,-12} {3,-15}", name, GetCurrentNumOfIngredients(), category.ToString(), descriptionText);
return textOut;
}
public bool ChangeIngredientAt(int index, string value)
{
bool bok = true;
if (CheckIndex(index))
ingredientArray[index] = value;
else
bok = false;
return bok;
}
public bool DeleteIngredientAt(int index)
{
bool bok = true;
if (CheckIndex(index))
ingredientArray[index] = "NO DESCRIPTION";
else
bok = false;
return bok;
}
}
}
RecipeManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace programmingTask1
{
class RecipeManager
{
private Recipe[] recipeList;
public RecipeManager(int maxNumOfElements)
{
Console.WriteLine("Recipe manager constructor called!");
recipeList = new Recipe[maxNumOfElements];
}
private int FindVacantPosition()
{
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] == null)
{
Console.WriteLine("Found free position at: " + i);
return i;
}
}
return -1;
}
public bool CheckIndex(int index)
{
bool check = false;
if (index <= recipeList.Length && index >= 0)
{
check = true;
}
return check;
}
public Recipe GetRecipeAt(int index)
{
if (CheckIndex(index))
return recipeList[index];
else
return null;
}
public bool Add(Recipe newRecipe)
{
if (newRecipe == null)
return false;
bool ok;
int next = FindVacantPosition();
if (next >= 0)
{
ok = true;
Console.WriteLine("Setting recipe list at index " + next + " to " + newRecipe.ToString());
recipeList[next] = newRecipe;
}
else
{
Console.WriteLine("No space for recipe available! " + next);
ok = false;
}
return ok;
}
public int CurrentNumberofItems()
{
int num = 0;
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] != null)
{
num++;
}
}
return num;
}
public string[] RecipeListToString()
{
string[] results = new string[recipeList.Length];
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] != null)
results[i] = recipeList[i].ToString();
else
results[i] = string.Empty;
}
return results;
}
}
}
FormMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace programmingTask4
{
public partial class FormMain : Form
{
const int maxRecipe = 3;
const int maxIngredients = 20;
Recipe currRecipe = new Recipe(maxIngredients);
RecipeManager recipemanager = new RecipeManager(maxRecipe);
public FormMain()
{
Console.WriteLine("Form constructor was called!");
InitializeComponent();
InitializeGui();
}
public void InitializeGui()
{
comboBoxCategory.DataSource = Enum.GetValues(typeof(FoodCategory));
}
public void UpdateGUI()
{
//listBoxDisplay.Text = recipemanager.CurrentNumberofItems().ToString();
//listBoxDisplay.Text = currRecipe.Ingredient.ToString();
string[] recipeListStrings = recipemanager.RecipeListToString();
listBoxDisplay.Items.Clear();
listBoxDisplay.Items.AddRange(recipeListStrings);
}
private void buttonRecipe_Click(object sender, EventArgs e)//add recipe button
{
currRecipe.Category = (FoodCategory)comboBoxCategory.SelectedIndex;
currRecipe.Name = textBoxRecipeName.Text.Trim();
currRecipe.Description = richTextBoxDescription.Text.Trim();
Console.WriteLine("Adding recipe: " + currRecipe.ToString());
bool result = recipemanager.Add(currRecipe);
Console.WriteLine("Result was " + result + " for adding to recipe list");
UpdateGUI();
currRecipe.DefaultValues();
}
}
}
Recipe is a class, which mean it's a reference type.
In your main form, your currRecipe instance is never changed.
RecipeManager has an array to store references of instance but unfortunately it stores the same instance because of 2.
Since RecipeManager stores the same instance of currRecipe, any modification on currRecipe would display N times.
To prevent it. Modify your buttonRecipe_Click
private void buttonRecipe_Click(object sender, EventArgs e)//add recipe button
{
currRecipt = new Recipe(maxIngredients);
currRecipe.Category = (FoodCategory)comboBoxCategory.SelectedIndex;
currRecipe.Name = textBoxRecipeName.Text.Trim();
currRecipe.Description = richTextBoxDescription.Text.Trim();
Console.WriteLine("Adding recipe: " + currRecipe.ToString());
bool result = recipemanager.Add(currRecipe);
Console.WriteLine("Result was " + result + " for adding to recipe list");
UpdateGUI();
// No need to reset it, use new one everytime.
//currRecipe.DefaultValues();
}

Paggeable Datagrid ItemSource throws null exception

I want to create a generic Datagrid that can paginate. When I call the constructor of my DataGrid_UC and pass 20 Employees it does stores all 20 Employees in AllObject Observable Collection. And filter out the CurrentPageItems to be 5. But upon setting datagrid.ItemsSource = CurrentPageItems it throws null exception but CurrentPageItems does contain 5 items.
DataGrid_UC.xaml
public partial class DataGrid_UC : UserControl
{
private ObservableCollection<object> _currentPageItems;
public ObservableCollection<object> CurrentPageItems
{
get
{
return _currentPageItems;
}
private set
{
if (_currentPageItems != value)
{
_currentPageItems = value;
}
}
}
// Default Entries per page Number
private int _pageSize = 5;
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (_pageSize != value)
{
_pageSize = value;
Reset();
}
}
}
public int TotalPagesNumber
{
get
{
if (AllObjects != null && PageSize > 0)
{
return (AllObjects.Count - 1) / PageSize + 1;
}
return 0;
}
}
private int _currentPageNumber = 1;
public int CurrentPageNumber
{
get
{
return _currentPageNumber;
}
protected set
{
if (_currentPageNumber != value)
{
_currentPageNumber = value;
}
}
}
protected ObservableCollection<object> AllObjects { get; set; }
public DataGrid_UC()
{
InitializeComponent();
dataGrid.ItemsSource = CurrentPageItems;
}
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
AllObjects = new ObservableCollection<object>(allObjects);
if (entriesPerPage != null)
PageSize = (int)entriesPerPage;
SetCurrentPageItems();
}
#region Public Methods
public void GoToNextPage()
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
public void GoToPreviousPage()
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
#endregion
#region Private Methods
public void SetCurrentPageItems()
{
int upperLimit = CurrentPageNumber * PageSize;
CurrentPageItems =
new ObservableCollection<object>(
AllObjects.Where(x => AllObjects.IndexOf(x) > upperLimit - (PageSize + 1) && AllObjects.IndexOf(x) < upperLimit));
dataGrid.ItemsSource = CurrentPageItems;
}
private void Reset()
{
CurrentPageNumber = 1;
SetCurrentPageItems();
}
#endregion
private void next_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
private void previous_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
}
Main Window.xaml
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Employee> emp = new List<Employee>();
for (int i = 0; i < 20; i++)
{
Employee e = new Employee();
e.ID = i;
e.Name = "Test " + i;
emp.Add(e);
}
DataGrid_UC d = new DataGrid_UC(emp, 5);
newContentControl.Content = d;
}
}
The dataGrid member is null because your second constructor is missing the InitializeComponent call, which (among other things) initializes the class members defined in XAML by x:Name.
So change the constructor like this:
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
InitializeComponent();
AllObjects = new ObservableCollection<object>(allObjects);
...
}

In Datagridview Paging not getting exact number of rows shown

I am using this code for paging ,using this i am getting all records in datagridview ,i have set _PateSize = 10;why i am not getting only 10 rows in datagridview,and on click of next button next 10 rows,how do i make this code working ,where i am going wrong
public partial class ShowEngClgList : Form
{
private int _CurrentPage = 1;
private int _PateSize = 10;
public int PageSize
{
get
{
return _PateSize;
}
set
{
_PateSize = value;
}
}
private DataTable _DataSource;
public DataTable DataSource
{
get
{
return _DataSource;
}
set
{
_DataSource = value;
}
}
private int _Width;
public int ControlWidth
{
get
{
if (_Width == 0)
return dataGridView1.Width;
else
return _Width;
}
set
{
_Width = value;
dataGridView1.Width = _Width;
}
}
private int _Height;
public int ControlHeight
{
get
{
if (_Height == 0)
return dataGridView1.Height;
else
return _Height;
}
set
{
_Height = value;
dataGridView1.Height = _Height;
}
}
private string _FirstButtonText = string.Empty;
public string FirstButtonText
{
get
{
if (_FirstButtonText == string.Empty)
return btnFirst.Text;
else
return _FirstButtonText;
}
set
{
_FirstButtonText = value;
btnFirst.Text = _FirstButtonText;
}
}
private string _LastButtonText = string.Empty;
public string LastButtonText
{
get
{
if (_LastButtonText == string.Empty)
return btnLast.Text;
else
return _LastButtonText;
}
set
{
_LastButtonText = value;
btnLast.Text = _LastButtonText;
}
}
private string _PreviousButtonText = string.Empty;
public string PreviousButtonText
{
get
{
if (_PreviousButtonText == string.Empty)
return btnPrevious.Text;
else
return _PreviousButtonText;
}
set
{
_PreviousButtonText = value;
btnPrevious.Text = _PreviousButtonText;
}
}
private string _NextButtonText = string.Empty;
public string NextButtonText
{
get
{
if (_NextButtonText == string.Empty)
return btnNext.Text;
else
return _NextButtonText;
}
set
{
_NextButtonText = value;
btnNext.Text = _NextButtonText;
}
}
public void DataBind(DataTable dataTable)
{
DataSource = dataTable;
dataGridView1.DataSource = ShowData(1);
}
private DataTable ShowData(int pageNumber)
{
DataTable dt = new DataTable();
int startIndex = PageSize * (pageNumber - 1);
var result = DataSource.AsEnumerable().Where((s, k) => (k >= startIndex && k < (startIndex + PageSize)));
foreach (DataColumn colunm in DataSource.Columns)
{
dt.Columns.Add(colunm.ColumnName);
}
foreach (var item in result)
{
dt.ImportRow(item);
}
txtPaging.Text = string.Format("Page {0} Of {1} Pages", pageNumber, (DataSource.Rows.Count / PageSize) + 1);
return dt;
}
public OleDbConnection acccon = null;
public OleDbDataAdapter da = null;
public DataTable dt = null;
public ShowEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
}
string sql = "Select EngClgName,EngClgAddress,EngClgEntranceType From EngColeges";
da = new OleDbDataAdapter(sql, acccon);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void btnFirst_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First Page.");
}
else
{
_CurrentPage = 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First page, you can not go to previous of First page.");
}
else
{
_CurrentPage -= 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int lastPage = (DataSource.Rows.Count / PageSize) + 1;
if (_CurrentPage == lastPage)
{
MessageBox.Show("You are already on Last page, you can not go to next page of Last page.");
}
else
{
_CurrentPage += 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnLast_Click(object sender, EventArgs e)
{
int previousPage = _CurrentPage;
_CurrentPage = (DataSource.Rows.Count / PageSize) + 1;
if (previousPage == _CurrentPage)
{
MessageBox.Show("You are already on Last Page.");
}
else
{
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
}
thanks in advance for any help

C# Class Method to loop through a List created in the same Class

To start off I am new to C# and I am in need of some help. I a class that contains a list. I can set the items in the list from the application but not from the class(where it needs to be done). I am also needing to move an event to class as well. This works in the app as well. Any help with this is greatly appreciated. Below is the code from my class:
namespace CarRace
{
class Cars
{
public string Name { get; set; }
public int StartPOS { get; set; }
public int Speed { get; set; }
public int CurPOS { get; set; }
public double Location { get; set; }
public Cars(string Name, int StartPOS, int Speed, int CurPOS, long Location)
{
this.Name = Name;
this.StartPOS = StartPOS;
this.Speed = Speed;
this.CurPOS = 0;
this.Location = 0;
}
public static int CompareCurrentLocation(Cars c1, Cars c2)
{
return c2.Location.CompareTo(c1.Location);
}
}
}
I am needing to add this to the class:
if (File.Exists("NewRace.xml"))
{
XDocument doc = XDocument.Load("NewRace.xml");
var nCars = doc.Descendants("Car").Select(x => new Cars("", 0, 0, 0, 0)
{
Name = x.Attribute("Name").Value,
StartPOS = int.Parse(x.Attribute("StartPOS").Value),
Speed = int.Parse(x.Attribute("Speed").Value),
CurPOS = 0
});
}
And this:
int p = 1;
int prevPOS = 1;
DateTime? PrevTime;
double dist = 0;
double PrevLoc = 0;
if (i == 0)
{
return;
}
foreach (var car in RaceList)
{
dist = (((car.Speed * 1609.344) * 1) / 1609.344) / 3600;
car.Location = car.Location + dist;
}
Comparison<Cars> compLoc = Cars.CompareCurrentLocation;
RaceList.Sort(compLoc);
PrevTime = DateTime.Now;
foreach (var car in RaceList)
{
if (car.Location != PrevLoc)
{
car.CurPOS = p;
}
else
{
car.CurPOS = prevPOS;
}
prevPOS = car.CurPOS;
PrevLoc = car.Location;
p++;
}
Thanks
Thanks for all of your replies. I tried the car.speed/3600 but only get
back 0 for that so I did the long way. I did get everything working
the way I needed it to.
That's because you are doing an integer division (car.Speed is of type int) so the fractional part of the result is discarded. Since the car's speed is less than 3600 this would hence always result in zero. You can avoid this by casting car.Speed to a double first - this should produce the result you want:
dist = (double)car.Speed / 3600;
Thanks for all of your replies. I tried the car.speed/3600 but only get back 0 for that so I did the long way. I did get everything working the way I needed it to. I am a rookie at this and any tips are greatly appreciated. Below is the code I have updated to.
namespace CarRace
{
class Cars
{
public string Name { get; set; }
public int StartPOS { get; set; }
public int CurPOS { get; set; }
public int Speed { get; set; }
public double Location { get; set; }
public string Make { get; set; }
private static List<Cars> CarList;
private static string ProgPart;
public Cars(string Name, int StartPOS, int CurPOS, int Speed, double Location, string Make)
{
this.Name = Name;
this.StartPOS = StartPOS;
this.CurPOS = CurPOS;
this.Speed = Speed;
this.Location = Location;
this.Make = Make;
}
public static List<Cars> FillList()
{
return CarList;
}
public static void Main()
{
try
{
bool Prog = false;
//Get Part to display
while (!Prog)
{
Console.WriteLine("Select the part you would like to test.(1 or 2)");
ProgPart = Console.ReadLine();
if (ProgPart == "1" || ProgPart == "2")
{
Prog = true;
}
}
Console.WriteLine("----------------------------------------");
//Read XML File and set the CarList
if (File.Exists("NewRace.xml"))
{
XDocument doc = XDocument.Load("NewRace.xml");
var nCars = doc.Descendants("Car").Select(x => new Cars("", 0, 0, 0, 0, "")
{
Name = x.Attribute("Name").Value,
StartPOS = int.Parse(x.Element("StartPOS").Value),
CurPOS = 0,
Speed = int.Parse(x.Element("Speed").Value),
Location = double.Parse(x.Element("Location").Value),
Make = x.Attribute("Make").Value
});
CarList = new List<Cars>();
foreach (var car1 in nCars)
{
if (ProgPart == "1")
{
CarList.Add(new Cars(car1.Name, car1.StartPOS, car1.CurPOS, car1.Speed, car1.Location, car1.Make));
}
else
{
CarList.Add(new Cars(car1.Name, car1.StartPOS, car1.CurPOS, 0, car1.Location, car1.Make));
}
}
}
else
{
Console.WriteLine("File Not Found!");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static int CompareCurrentLocation(Cars c1, Cars c2)
{
return c2.Location.CompareTo(c1.Location);
}
public static Boolean UpdateLeaderBoard(long i)
{
try
{
int p = 1;
int prevPOS = 1;
DateTime? PrevTime;
double dist = 0;
double prevLocation = 0;
if (i == 0)
{
return false;
}
foreach (var car in CarList)
{
if (ProgPart == "2")
{
switch (car.Make)
{
case "300ZX":
//Slow continuous gain of speed by percentage after 60 with top speed of 320.
if (i <= 15)
{
car.Speed = car.Speed + (60 / 10);
}
else if (car.Speed < 320)
{
double percent = (double)(car.Speed * .1);
if ((Convert.ToInt32(car.Speed + percent)) > 320)
{
car.Speed = 320;
}
else
{
car.Speed = Convert.ToInt32(car.Speed + (percent));
}
}
break;
case "Camero":
//0-60 4 seconds 60-220 20 seconds Top 220
if (i <= 4)
{
car.Speed = car.Speed + (60 / 4);
}
else if (i <= 20)
{
car.Speed = car.Speed + 10;
}
break;
case "Mustang":
//0-top(210) 25 seconds
if (car.Speed <= 200)
{
car.Speed = car.Speed + (200 / 20);
}
break;
case "VW Bug":
//Constant Speed
car.Speed = 165;
break;
default:
Console.WriteLine("Make not found");
break;
}
}
//Set Cars Current Location
dist = (((car.Speed * 1609.344) * 1) / 1609.344) / 3600;
car.Location = car.Location + dist;
}
//Sort list by location
Comparison<Cars> compLoc = Cars.CompareCurrentLocation;
CarList.Sort(compLoc);
PrevTime = DateTime.Now;
//Set the Current Position
foreach (var car in CarList)
{
if (car.Location != prevLocation)
{
car.CurPOS = p;
}
else
{
car.CurPOS = prevPOS;
}
prevPOS = car.CurPOS;
prevLocation = car.Location;
p++;
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}

What wrong with my loop .Need to calculate a running total

I have to build some logic to write some sort of scoreboard. The idea is this:
There are many stages:
1st stage you have 2 numbers. 7 and 3=10
2nd stage you have another 2 numbers. 5 and 1 =6
After the loop has finished, the wanted result should be:
Stage 1 total score=15 (total 1st Stage + firstTry of secondStage)
Stage 2 total score=21 (total 1st Stage + (firstTry + SecondTry of SecondStage)
What's wrong with my loop? I dont seem to get the wanted resoult.
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
//If firstTry + SecondTry==10 is spare
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore +
player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = stageScore;
}
}
}
public class Stage
{
public int FirstTry { get; set; }
public int SecondTry { get; set; }
public int TotalScore { get; set; }
}
public class Player
{
public Player(string name)
{
Name = name;
Game = new Game(name);
}
public Game Game { get; set; }
public string Name { get; set; }
}
public class Game
{
public Game(string playerName)
{
PlayerName = playerName;
Stages = new Stage[10];
for (int i = 0; i < Stages.Length; i++)
{
Stages[i] = new Stage();
}
}
public Stage[] Stages { get; internal set; }
public string PlayerName { get; set; }
}
Change this:
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore + player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = sumFirstAndSecond + stageScore;
}
else if (i > 0) player.Game.Stages[i].TotalScore = player.Game.Stages[i - 1].TotalScore + sumFirstAndSecond;
}
}
Bowling?
Try this, and do not forget to add misses (as 0).
Should work for both running and final scoring.
// All balls, including misses (0)!
public readonly IList<int> _balls = new List<int>();
private int _currentBall;
public int CalculateTotalScore()
{
int score = 0;
_currentBall = 0;
for (var frame = 0; frame < 10; frame++)
{
if (_currentBall >= _balls.Count)
break;
if (_balls[_currentBall] == 10)
{
// Strrrike!
score += AggregateScoreFromCurrentBall(3);
_currentBall++;
}
else if (AggregateScoreFromCurrentBall(2) == 10)
{
// Spare
score += AggregateScoreFromCurrentBall(3);
_currentBall += 2;
}
else
{
score += AggregateScoreFromCurrentBall(2);
_currentBall += 2;
}
}
return score;
}
private int AggregateScoreFromCurrentBall(int numberOfBallsToSum)
{
var sum = 0;
for (var i = 0; i < numberOfBallsToSum; i++)
if (_currentBall + i < _balls.Count)
sum += _balls[_currentBall + i];
return sum;
}

Categories

Resources