first commit
This commit is contained in:
82
HanoiTowers.cs
Normal file
82
HanoiTowers.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
namespace su.divan2000.PLandDS_hanoi
|
||||
{
|
||||
class HanoiTowers
|
||||
{
|
||||
private int[] tower_A;
|
||||
private int[] tower_B;
|
||||
private int[] tower_C;
|
||||
|
||||
private int size;
|
||||
|
||||
public HanoiTowers(int size)
|
||||
{
|
||||
this.size = size;
|
||||
tower_A = new int[size];
|
||||
tower_B = new int[size];
|
||||
tower_C = new int[size];
|
||||
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
tower_A[i] = size - i;
|
||||
}
|
||||
}
|
||||
|
||||
public string toString()
|
||||
{
|
||||
int charsPerTower = size.ToString().Length;
|
||||
string result = "";
|
||||
for (int i = size - 1; i >= 0; i--)
|
||||
{
|
||||
result += tower_A[i].ToString().PadLeft(charsPerTower).Replace("0", "|") + " ";
|
||||
result += tower_B[i].ToString().PadLeft(charsPerTower).Replace("0", "|") + " ";
|
||||
result += tower_C[i].ToString().PadLeft(charsPerTower).Replace("0", "|") + "\n";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void move(int from, int to)
|
||||
{
|
||||
int[] sourceTower = getTower(from);
|
||||
int[] targetTower = getTower(to);
|
||||
|
||||
int sourceTopIndex = getTopIndex(sourceTower);
|
||||
int targetTopIndex = getTopIndex(targetTower);
|
||||
|
||||
if (sourceTopIndex == -1)
|
||||
{
|
||||
throw new InvalidOperationException("No disk to move");
|
||||
}
|
||||
|
||||
if (targetTopIndex != -1 && sourceTower[sourceTopIndex] > targetTower[targetTopIndex])
|
||||
{
|
||||
throw new InvalidOperationException("Cannot place larger disk on smaller one");
|
||||
}
|
||||
|
||||
targetTower[targetTopIndex + 1] = sourceTower[sourceTopIndex];
|
||||
sourceTower[sourceTopIndex] = 0;
|
||||
}
|
||||
|
||||
private int[] getTower(int index)
|
||||
{
|
||||
switch (index)
|
||||
{
|
||||
case 0: return tower_A;
|
||||
case 1: return tower_B;
|
||||
case 2: return tower_C;
|
||||
default: throw new ArgumentException("Invalid tower index");
|
||||
}
|
||||
}
|
||||
|
||||
private int getTopIndex(int[] tower)
|
||||
{
|
||||
for (int i = size - 1; i >= 0; i--)
|
||||
{
|
||||
if (tower[i] != 0)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // Tower is full
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user