Pfadevierschritt.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. import java.math.BigInteger;
  7. import java.util.Arrays;
  8. /**
  9. *
  10. * @author iZc <nplusc.de>
  11. */
  12. public class Pfadevierschritt
  13. {
  14. public static void main(String[] args)
  15. {
  16. System.out.println(calculatePaths(11));
  17. }
  18. public static BigInteger calculatePaths(int n)
  19. {
  20. //speichertabelle, aktuell und letzte
  21. BigInteger[][] table=new BigInteger[2][];//eine seite initialisieren mit leerem array (n modulo 2, gibt entweder 0 oder 1, nächster lauf wechselt
  22. table[n%2]=new BigInteger[n+1];
  23. Arrays.fill(table[n%2], BigInteger.ZERO);//array füllen
  24. table[n%2][0]=BigInteger.ONE;//eine zelle auf 1 seeded, da von def vorherigen reihe je 1 pfad hingeht // magie enthalten
  25. for(int x=n-1;x>=0;x--)//von rechts nach links scannen
  26. {
  27. //System.out.println("X="+x);
  28. BigInteger[] tableadd=new BigInteger[x+1];//tabellenspalte für neue werte
  29. Arrays.fill(tableadd, BigInteger.ZERO);//füllen
  30. BigInteger[] tabletouse = table[(x+1)%2];//tabellenspalte für spalte 1 rechts rausziehen
  31. for(int y=0;y<=x;y++)//hochwärts scannen
  32. {
  33. //arithmetik um innerhalb der grenzen zu bleiben
  34. if(y-4>=0)
  35. {
  36. // System.out.println("-4");
  37. tableadd[y]=tableadd[y].add(tabletouse[y-4]);
  38. }
  39. if(y-1>=0)
  40. {
  41. //System.out.println("-1");
  42. tableadd[y]=tableadd[y].add(tabletouse[y-1]);
  43. }
  44. //System.out.println("+-0");
  45. tableadd[y]=tableadd[y].add(tabletouse[y]);
  46. if(y+1<=x+1)
  47. {
  48. //System.out.println("+1");
  49. tableadd[y]=tableadd[y].add(tabletouse[y+1]);
  50. }
  51. if(y+4<=x+1)
  52. {
  53. //System.out.println("+4");
  54. tableadd[y]=tableadd[y].add(tabletouse[y+4]);
  55. }
  56. }
  57. table[x%2]=tableadd;
  58. //tabelle zurücknudeln
  59. }
  60. //rlement an 0|0 enthält das ergebnis
  61. return table[0][0];
  62. }
  63. }