Can someone explain what to do with this code? i have already write FindFisrtitem() but with FindPoorer() I have a problem…
1.I need to write a method FindPoorer();. Method have to find a lowest account balance and if will not find, method need to return "Basia".
- Same question but method need to return null.
I don’t expect 100% solution of tasks, but rather a hint
using System;
namespace Poorer
{
class Item
{
public Item PreviousItem { get; set; }
public string Name { get; set; }
public double AccountBalance { get; set; }
public Item(string name, double balance, Item prevItem)
{
Name = name;
AccountBalance = balance;
PreviousItem = prevItem;
}
internal Item AddItem(string v1, int v2)
{
return new Item(v1, v2, this);
}
internal Item FindFirstItem()
{
//if (PreviousItem == null)
//{
// return this;
//}
//return PreviousItem.FindFirstItem();
var curr = this;
while (true)
{
if (curr.PreviousItem == null)
{
return curr;
}
curr = curr.PreviousItem;
}
}
internal Item FindPoorer()
{
if(AccountBalance > 0)
{
return ;
}
return FindPoorer();
}
}
class ListExcercise
{
static void Main(string[] args)
{
var basia = new Item("Basia", 100, null);
var kasia = basia.AddItem("Kasia", 50);
var isia = kasia.AddItem("Isia", 40);
var isia2 = isia.AddItem("Isia2", 20);
var isia3 = isia2.AddItem("Isia3", 40);
var first = isia3.FindFirstItem();
var poorer = isia3.FindPoorer();
Console.WriteLine("The poorer person is: " + poorer.Name);
}
}
}
>Solution :
Just loop through the list like you did with FindFirstItem().
Compare the current item with the poorest item (as of now) then return it when you reach the end of list.
You do not need to use recursive here.
Pseudocode:
internal Item FindPoorer()
{
var curr = this;
var poorest = this;
while (true)
{
if (curr.balance < poorest.balance)
{
poorest = curr;
}
if (curr.PreviousItem == null)
{
return poorest;
}
curr = curr.PreviousItem;
}
}