Recently I had a practical test for Software developer position , in that test they asked following question.
Write me a function that receives three integer inputs for the lengths
of the sides of a triangle and returns one of four values to determine
the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error)
Also they asked to use enums and OOP approach for this solution,
but without OOP approach I built that on following way
using System;
using System.Linq;
namespace triangleSolution
{
class Program
{
static void Main(string[] args)
{
int[] values = new int[3];
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Please enter side " + i +" value");
values[i - 1] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(GetTriangleType(values[0], values[1], values[2]));
Console.WriteLine();
}
public enum TriangleType
{
Scalene = 1, // no two sides are the same length
Isosceles = 2, // two sides are the same length and one differs
Equilateral = 3, // all sides are the same length
Error = 4 // inputs can't produce a triangle
}
public static TriangleType GetTriangleType(int a, int b, int c)
{
// There should also be a side length check
if (a <= 0 || b <= 0 || c <= 0)
{
return TriangleType.Error;
}
if (a == b && a == c) // These could also be their own methods
{
return TriangleType.Equilateral;
}
else if (a == b || a == c || b == c)
{
return TriangleType.Isosceles;
}
else
{
return TriangleType.Scalene;
}
}
}
}
I wish to extend above solution in OOP way though I failed that interview :)
There are many ways to do this (based on the vague description)
e.g.: use a,b,c in a class Triangle that has a property TriangleType
But I have to say, the wording
Write me a function that ...
Is very misleading if OOP was what they were after.
public enum TriangleType
{
Scalene = 1, // no two sides are the same length
Isosceles = 2, // two sides are the same length and one differs
Equilateral = 3, // all sides are the same length
Error = 4 // inputs can't produce a triangle
}
public class Triangle
{
public TriangleType TriangleType {get; private set;}
public int SideA {get; private set;}
public int SideB {get; private set;}
public int SideC {get; private set;}
public Triangle(int a, int b, int c)
{
SideA = a;
SideB = b;
SideC = c;
TriangleType = GetTryangleType(a,b,c);
}
public static TriangleType GetTriangleType(int a, int b, int c)
{
// There should also be a side length check
if (a <= 0 || b <= 0 || c <= 0)
{
return TriangleType.Error;
}
if (a == b && a == c) // These could also be their own methods
{
return TriangleType.Equilateral;
}
else if (a == b || a == c || b == c)
{
return TriangleType.Isosceles;
}
else
{
return TriangleType.Scalene;
}
}
}
Usage:
static void Main(string[] args)
{
int[] values = new int[3];
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Please enter side " + i +" value");
values[i - 1] = Int32.Parse(Console.ReadLine());
}
Triangle triangle = new Triangle(values[0], values[1], values[2]);
Console.WriteLine(triangle.TriangleType);
Console.WriteLine();
}
You could use a triangle class, something like this
public class Triangle
{
private int[] sideLength;
public Triangle(int side1, int side2, int side3)
{
sideLength = new int[3];
sideLength[0] = side1;
sideLength[1] = side2;
sideLength[2] = side3;
}
public TriangleType GetTriangleType()
{
//Your code here ;)
}
}
Related
I'm working on a small calculator program in Unity.
I only need the calculator to work with two numbers.
The feature I'm trying to implement:
After inputting the math operator, It should display the second number in the third index.
The issue:
Instead of Adding a second number, the first number is being overwritten if a different number is pressed on the keyboard.
Here's the script I've created:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Functions : MonoBehaviour
{
// Global Variable to display text on top panel
public Text panelText;
// Create a number variable
string num;
string num1;
string num2;
string mOpr;
string calNum;
string cbutton;
string opr;
bool isFirstNum;
// Start is called before the first frame update
void Start()
{
}
// A function with an int argument
public void NumberInputOne(string num)
{
num1 = num;
num2 = num;
if (panelText.text.Length < 1)
{
Debug.Log(num1);
panelText.text = num1;
isFirstNum = false;
}
else if (panelText.text.Length > 1 && panelText.text.Length < 3)
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
public void OperatorInput(string opr)
{
mOpr = opr;
if (panelText.text.Length > 0 && panelText.text.Length < 2)
{
panelText.text = num1 + mOpr;
}
}
// public void NumberInputTwo(int num)
//{
// ResNum2 = num;
// Debug.Log(ResNum2);
// if (panelText.text.Length > 1 && panelText.text.Length < 3)
// {
// panelText.text = ResNum1 + opr + ResNum2;
// }
// }
public void RestartCal(string cButton)
{
panelText.text = "";
}
}
I've also added a screen recording to capture the issue:
First number being overwritten
Do you have any suggestions?
Thank you
use the NumberInputOne func like below;
public void NumberInputOne(string num)
{
if (num1 is null)
{
Debug.Log(num1);
panelText.text = num1;
num1 = num
}
else
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
btw i recommend that you review the sample calculation application codes. because apart from what you're asking, there are places you need to improve in general.
This feels like a beginner programming exercise. But the right way to build a calculator involves programming concepts that you probably haven't been taught yet. Which makes this a poor choice as an assignment.
Personally I would build a calculator by defining a simple syntax tree to represent the formula being input. Including methods to display the formula and calculate the answer. For example;
public interface IValue
{
int Calculate();
string PrintValue();
}
public class Number : IValue
{
public int? Value;
public void AddDigit(int digit) => Value = (Value ?? 0) * 10 + digit;
public int Calculate() => Value ?? 0;
public string PrintValue() => Value?.ToString();
}
public abstract class BinaryOperator : IValue
{
public IValue Left;
public IValue Right;
public abstract int Operation(int left, int right);
public abstract char Operator { get; }
public int Calculate()
{
var left = Left.Calculate();
var right = Right.Calculate();
return Operation(left, right);
}
public string PrintValue() => $"{Left?.PrintValue()} {Operator} {Right?.PrintValue()}";
}
public class Addition : BinaryOperator
{
public override char Operator => '+';
public override int Operation(int left, int right) => left + right;
}
// TODO define other operators
Then think about how each button should change the syntax tree.
// the entire formula
public IValue Root;
// the number currently being typed
public Number Input;
public void Display() {
panelText.text = Root.PrintValue();
}
// start / clear
public void Start(){
Root = Input = new Number(){
Value = 0
};
Display();
}
public void Plus(){
// left as an exercise for the reader
Display();
}
public void Digit(int digit) {
Input.AddDigit(digit);
Display();
}
public void Calculate() {
// left as an exercise for the reader
Display();
}
A method receiving 2 numbers and I need to return the numbers of common digits for them. For example, the numbers 2201 and 3021 returns 3 because these numbers have 3 common digits: 0, 1, and 2.
I get this error and don't understand it: A namespace cannot directly contain members such as fields or methods
Here is the code:
public static int AlphaRomeo(int a, int b)
{
int count = 0;
while (a > 0)
{
int tempa = a % 10;
a = a / 10;
int tempb = b % 10;
b = b / 10;
if (tempa == tempb)
count++;
}
return count;
}
Might be easier to avoid the mathematics:
private static string _digits = "0123456789";
public static int AlphaRomeo(int a, int b)
{
string aStr = a.ToString();
string bStr = b.ToString();
int common = 0;
for (int i = 0; i < _digits.Length; i++)
{
if (aStr.Contains(_digits[i]) && bStr.Contains(_digits[i]))
common++;
}
return common;
}
Consider this example, you don't have a class in your code:
using System; // Imports
namespace LearnClasses // Namespace
{
class Program //class
{
static void Main(string[] args) // Method 1
{
Console.WriteLine( AlphaRomeo(2201, 3021));
}
public static int AlphaRomeo(int a, int b) // Method 2
{
int count = 0;
// Your code
return count;
}
}
}
I'm trying to do a Radix sort in a Linked list class. I found radix sort algorithm for array and am trying to change it to work with my linked list. However, I'm a bit struggling. The code I'm trying to change is taken from http://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-10.php I tested the code with an array and it worked. Does anybody have any ideas how to make radix sort work in a linked list?
//abstract class
abstract class DataList
{
protected int length;
public int Length { get { return length; } }
public abstract double Head();
public abstract double Next();
public abstract void Swap(int a, int b);
public void Print(int n)
{
Console.Write("{0} ", Head());
for (int i = 1; i < n; i++)
Console.Write("{0} ", Next());
Console.WriteLine();
}
}
//linked list class
class LinkedList : DataList
{
class MyLinkedListNode
{
public MyLinkedListNode nextNode { get; set; }
public int data { get; set; }
public MyLinkedListNode(int data)
{
this.data = data;
}
public MyLinkedListNode()
{
this.data = 0;
}
}
MyLinkedListNode headNode;
MyLinkedListNode prevNode;
MyLinkedListNode currentNode;
public LinkedList(int n, int min, int max)
{
length = n;
Random rand = new Random();
headNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = headNode;
for (int i = 1; i < length; i++)
{
prevNode = currentNode;
currentNode.nextNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = currentNode.nextNode;
}
currentNode.nextNode = null;
}
public LinkedList()
{
headNode = new MyLinkedListNode();
currentNode = headNode;
}
public override double Head()
{
currentNode = headNode;
prevNode = null;
return currentNode.data;
}
public override double Next()
{
prevNode = currentNode;
currentNode = currentNode.nextNode;
return currentNode.data;
}
public override void Swap(int a, int b)
{
prevNode.data = a;
currentNode.data = b;
}
//my radix sort
public void radixSort()
{
int j = 0;
LinkedList tmp = new LinkedList();
for (int shift = 31; shift > -1; --shift)
{
//I try to go trough old list
MyLinkedListNode current = headNode;
while (current != null)
{
bool move = (current.data << shift) >= 0;
//I found this expression somewhere and I'm trying to use it to form a new Linked list (tmp)
if (shift == 0 ? !move : move)
;
else
{
if (tmp.headNode == null)
tmp.headNode = currentNode;
else
{
tmp.currentNode.nextNode = current;
//infinite loop happens on the commented line
//tmp.currentNode = tmp.currentNode.nextNode;
j++;
}
current = current.nextNode;
}
}
}
}
Following the C# radix sort example, you need an array of ten lists. Move nodes from the original list into the ten lists, appending a node with least signfificant digit == '0' into array_of_lists[0], '1' into array_of_list[1], and so on. After the original list is emptied, then concatenate the array of lists back into the original list and repeat for the next to least significant digit. Repeat the process until all the digits are handled.
You could use a larger base, such as base 16, where you would use an array of 16 lists. You can then select each "digit" using a shift and an and .
What I am trying to do is get the number of right angled triangles between 1 and 20 on both sides.
Most of the logic is fine, but when I want to check for 3, 4 and 5 this is one triangle, while 4, 3 and 5 would not be valid as it 3, 4, 5 in a different order.
Here is the code that I have written for the problem area
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
bool breakLoop = false;
Int32 length = triangleList.Count;
for (int index = 0; index < length && breakLoop != false; index++)
{
//This is to compare an existing adjacent that is stored in the list to the
//supplied opposite, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var response = triangleList.Find(r => r.IntAdjacent == intOpp);
if (response !=null)
{
//This is to compare an existing opposite that is stored in the list to the
//supplied adjacent, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var otherResponse = triangleList.Find(r => r.IntOpposite == intAdj);
if (otherResponse != null)
{
breakLoop = true;
}
}
}
return breakLoop;
}
Just in case anybody needs the Triangle code, here it is
public class Triangle
{
private int intAdjacent;
private int intOpposite;
private int intHypotenuse;
public Triangle(int intAdjacent, int intOpposite, int intHypotenuse)
{
this.intAdjacent = intAdjacent;
this.intOpposite = intOpposite;
this.intHypotenuse = intHypotenuse;
}
public int IntAdjacent
{
get { return intAdjacent; }
}
public int IntOpposite
{
get { return intOpposite; }
}
public int IntHypotenuse
{
get { return intHypotenuse; }
}
}
Could some one spot to see where I am making a mistake in the logic or have made an error in the code itself?
Keith
You can simplify this quite a lot like this:
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
if(triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
It first looks for any matches where the passed in values are a match, then reverses the search if they don't. It's slightly different to your code in that it looks for both adjacent and opposite at the same time which is where you went wrong. Additionally, it uses Any which returns a boolean value if any item is found that matches.
Thinking about this further, I would change the function to make it an extension method like this:
public static bool isAlreadyValidTriangle(this List<Triangle> triangleList, int intAdj, int intOpp)
{
if(triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
This means you can call it with a little more readability:
List<Triangle> triangleList = new List<Triangle>();
... fill list with triangles ...
if(triangleList.isAlreadyValidTriangle(adjacent, opposite)
{
...
}
First of all thanks for the advice and help.
Here is the complete code from start to finish
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication1
{
public class Program
{
private static double doubleHypotenuse = 0;
private static int adjacent = 1;
private static int opposite = 1;
private static int limit = 200;
private static int count = 0;
public static void Main(string[] args)
{
TriangleLogic triLogic = new TriangleLogic();
List<Triangle> triangleList = new List<Triangle>();
List<Triangle> trianglePlus1 = new List<Triangle>();
while (adjacent < limit)
{
opposite = 1;
while (opposite < limit)
{
doubleHypotenuse = triLogic.intRightAngle(adjacent, opposite);
if (doubleHypotenuse % 1 == 0)
{
if (!triLogic.isAlreadyValidTriangle(adjacent, opposite, triangleList))
{
triangleList.Add(new Triangle(adjacent, opposite, (int)Convert.ToInt32(doubleHypotenuse)));
}
count++;
}
opposite++;
}
adjacent++;
}
Console.WriteLine("The following are integer triangles");
triangleList.ForEach(delegate(Triangle pytag)
{
if ((pytag.IntHypotenuse - pytag.IntOpposite) == 1)
{
trianglePlus1.Add(new Triangle(pytag.IntAdjacent, pytag.IntOpposite, pytag.IntHypotenuse));
}
Console.WriteLine(pytag.IntAdjacent + ", " + pytag.IntOpposite + " and " + pytag.IntHypotenuse);
});
Console.WriteLine("the number of squares is " + count);
Int32 length = triangleList.Count;
Console.WriteLine("the length of the list is " + length);
Console.WriteLine("");
Console.WriteLine("the List of triangles with the hypotenuse 1 ");
Console.WriteLine("more than the opposite");
trianglePlus1.ForEach(delegate(Triangle pytagPlus1)
{
Console.WriteLine(pytagPlus1.IntAdjacent + ", " + pytagPlus1.IntOpposite + " and " + pytagPlus1.IntHypotenuse);
});
Int32 lengthPlus1 = trianglePlus1.Count;
Console.WriteLine("the length of the list is " + lengthPlus1);
}
}
}
Here is the Triangle Class
public class Triangle
{
private int intAdjacent;
private int intOpposite;
private int intHypotenuse;
public Triangle(int intAdjacent, int intOpposite, int intHypotenuse)
{
this.intAdjacent = intAdjacent;
this.intOpposite = intOpposite;
this.intHypotenuse = intHypotenuse;
}
public int IntAdjacent
{
get { return intAdjacent; }
}
public int IntOpposite
{
get { return intOpposite; }
}
public int IntHypotenuse
{
get { return intHypotenuse; }
}
}
And finally the TriangleLogic class
public class TriangleLogic
{
private double squareAdjacent = 0;
private double squareOpposite = 0;
private double squareSum = 0;
public TriangleLogic()
{
}
public double intRightAngle(int intAdjacent, int intOpposite)
{
squareAdjacent = Math.Pow(Convert.ToDouble(intAdjacent), 2);
squareOpposite = Math.Pow(Convert.ToDouble(intOpposite), 2);
squareSum = squareAdjacent + squareOpposite;
return Math.Sqrt(squareSum);
}
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
if (triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
}
Thanks again for the support
I'm trying to create a find method from scratch to see if two objects are equal given that the results of certain methods are equal, using the Equals method to do so. I know using the Find/Contains methods would be faster, but I'm not allowed use them. The signature of the method is "static int Find(List c, Coffee x)" Find seeks x in c and returns a valid index (e.g., 0, 1) if x exists in c, returns -1 otherwise. The equals method must be used to determine equivalency. If the passed object isn't equal to an object currently in the list, it is added to the list (the list contains two types of objects that derive from a base class, so the list can store both types). Equivalency is defined by name, cost, demand, holding cost(h) and roasttype(M) for regular and name, cost, demand, holding cost(h) and minimum quantity(also M) for decaf. Here's what I have so far (it's a lot of code that could probably be written better):
class EOQCalculator4
{
static void Main(string[] args)
{
// Create objects and references
Coffee obv = new Coffee();
Decaf decafCoffee = null;
Regular regularCoffee = null;
List<Coffee> inventory = new List<Coffee>();
// Prompt user for input and store it as a string
Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast ");
string s = Console.ReadLine();
// Loop
while (!s.ToLower().Equals("q"))
{
// Split string up and assign componets to variables
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string name = values[0];
string demand = (values[1]);
string cost = (values[2]);
string type = values[3];
// Check for > 0 and convert to numbers
float D = CheckDemand(demand);
float C = CheckCost(cost);
float M = 0;
if (type.StartsWith("D:"))
{
type = Regex.Match(type, #"\d+").Value;
M = CheckMin(type);
decafCoffee = new Decaf(name, D, C, M);
inventory.Add(decafCoffee);
}
else if (type.StartsWith("R:"))
{
if (type.Contains("light"))
{
M = 1;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else if (type.Contains("medium"))
{
M = 2;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else if (type.Contains("dark"))
{
M = 3;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else Console.WriteLine("\nError, please enter all lower case \"dark\", \"medium\", or \"light\" next time.");
}
else Console.WriteLine("\nError, please enter either \"D:\" followed by a number or \"R:\" followed by roast type next time.");
Console.Write("\nEnter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast: ");
s = Console.ReadLine();
} // End loop
// Sort and display values
var sortedList = inventory.OrderBy(i => i.Q()).ToList();
Console.WriteLine("\nName \t C ($) Demand \t Detail Q(lbs.) TAC ($) T(weeks) ");
for (int j = 0; j < inventory.Count; j++)
{
Console.WriteLine("{0}", sortedList[j].toString());
}
Console.WriteLine(obv.toStringQ());
}
#region CheckMethods
// Data validation methods
public static float CheckDemand(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for demand: ");
R = Console.ReadLine();
} return number;
}
public static float CheckCost(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for cost: ");
R = Console.ReadLine();
} return number;
}
public static float CheckMin(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for minimum quantity: ");
R = Console.ReadLine();
} return number;
}
public class Coffee
{
// Members
private static float sumQ = 0;
private static int mcount;
private float k = 20;
private float mc;
private string mName;
private float md;
private float q;
private float mh;
private float tac;
private float min = 0;
private float type = 0;
Coffee i = new Coffee();
public override bool Equals(object obj)
{
if (obj is Coffee)
{
bool isNameEqual = i.Name.Equals(this.Name);
bool isuCostEqual = i.Cost.Equals(this.Cost);
bool isDemandEqual = i.Demand.Equals(this.Demand);
bool ishCostEqual = i.h.Equals(this.h);
bool isMinEqual = i.getMin.Equals(this.min);
return (isNameEqual && isuCostEqual && isDemandEqual && ishCostEqual && isMinEqual);
}
return false;
}
// Default Constructor
public Coffee()
{ mcount = 0; }
// Full Constructor
public Coffee(string Name, float d, float c, float m)
{
mName = Name;
md = d;
mc = c;
mh = (float).30 * mc;
type = m;
min = m;
mcount++;
}
public Coffee(string Name, float d, float c)
{
mName = Name;
md = d;
mc = c;
mh = (float).30 * mc;
mcount++;
}
// Copy Constructor
public Coffee(Coffee e)
{
this.mName = e.mName;
this.md = e.md;
this.mh = e.mh;
this.mc = e.mc;
this.q = e.q;
mcount++;
}
// Destructor
~Coffee()
{ mcount--; }
// Properties
#region Properties
public float getMin
{
get { return min; }
}
public float getType
{
get { return type; }
}
public string Name
{
get { return mName; }
}
public float h
{
get { return mh; }
}
public float Cost
{
get { return mc; }
}
public float Demand
{
get { return md; }
}
public float getQ
{
get { return q; }
}
public float K
{
get { return k; }
}
public float getSumQ
{
get { return sumQ; }
set { sumQ = value; }
}
#endregion
// Methods
public virtual float Q()
{
q = (float)Math.Sqrt(2 * md * k / mh);
sumQ += q;
return q;
}
public virtual float TAC()
{
tac = q / 2 * mh + md * k / q + md * mc;
return tac;
}
public virtual float T()
{
float t = (q / (md / 52));
return t;
}
public virtual string toString()
{
string a = String.Format("{0,-10:s} {1,-10:f2} {2,-13:f0} {3,-11:f0} {4,-11:f2} {5,-0:f2}", mName, mc, md, Q(), TAC(), T());
return a;
}
public virtual string toStringQ()
{
string c = String.Format("\nIf you purchase all of the coffee you will need space to hold {0,-0:f2} of coffee", sumQ);
return c;
}
}
}
public class Decaf : Coffee
{
// Members
private float k = 30;
private float min;
private float q;
// Constructor
public Decaf(string Name, float d, float c, float m)
: base(Name, d, c)
{
min = m;
}
// Methods
public override float Q()
{
q = (float)Math.Sqrt(2 * Demand * k / h);
if (q < min)
{
return min;
}
else return q;
}
public override float TAC()
{
getSumQ += Q();
return Q() / 2 * h + Demand * k / Q() + Demand * Cost;
}
public override float T()
{
return (Q() / (Demand / 52));
}
public override string toString()
{
string a = String.Format("{0,-11:s}{1,-11:f2}{2,-12:f0}{3,-9:f0}{4,-12:f0}{5,-13:f2}{6,-10:f2}", Name, Cost, Demand, min, Q(), TAC(), T());
return a;
}
}
}
// Enumerator
[Flags] enum RoastType { light = 1, medium = 2, dark = 3 }
public class Regular : Coffee
{
// Members
RoastType roast;
private float q;
private float k = 20;
// Constructor
public Regular(string Name, float d, float c, float r)
: base(Name, d, c)
{
int x = (int) r;
roast = (RoastType) x;
roast.ToString();
}
// Methods
public override float Q()
{
q = (float)Math.Sqrt(2 * Demand * k / h);
return q;
}
public override float TAC()
{
getSumQ += Q();
return Q() / 2 * h + Demand * k / Q() + Demand * Cost;
}
public override float T()
{
return (Q() / (Demand / 52));
}
public override string toString()
{
string b = String.Format("{0,-11:s}{1,-11:f2}{2,-12:f0}{3,-9:s}{4,-12:f0}{5,-13:f2}{6,-10:f2}", Name, Cost, Demand, roast.ToString(), Q(), TAC(), T());
return b;
}
}
}
Assuming I implemented the equals method correctly, where/how would I implement the "static int Find(List<Coffee> c, Coffee x)" method?
As it stands your overridden Equals method won't work correctly. Equals tests for reference equality i.e. if two object references point to the same object. See MSDN for more info on Equals.
If you are just wanting to make sure that the same two coffees (with the same name, demand cost and type) are not added, then you can perform a simple value check on those fields, something like (method added to your Coffee class)
public bool CoffeeIsSame(Coffee c2)
{
return (this.Name == c2.Name) && (this.Demand == this.Demand) && (this.Cost == c2.Cost) && (this.Type == c2.Type);
}
Your Find method could look something like this:
static bool Find(List c, Coffee x)
{
bool result = false;
foreach(Coffee coffee in c)
{
result = coffee.CoffeeIsSame(x);
if (result)
{
break;
}
}
return result;
}
To implement your static Find method, you could add it to your Coffee class. Then you call it like this (using some of your code from your Main method as an example):
...
else if (type.Contains("dark"))
{
M = 3;
regularCoffee = new Regular(name, D, C, M);
if (!Coffee.Find(inventory, regularCoffee))
{
inventory.Add(regularCoffee);
}
}
...
Hope that helps,
cheers