Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. package pt.ipleiria.estg.dei.aed.recursividade.algoritmos;
  2.  
  3. import pt.ipleiria.estg.dei.aed.utils.EstatisticaDeChamadasEMovimentos;
  4.  
  5. public class Hanoi {
  6. public void executar(int n, Torre inicial, Torre fim, Torre aux, boolean mostrar, EstatisticaDeChamadasEMovimentos estatistica) {
  7. estatistica.incrementarChamadas();
  8. if (n <= 0) {
  9. if (n <= 0) {
  10. throw new IllegalArgumentException("hanoi(" + n + ") = argumento inválido: deve ser > 0");
  11. }
  12. }
  13. if (n == 1) {
  14. estatistica.incrementarMovimentos();
  15. fim.adicionarDisco(inicial.removerDisco());
  16. if (mostrar) {
  17. System.out.println("Disco " + n + " movido da torre " + inicial + " para a torre " + fim + ".");
  18. }
  19. return;
  20. }
  21. executar(n - 1, inicial, aux, fim, mostrar, estatistica);
  22. estatistica.incrementarMovimentos();
  23. if (mostrar) {
  24. System.out.println("Disco " + n + " movido da torre " + inicial + " para a torre " + fim + ".");
  25. }
  26. executar(n - 1, aux, fim, inicial, mostrar, estatistica);
  27. }
  28.  
  29. public EstatisticaDeChamadasEMovimentos getEstatistica(int n, boolean mostrar) {
  30. try {
  31. Torre inicial = new Torre("incial", n);
  32. Torre aux = new Torre("aux",n);
  33. Torre fim = new Torre("final",n);
  34. inicial.preencherComDiscos();
  35. EstatisticaDeChamadasEMovimentos estatistica = new EstatisticaDeChamadasEMovimentos(n);
  36. executar(n, inicial, aux, fim, mostrar, estatistica);
  37. estatistica.parar();
  38. estatistica.apresentar();
  39. return estatistica;
  40. } catch (RuntimeException exception) {
  41. System.err.println(exception.getMessage() + "\n");
  42. return null;
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement