Examples of smaller Java programs that do various interesting things.

RecursionExampleDirectory.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. public class RecursionExampleDirectory
  2. {
  3. public int getSize(Directory dir)
  4. { int total = 0;
  5. //check files
  6. File[] files = dir.getFiles();
  7. for(int i = 0; i < files.length; i++)
  8. total += files[i].getSize();
  9. //get sub directories and check them
  10. Directory[] subs = dir.getSubs();
  11. for(int i = 0; i < subs.length; i++)
  12. total += getSize(subs[i]);
  13. return total;
  14. }
  15. public static void main(String[] args)
  16. { RecursionExampleDirectory r = new RecursionExampleDirectory();
  17. Directory d = new Directory();
  18. System.out.println( r.getSize(d) );
  19. }
  20. //pre: n >= 0
  21. public static int fact(int n)
  22. { int result = 0;
  23. if(n == 0)
  24. result = 1;
  25. else
  26. result = n * fact(n-1);
  27. return result;
  28. }
  29. //pre: exp >= 0
  30. public static int pow(int base, int exp)
  31. { int result = 0;
  32. if(exp == 0)
  33. result = 1;
  34. else
  35. result = base * pow(base, exp - 1);
  36. return result;
  37. }
  38. //slow fib
  39. //pre: n >= 1
  40. public static int fib(int n)
  41. { int result = 0;
  42. if(n == 1 || n == 2)
  43. result = 1;
  44. else
  45. result = fib(n-1) + fib(n-2);
  46. return result;
  47. }
  48. public static int minWasted(int[] items, int itemNum, int capLeft)
  49. { int result = 0;
  50. if(itemNum >= items.length)
  51. result = capLeft;
  52. else if( capLeft == 0)
  53. result = 0;
  54. else
  55. { int minWithout = minWasted(items, itemNum + 1, capLeft);
  56. if( capLeft <= items[itemNum])
  57. { int minWith = minWasted(items, itemNum + 1, capLeft - items[itemNum]);
  58. result = Math.min(minWith, minWithout);
  59. }
  60. else
  61. result = minWithout;
  62. }
  63. return result;
  64. }
  65. }
  66. class Directory
  67. { private Directory[] mySubs;
  68. private File[] myFiles;
  69. public Directory()
  70. { int numSubs = (int)(Math.random() * 3);
  71. mySubs = new Directory[numSubs];
  72. int numFiles = (int)(Math.random() * 10);
  73. myFiles = new File[numFiles];
  74. for(int i = 0; i < myFiles.length; i++)
  75. myFiles[i] = new File( (int)(Math.random() * 1000 ) );
  76. for(int i = 0; i < mySubs.length; i++)
  77. mySubs[i] = new Directory();
  78. }
  79. public Directory[] getSubs()
  80. { return mySubs;
  81. }
  82. public File[] getFiles()
  83. { return myFiles;
  84. }
  85. }
  86. class File
  87. { private int iMySize;
  88. public File(int size)
  89. { iMySize = size;
  90. }
  91. public int getSize()
  92. { return iMySize;
  93. }
  94. }