📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / Programmieren-Tutorium / Tutorium-10 / Hanoi / Pole.java
132948 viewsLicense: OTHER
/**1A Pole is a stick with Discs on it. The Discs have to be sorted ascending by their size, at all time.2Discs can be moved from one pole to another. Only the Disc on top of a pole can be accessed.3*/4public class Pole {5private Disc[] discs;6int currPop; //the index of the element, which has to be popped next.78/**9Creates a {@code Pole} with a given capacity.1011The capacity is a positive number. It indicates, how many Discs can be handeld by the Pole-Instance.12@param capacity the capacity of the new pole13*/14public Pole(int capacity) {15if (capacity < 0) {16throw new IllegalArgumentException("Invalid capacity. Has to be >= 0!");17}18discs = new Disc[capacity];19currPop = -1;20}2122/**23Pushes a given disc to the top of this pole.2425The result will be false, if the pole is full or the size of the given disc does not fit.26@param d the disc to push onto this pole27@param true of the operation has succeeded28@return true iff operation was successfull, otherwise false29*/30public boolean push(Disc d) {31if (d == null) {32throw new IllegalArgumentException("parameter was null");33} else if (getTopDisc() != null && getTopDisc().getSize() <= d.getSize()) {34return false; //size of d is too big.35} else if (currPop >= discs.length - 1) {36return false; //full37}3839currPop++;40discs[currPop] = d;41return true;42}4344/**45Fetches the Disc of the top of the Pole, removes it from the pole and returns the disc.46@return the top disc of the pole or null, if the pole is empty.47*/48public Disc pop() {49Disc result = getTopDisc();50if(result != null) { //if there is no top disc, there is no need of change of currPop.51discs[currPop] = null;52currPop--;53}54return result;55}5657public String toString() {58String result = "";59for(int i = discs.length - 1; i >= 0; i--) {60result += discToString(discs[i], discs.length) + "\n";61}62return result;63}6465private String discToString(Disc d, int width) {66String result = "";67int padWhitespace = width;68if(d == null) {69result = "|";70} else {71padWhitespace = (width - d.getSize());72for (int i = 0; i < d.getSize(); i++){73result += "+++";74}75}76//pad left/right77for(int i = 0; i < padWhitespace; i++) {78result = " " + result + " ";79}8081return result;82}8384/**85Returns the number of discs on this pole.86@return the number of discs87*/88public int getSize() {89return currPop + 1;90}9192/* Returns the disc on top (or null if empty), but doesn't pop it.*/93private Disc getTopDisc() {94if (currPop >= 0) {95return discs[currPop];96} else {97return null;98}99}100}101102103