Exercises from labs 2023-2024
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

week1.java 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import java.util.Calendar;
  2. import java.util.Scanner;
  3. import java.util.concurrent.ThreadLocalRandom;
  4. class runLabs {
  5. public static void main(String[] args) {
  6. new Lab4();
  7. new Lab5();
  8. new Lab6();
  9. }
  10. }
  11. class Section {
  12. private int _sectionNumber;
  13. public Section(int s) {
  14. this._sectionNumber = s;
  15. this.printSection();
  16. }
  17. public int getSection() {
  18. return _sectionNumber;
  19. }
  20. public void printSection() {
  21. String title = String.format("Starting section %s", this._sectionNumber);
  22. System.out.println("-".repeat(title.length()));
  23. System.out.println(String.format("%s", title));
  24. System.out.println("-".repeat(title.length()));
  25. }
  26. }
  27. class Lab {
  28. public Lab(int lN) {
  29. String title = String.format("|Starting Lab %s|", lN);
  30. this._labNumber = lN;
  31. System.out.println("*".repeat(title.length()));
  32. System.out.println(title);
  33. System.out.println("*".repeat(title.length()));
  34. }
  35. private int _labNumber;
  36. public Section currentSection;
  37. public Section getCurrentSection() {
  38. return currentSection;
  39. }
  40. public void setCurrentSection(Section currentSection) {
  41. this.currentSection = currentSection;
  42. }
  43. public static void printSection(String section) {
  44. String title = String.format("Starting section %s", section);
  45. System.out.println("-".repeat(title.length()));
  46. System.out.println(String.format("%s", title));
  47. System.out.println("-".repeat(title.length()));
  48. }
  49. public int getLabNumber() {
  50. return this._labNumber;
  51. }
  52. }
  53. class Lab4 extends Lab {
  54. public Lab4() {
  55. super(4);
  56. ex44();
  57. ex46();
  58. }
  59. // public static void main(String[] args) {
  60. // }
  61. public static void ex41() {
  62. String labSection = "4.1";
  63. // System.out.println(String.format("Starting section %s", labSection));
  64. printSection(labSection);
  65. int testYear1 = 1996; // true
  66. int testYear2 = 1997; // false
  67. int testYear3 = 2000; // true
  68. int testYear4 = 9332; // true
  69. int testYear5 = 1900; // false
  70. int randomYear = ThreadLocalRandom.current().nextInt(1, 9999 + 1);
  71. System.out.println(String.format("Testing %s", testYear1));
  72. System.out.println(String.format("%s", isLeap(testYear1)));
  73. System.out.println(String.format("Testing %s", testYear2));
  74. System.out.println(String.format("%s", isLeap(testYear2)));
  75. System.out.println(String.format("Testing %s", testYear3));
  76. System.out.println(String.format("%s", isLeap(testYear3)));
  77. System.out.println(String.format("Testing %s", testYear4));
  78. System.out.println(String.format("%s", isLeap(testYear4)));
  79. System.out.println(String.format("Testing %s", randomYear));
  80. System.out.println(String.format("%s", isLeap(randomYear)));
  81. System.out.println(String.format("Testing %s", testYear5));
  82. }
  83. public static void ex44() {
  84. String labSection = "4.4";
  85. printSection(labSection);
  86. // System.out.println("------------------------");
  87. // System.out.println("Starting lab section " + labSection);
  88. // System.out.println("------------------------");
  89. String month1 = "oct";
  90. int year1 = 2000;
  91. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  92. month1, year1, monthLen(month1, year1)));
  93. String month2 = "feb";
  94. int year2 = 2000;
  95. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  96. month2, year2, monthLen(month2, year2)));
  97. String month3 = "feb";
  98. int year3 = 1997;
  99. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  100. month3, year3, monthLen(month3, year3)));
  101. String month4 = "apr";
  102. int year4 = 2001;
  103. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  104. month4, year4, monthLen(month4, year4)));
  105. }
  106. /**
  107. * Lab section 4.5
  108. *
  109. * Write a program that can calculate how many whole years old someone is from
  110. * today’s date and their date of birth. You could store each date as three
  111. * integers (day,
  112. * month, year)
  113. */
  114. public static void ex46() {
  115. String labSection = "4.6";
  116. printSection(labSection);
  117. // calculate whole years' old to date
  118. Calendar today = Calendar.getInstance();
  119. System.out.println("Today:\t" + today.getTime());
  120. Calendar dob1 = Calendar.getInstance();
  121. dob1.set(1990, 1, 1);
  122. System.out.println(String.format(
  123. "DOB 1:\t%s (difference:\t%d years)",
  124. dob1.getTime(),
  125. yearDifference(today, dob1)));
  126. Calendar dob2 = Calendar.getInstance();
  127. dob2.set(1994, 12, 22);
  128. System.out.println(String.format(
  129. "DOB 2:\t%s (difference:\t%d years)",
  130. dob2.getTime(),
  131. yearDifference(today, dob2)));
  132. }
  133. public static boolean isLeap(int year) {
  134. if (year % 4 != 0) {
  135. return false;
  136. } else {
  137. if (year % 100 == 0) {
  138. if (year % 400 == 0) {
  139. return true;
  140. } else {
  141. return false;
  142. }
  143. }
  144. return true;
  145. }
  146. }
  147. public static int monthLen(String month, int year) {
  148. if (month == "feb") {
  149. if (isLeap(year)) {
  150. return 29;
  151. } else {
  152. return 28;
  153. }
  154. } else if (
  155. (month == "apr") ||
  156. (month == "jun") ||
  157. (month == "sep") ||
  158. (month == "nov")) {
  159. return 30;
  160. } else {
  161. return 31;
  162. }
  163. }
  164. public static int yearDifference(Calendar date1, Calendar date2)
  165. {
  166. return (int) Math.abs(date1.get(Calendar.YEAR) -
  167. date2.get(Calendar.YEAR)
  168. );
  169. }
  170. }
  171. /**
  172. * Keyboard input
  173. */
  174. class Lab5 extends Lab {
  175. public Lab5() {
  176. super(5);
  177. new five1();
  178. }
  179. class five1 extends Section {
  180. /**
  181. * We will now look at how we can get user input from the keyboard. We will
  182. * gloss over some
  183. * of the details here, but give you just the information you need to start
  184. * getting input and
  185. * processing it.
  186. */
  187. public five1() {
  188. super(1);
  189. System.out.println(String.format("TBC"));
  190. // Scanner keyboard = new Scanner(System.in);
  191. // System.out.println("Please enter your name, followed by the return key?");
  192. // String userEntry = keyboard.nextLine();
  193. // System.out.println("Hello " + userEntry);
  194. // System.out.println(String.format("%s", keyboard));
  195. }
  196. }
  197. }
  198. /**
  199. * Loops
  200. */
  201. class Lab6 extends Lab {
  202. public Lab6() {
  203. super(6);
  204. new six1();
  205. System.out.println(String.format("%n"));
  206. new six3();
  207. new six5();
  208. new six6();
  209. new six7();
  210. }
  211. /**
  212. * Times tables
  213. */
  214. class six1 extends Section {
  215. public six1() {
  216. super(1);
  217. int testNum = 6;
  218. System.out.println(String.format("Times table for %d:", testNum));
  219. writeTimesTable(7);
  220. }
  221. }
  222. class six3 extends Section {
  223. public six3() {
  224. super(3);
  225. int testNum = 13; // statistically the most prime of all numbers
  226. System.out.println(String.format("Testing primes..."));
  227. System.out.println(String.format("%d prime? %s", testNum, isPrime(testNum)));
  228. System.out.println(String.format("%d prime? %s", 23, isPrime(23)));
  229. System.out.println(String.format("%d prime? %s", 27, isPrime(27)));
  230. System.out.println(String.format("%d prime? %s", 28, isPrime(28)));
  231. System.out.println(String.format("%d prime? %s", 299, isPrime(299)));
  232. System.out.println(String.format("Generating primes..."));
  233. generatePrimes(1024);
  234. System.out.println(String.format("Done!%n"));
  235. }
  236. }
  237. class six5 extends Section {
  238. public six5() {
  239. super(5);
  240. System.out.println(String.format("TODO / NOT IMPLEMENTED until we get stdin working"));
  241. }
  242. }
  243. /**
  244. * Produce a number triangle
  245. *
  246. * eg:
  247. * 1
  248. * 2 2
  249. * 3 3 3
  250. * 4 4 4 4
  251. */
  252. class six6 extends Section {
  253. public six6() {
  254. super(6);
  255. numberTriangle(8);
  256. }
  257. }
  258. class six7 extends Section {
  259. public six7() {
  260. super(7);
  261. describeDD(4.2, 1.6);
  262. describeDD(47.42, 7.9);
  263. }
  264. /** Simple exposition of double division
  265. * @param num1 Dividend
  266. * @param num2 Divisor
  267. */
  268. public void describeDD(double num1, double num2) {
  269. System.out.println(String.format("Double division of %.2f by %.2f:\t", num1, num2));
  270. DoubleDivisionResult result = doubleDivision(num1, num2);
  271. System.out.println(String.format("Quotient: %d (ie %.2f ✕ %d = %.2f)\tRemainder: %.2f",
  272. result.getQuotient(),
  273. num2,
  274. result.getQuotient(),
  275. (num2 * result.getQuotient()),
  276. result.getRemainder()));
  277. }
  278. }
  279. /* TOASK - is there a better way of returning multiple values in Java?
  280. à la python, ie: return (quotient, remainder)
  281. */
  282. /**
  283. * Wrapper class for returning results from double division
  284. */
  285. final class DoubleDivisionResult {
  286. private int quotient; // that's the number of times something goes into something else
  287. private double remainder; // that's the bit left over
  288. public DoubleDivisionResult(int quotient, double remainder) {
  289. this.quotient = quotient;
  290. this.remainder = remainder;
  291. }
  292. public int getQuotient() {
  293. return quotient;
  294. }
  295. public double getRemainder() {
  296. return remainder;
  297. }
  298. }
  299. /**
  300. * Perform 'double division'
  301. *
  302. * @param dividend Number to be divided
  303. * @param divisor Number to divide by
  304. * @return a {@link DoubleDivisionResult} with the (int) quotient and (double) remainder
  305. */
  306. public DoubleDivisionResult doubleDivision(double dividend, double divisor) {
  307. // example used is 4.2 and 1.6
  308. // should return 2 and 1.0
  309. final boolean DEBUG = false;
  310. double dQuotient = dividend / divisor;
  311. int iQuotient = (int)dQuotient;
  312. double remainder = dividend - (iQuotient * divisor);
  313. if (DEBUG) {
  314. System.out.println(String.format("float quotient: %.2f", dQuotient));
  315. System.out.println(String.format("int quotient: %d", iQuotient));
  316. // TOASK: is there a neater way to do this casting?
  317. }
  318. return new DoubleDivisionResult(iQuotient, remainder);
  319. }
  320. /**
  321. * @param num Size of triangle
  322. */
  323. public void numberTriangle(int num) {
  324. /* Observations:
  325. - for even-sized triangles, preceding number of spaces starts at n=rows and decrements
  326. - for even-sized triangles even numbers have odd spaces and vice versa
  327. */
  328. System.out.println(String.format(""));
  329. int spaces = num;
  330. for (int i = 1; i <= num; i++) {
  331. System.out.println(" ".repeat(spaces)
  332. + String.format("%s ", i).repeat(i)
  333. + " ".repeat(spaces-1)
  334. );
  335. spaces--;
  336. }
  337. System.out.println(String.format(""));
  338. }
  339. /**
  340. * @param num The number to write the times table for
  341. * @param limit How many multiples to show
  342. */
  343. public void writeTimesTable(int num, int limit) {
  344. for (int i = 0; i < (limit + 1); i++) {
  345. System.out.printf("%d\t", num * i);
  346. }
  347. }
  348. /* TOASK - overload example.
  349. Question: is there a better way of doing optional function parameters in java?
  350. */
  351. /**
  352. * Write times table for num (10 entries)
  353. * @param num Number to show times table for
  354. */
  355. public void writeTimesTable(int num) {
  356. int DEFAULT_LIMIT = 10;
  357. writeTimesTable(num, DEFAULT_LIMIT);
  358. }
  359. public void generatePrimes(int upperLimit) {
  360. // handle 2 as a special case
  361. System.out.println(String.format("2"));
  362. // for (int i = 3; i <= upperLimit; i += 2) {
  363. for (int i = 2; i <= upperLimit; i++) {
  364. // TODO: figure out smarter way of doing this, I'm sure primes must be at least 6 apart...
  365. // Something about 2n ± 1 ?
  366. // seive of Erasthotenes ..?
  367. if (isPrime(i)) {
  368. System.out.printf("%d\t", i);
  369. }
  370. }
  371. }
  372. /**
  373. * But is it prime?
  374. * @param num Integer to test for primality
  375. * @return if it's prime
  376. */
  377. public boolean isPrime(int num) {
  378. boolean DEBUG = false;
  379. if ((num == 2) || (num == 1)) {
  380. return true;
  381. }
  382. if (num % 2 == 0){
  383. return false;
  384. } else {
  385. int divisor = 3;
  386. double numSquareRoot = Math.sqrt((double)num);
  387. while (divisor <= numSquareRoot) {
  388. if (num % divisor == 0) {
  389. return false;
  390. }
  391. divisor += 2;
  392. if (DEBUG) {
  393. System.out.printf("%d\t", divisor);
  394. }
  395. }
  396. return true;
  397. }
  398. }
  399. }