Exercises from labs 2023-2024
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

642 linhas
20 KiB

  1. import java.util.Calendar;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4. import java.util.concurrent.ThreadLocalRandom;
  5. class runLabs {
  6. public static void main(String[] args) {
  7. new Lab4();
  8. new Lab5();
  9. new Lab6();
  10. // new Lab7();
  11. }
  12. }
  13. class Exercise {
  14. private int _exerciseNumber;
  15. public Exercise(int s) {
  16. this._exerciseNumber = s;
  17. this.printExercise();
  18. }
  19. public void printExercise() {
  20. String title = String.format("Starting exercise %s", this._exerciseNumber);
  21. System.out.println("-".repeat(title.length()));
  22. System.out.println(String.format("%s", title));
  23. System.out.println("-".repeat(title.length()));
  24. }
  25. public int get_exerciseNumber() {
  26. return _exerciseNumber;
  27. }
  28. public void set_exerciseNumber(int _exerciseNumber) {
  29. this._exerciseNumber = _exerciseNumber;
  30. }
  31. }
  32. class Lab {
  33. private int _labNumber;
  34. public Exercise currentExercise;
  35. public Lab(int lN) {
  36. String title = String.format("|Starting Lab %s|", lN);
  37. this._labNumber = lN;
  38. System.out.println("*".repeat(title.length()));
  39. System.out.println(title);
  40. System.out.println("*".repeat(title.length()));
  41. }
  42. public Exercise getCurrentExercise() {
  43. return currentExercise;
  44. }
  45. public void setCurrentExercise(Exercise currentSection) {
  46. this.currentExercise = currentSection;
  47. }
  48. public static void printSection(String section) {
  49. String title = String.format("Starting exercise %s", section);
  50. System.out.println("-".repeat(title.length()));
  51. System.out.println(String.format("%s", title));
  52. System.out.println("-".repeat(title.length()));
  53. }
  54. public int getLabNumber() {
  55. return this._labNumber;
  56. }
  57. }
  58. class Lab4 extends Lab {
  59. public Lab4() {
  60. super(4);
  61. ex44();
  62. ex46();
  63. }
  64. // public static void main(String[] args) {
  65. // }
  66. public static void ex41() {
  67. String labSection = "4.1";
  68. // System.out.println(String.format("Starting section %s", labSection));
  69. printSection(labSection);
  70. int testYear1 = 1996; // true
  71. int testYear2 = 1997; // false
  72. int testYear3 = 2000; // true
  73. int testYear4 = 9332; // true
  74. int testYear5 = 1900; // false
  75. int randomYear = ThreadLocalRandom.current().nextInt(1, 9999 + 1);
  76. System.out.println(String.format("Testing %s", testYear1));
  77. System.out.println(String.format("%s", isLeap(testYear1)));
  78. System.out.println(String.format("Testing %s", testYear2));
  79. System.out.println(String.format("%s", isLeap(testYear2)));
  80. System.out.println(String.format("Testing %s", testYear3));
  81. System.out.println(String.format("%s", isLeap(testYear3)));
  82. System.out.println(String.format("Testing %s", testYear4));
  83. System.out.println(String.format("%s", isLeap(testYear4)));
  84. System.out.println(String.format("Testing %s", randomYear));
  85. System.out.println(String.format("%s", isLeap(randomYear)));
  86. System.out.println(String.format("Testing %s", testYear5));
  87. }
  88. public static void ex44() {
  89. String labSection = "4.4";
  90. printSection(labSection);
  91. // System.out.println("------------------------");
  92. // System.out.println("Starting lab section " + labSection);
  93. // System.out.println("------------------------");
  94. String month1 = "oct";
  95. int year1 = 2000;
  96. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  97. month1, year1, monthLen(month1, year1)));
  98. String month2 = "feb";
  99. int year2 = 2000;
  100. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  101. month2, year2, monthLen(month2, year2)));
  102. String month3 = "feb";
  103. int year3 = 1997;
  104. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  105. month3, year3, monthLen(month3, year3)));
  106. String month4 = "apr";
  107. int year4 = 2001;
  108. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  109. month4, year4, monthLen(month4, year4)));
  110. }
  111. /**
  112. * Lab section 4.5
  113. *
  114. * Write a program that can calculate how many whole years old someone is from
  115. * today’s date and their date of birth. You could store each date as three
  116. * integers (day,
  117. * month, year)
  118. */
  119. public static void ex46() {
  120. String labSection = "4.6";
  121. printSection(labSection);
  122. // calculate whole years' old to date
  123. Calendar today = Calendar.getInstance();
  124. System.out.println("Today:\t" + today.getTime());
  125. Calendar dob1 = Calendar.getInstance();
  126. dob1.set(1990, 1, 1);
  127. System.out.println(String.format(
  128. "DOB 1:\t%s (difference:\t%d years)",
  129. dob1.getTime(),
  130. yearDifference(today, dob1)));
  131. Calendar dob2 = Calendar.getInstance();
  132. dob2.set(1994, 12, 22);
  133. System.out.println(String.format(
  134. "DOB 2:\t%s (difference:\t%d years)",
  135. dob2.getTime(),
  136. yearDifference(today, dob2)));
  137. }
  138. public static boolean isLeap(int year) {
  139. if (year % 4 != 0) {
  140. return false;
  141. } else {
  142. if (year % 100 == 0) {
  143. if (year % 400 == 0) {
  144. return true;
  145. } else {
  146. return false;
  147. }
  148. }
  149. return true;
  150. }
  151. }
  152. public static int monthLen(String month, int year) {
  153. if (month == "feb") {
  154. if (isLeap(year)) {
  155. return 29;
  156. } else {
  157. return 28;
  158. }
  159. } else if (
  160. (month == "apr") ||
  161. (month == "jun") ||
  162. (month == "sep") ||
  163. (month == "nov")) {
  164. return 30;
  165. } else {
  166. return 31;
  167. }
  168. }
  169. public static int yearDifference(Calendar date1, Calendar date2)
  170. {
  171. return (int) Math.abs(date1.get(Calendar.YEAR) -
  172. date2.get(Calendar.YEAR)
  173. );
  174. }
  175. }
  176. /**
  177. * Keyboard input
  178. */
  179. class Lab5 extends Lab {
  180. public Lab5() {
  181. super(5);
  182. new five1();
  183. }
  184. class five1 extends Exercise {
  185. /**
  186. * We will now look at how we can get user input from the keyboard. We will
  187. * gloss over some
  188. * of the details here, but give you just the information you need to start
  189. * getting input and
  190. * processing it.
  191. */
  192. public five1() {
  193. super(1);
  194. System.out.println(String.format("TBC"));
  195. // Scanner keyboard = new Scanner(System.in);
  196. // System.out.println("Please enter your name, followed by the return key?");
  197. // String userEntry = keyboard.nextLine();
  198. // System.out.println("Hello " + userEntry);
  199. // System.out.println(String.format("%s", keyboard));
  200. }
  201. }
  202. }
  203. /**
  204. * Loops
  205. */
  206. class Lab6 extends Lab {
  207. public Lab6() {
  208. super(6);
  209. new six1();
  210. System.out.println(String.format("%n"));
  211. new six3();
  212. new six5();
  213. new six6();
  214. new six7();
  215. new six8();
  216. new six9();
  217. }
  218. /**
  219. * Times tables
  220. */
  221. class six1 extends Exercise {
  222. public six1() {
  223. super(1);
  224. int testNum = 6;
  225. System.out.println(String.format("Times table for %d:", testNum));
  226. writeTimesTable(7);
  227. }
  228. }
  229. class six3 extends Exercise {
  230. public six3() {
  231. super(3);
  232. int testNum = 13; // statistically the most prime of all numbers
  233. System.out.println(String.format("Testing primes..."));
  234. System.out.println(String.format("%d prime? %s", testNum, isPrime(testNum)));
  235. System.out.println(String.format("%d prime? %s", 23, isPrime(23)));
  236. System.out.println(String.format("%d prime? %s", 27, isPrime(27)));
  237. System.out.println(String.format("%d prime? %s", 28, isPrime(28)));
  238. System.out.println(String.format("%d prime? %s", 299, isPrime(299)));
  239. System.out.println(String.format("Generating primes..."));
  240. generatePrimes(1024);
  241. System.out.println(String.format("Done!%n"));
  242. }
  243. }
  244. class six5 extends Exercise {
  245. public six5() {
  246. super(5);
  247. System.out.println(String.format("TODO / NOT IMPLEMENTED until we get stdin working"));
  248. }
  249. }
  250. /**
  251. * Produce a number triangle
  252. *
  253. * eg:
  254. * 1
  255. * 2 2
  256. * 3 3 3
  257. * 4 4 4 4
  258. */
  259. class six6 extends Exercise {
  260. public six6() {
  261. super(6);
  262. numberTriangle(1);
  263. numberTriangle(4);
  264. numberTriangle(8);
  265. numberTriangle(29);
  266. }
  267. }
  268. class six7 extends Exercise {
  269. public six7() {
  270. super(7);
  271. describeDD(4.2, 1.6);
  272. describeDD(47.42, 7.9);
  273. }
  274. /** Simple exposition of double division
  275. * @param num1 Dividend
  276. * @param num2 Divisor
  277. */
  278. public void describeDD(double num1, double num2) {
  279. System.out.println(String.format("Double division of %.2f by %.2f:\t", num1, num2));
  280. DoubleDivisionResult result = doubleDivision(num1, num2);
  281. System.out.println(String.format("Quotient: %d (ie %.2f ✕ %d = %.2f)\tRemainder: %.2f",
  282. result.getQuotient(),
  283. num2,
  284. result.getQuotient(),
  285. (num2 * result.getQuotient()),
  286. result.getRemainder()));
  287. }
  288. }
  289. /**
  290. * Exercise 8 - String pad with specified character
  291. */
  292. class six8 extends Exercise {
  293. public six8() {
  294. super(8);
  295. describeStringPadding("NoNeed", 4, '!');
  296. describeStringPadding("Simon", 10, '@');
  297. describeStringPadding("Zaphod Beeblebrox", 42, '?');
  298. // describeStringPadding("Unicode", 10, '🤯'); aww
  299. }
  300. /**
  301. * Print for display what we're padding and the result
  302. *
  303. * @param toPad The string to pad eg "Simon"
  304. * @param length Desired length
  305. * @param padChar Character to pad with
  306. */
  307. public void describeStringPadding(String toPad, int paddedLength, char padChar) {
  308. System.out.println(String.format("Padding '%s' to length %d using padding character: %s",
  309. toPad, paddedLength, padChar));
  310. System.out.println(stringLPad(toPad, paddedLength, padChar));
  311. }
  312. /**
  313. * (Left-)pad a string with the specific character
  314. *
  315. * @param toPad The string to pad eg "Simon"
  316. * @param length Desired length
  317. * @param padChar Character to pad with
  318. * @return The padded result
  319. */
  320. public static String stringLPad(String toPad, int paddedLength, char padChar) {
  321. // early out - return unmodified
  322. if (toPad.length() >= paddedLength) {
  323. return toPad;
  324. }
  325. // note that we could do this with String.repeat(), but since this is in the 'Loops'
  326. // part of the lab, we should probably do this with a loop
  327. // String paddedString = String.valueOf(padChar) + toPad;
  328. String paddedString = toPad;
  329. while (paddedString.length() < paddedLength) {
  330. paddedString = String.valueOf(padChar) + paddedString;
  331. }
  332. return paddedString;
  333. }
  334. }
  335. class six9 extends Exercise {
  336. private Random random = new Random(); // initialise once
  337. // see https://stackoverflow.com/a/35277291, to pick a random member of an enum, first convert it to an array
  338. private Throw[] throwsArray = Throw.values(); // can't call it 'throws' for obvious reasons
  339. final Throw randomThrow() {
  340. return throwsArray[random.nextInt(throwsArray.length)];
  341. }
  342. public six9() {
  343. super(9);
  344. System.out.println(String.format("TODO: Take input when we have stdin working"));
  345. Throw player1 = Throw.ROCK; // "Good ol' rock, nothing beats that"
  346. Throw player2 = randomThrow();
  347. playRockPaperScissors(player1, player2);
  348. player2 = randomThrow();
  349. playRockPaperScissors(player1, player2);
  350. player2 = randomThrow();
  351. playRockPaperScissors(player1, player2);
  352. }
  353. }
  354. public void playRockPaperScissors (Throw player1, Throw player2) {
  355. // slight semantic overload with throwing an error but I think that's the term
  356. // for plays in RPS
  357. String result;
  358. // early out - TOASK why this doesn't work when it works in a REPL!!
  359. if (player1 == player2) {
  360. result = "a draw";
  361. } else {
  362. switch (player1) {
  363. case ROCK:
  364. if (player2 == Throw.SCISSORS) { result = "R>S Player 1 wins"; }
  365. else { result = "R<P Player 2 wins"; } // must be paper
  366. break;
  367. case PAPER:
  368. if (player2 == Throw.SCISSORS) { result = "P<S Player 2 wins"; }
  369. else { result = "P>R Player 1 wins"; } // must be rock
  370. break;
  371. case SCISSORS:
  372. if (player2 == Throw.ROCK) { result = "S<R Player 2 wins"; }
  373. else { result = "S>P Player 1 wins"; } // must be paper
  374. break;
  375. default:
  376. result = "undefined behaviour";
  377. break;
  378. }
  379. }
  380. writeRPSPlay(player1, player2, result);
  381. }
  382. public String getThrowName(Throw thrown) {
  383. // This could probably be done in the enum itself
  384. switch (thrown) {
  385. case ROCK: return six8.stringLPad("rock", 8, ' '); // pad to 'scissors' length so everything stays lined-up
  386. case PAPER: return six8.stringLPad("paper", 8, ' ');
  387. case SCISSORS: return "scissors";
  388. default: return "uh?";
  389. }
  390. }
  391. public void writeRPSPlay (Throw player1, Throw player2, String result) {
  392. System.out.printf("Player 1 throws... %s\t\t", getThrowName(player1));
  393. System.out.printf("Player 2 throws... %s\t\t", getThrowName(player2));
  394. System.out.println(String.format("The result is...\t%s", result));
  395. }
  396. enum Throw {
  397. ROCK,
  398. PAPER,
  399. SCISSORS
  400. }
  401. /* TOASK - is there a better way of returning multiple values in Java?
  402. à la python, ie: return (quotient, remainder)
  403. */
  404. /**
  405. * Wrapper class for returning results from double division
  406. */
  407. final class DoubleDivisionResult {
  408. private int quotient; // that's the number of times something goes into something else
  409. private double remainder; // that's the bit left over
  410. public DoubleDivisionResult(int quotient, double remainder) {
  411. this.quotient = quotient;
  412. this.remainder = remainder;
  413. }
  414. public int getQuotient() {
  415. return quotient;
  416. }
  417. public double getRemainder() {
  418. return remainder;
  419. }
  420. }
  421. /**
  422. * Perform 'double division'
  423. *
  424. * @param dividend Number to be divided
  425. * @param divisor Number to divide by
  426. * @return a {@link DoubleDivisionResult} with the (int) quotient and (double) remainder
  427. */
  428. public DoubleDivisionResult doubleDivision(double dividend, double divisor) {
  429. // example used is 4.2 and 1.6
  430. // should return 2 and 1.0
  431. final boolean DEBUG = false;
  432. double dQuotient = dividend / divisor;
  433. int iQuotient = (int)dQuotient;
  434. double remainder = dividend - (iQuotient * divisor);
  435. if (DEBUG) {
  436. System.out.println(String.format("float quotient: %.2f", dQuotient));
  437. System.out.println(String.format("int quotient: %d", iQuotient));
  438. // TOASK: is there a neater way to do this casting?
  439. }
  440. return new DoubleDivisionResult(iQuotient, remainder);
  441. }
  442. /**
  443. * @param num Size of triangle
  444. */
  445. public void numberTriangle(int num) {
  446. /* Observations:
  447. - for even-sized triangles, preceding number of spaces starts at n=rows and decrements
  448. - for even-sized triangles even numbers have odd spaces and vice versa
  449. TODO: handle multi-digit numbers
  450. */
  451. System.out.println(String.format(""));
  452. int spaces = num;
  453. for (int i = 1; i <= num; i++) {
  454. System.out.println(" ".repeat(spaces)
  455. + String.format("%s ", i).repeat(i)
  456. + " ".repeat(spaces-1)
  457. );
  458. spaces--;
  459. }
  460. System.out.println(String.format(""));
  461. }
  462. /**
  463. * @param num The number to write the times table for
  464. * @param limit How many multiples to show
  465. */
  466. public void writeTimesTable(int num, int limit) {
  467. for (int i = 0; i < (limit + 1); i++) {
  468. System.out.printf("%d\t", num * i);
  469. }
  470. }
  471. /* TOASK - overload example.
  472. Question: is there a better way of doing optional function parameters in java?
  473. */
  474. /**
  475. * Write times table for num (10 entries)
  476. * @param num Number to show times table for
  477. */
  478. public void writeTimesTable(int num) {
  479. int DEFAULT_LIMIT = 10;
  480. writeTimesTable(num, DEFAULT_LIMIT);
  481. }
  482. public void generatePrimes(int upperLimit) {
  483. // handle 2 as a special case
  484. System.out.println(String.format("2"));
  485. // for (int i = 3; i <= upperLimit; i += 2) {
  486. for (int i = 2; i <= upperLimit; i++) {
  487. // TODO: figure out smarter way of doing this, I'm sure primes must be at least 6 apart...
  488. // Something about 2n ± 1 ?
  489. // seive of Erasthotenes ..?
  490. if (isPrime(i)) {
  491. System.out.printf("%d\t", i);
  492. }
  493. }
  494. }
  495. /**
  496. * But is it prime?
  497. * @param num Integer to test for primality
  498. * @return if it's prime
  499. */
  500. public boolean isPrime(int num) {
  501. boolean DEBUG = false;
  502. if ((num == 2) || (num == 1)) {
  503. return true;
  504. }
  505. if (num % 2 == 0){
  506. return false;
  507. } else {
  508. int divisor = 3;
  509. double numSquareRoot = Math.sqrt((double)num);
  510. while (divisor <= numSquareRoot) {
  511. if (num % divisor == 0) {
  512. return false;
  513. }
  514. divisor += 2;
  515. if (DEBUG) {
  516. System.out.printf("%d\t", divisor);
  517. }
  518. }
  519. return true;
  520. }
  521. }
  522. }
  523. /**
  524. * String formatting
  525. *
  526. */
  527. class Lab7 extends Lab {
  528. public Lab7() {
  529. super(7);
  530. writeTimesTable(8.24579, 10);
  531. writeTimesTable(93.12279, 22);
  532. writeTimesTable(193.12279, 22);
  533. writeTimesTable(13.9, 122);
  534. }
  535. /**
  536. * @param num The number to write the times table for (0 <= num <= 99)
  537. * @param limit How many multiples to show (0 <= limit <= 99)
  538. */
  539. public void writeTimesTable(double num, int limit) {
  540. final double MINNUM = 0;
  541. final double MAXNUM = 99;
  542. final int MINLIMIT = 0;
  543. final int MAXLIMIT = 99;
  544. if ((num < MINNUM) || (num > MAXNUM)) {
  545. System.err.println(String.format("Please specify a number between %.2f and %.2f (supplied: %.2f)",
  546. MINNUM, MAXNUM, num));
  547. return;
  548. }
  549. if ((limit < MINLIMIT) || (limit > MAXLIMIT)) {
  550. System.err.println(String.format("Please specify a limit between %d and %d (supplied: %d)",
  551. MINLIMIT, MAXLIMIT, limit));
  552. return;
  553. }
  554. for (int i = 0; i < (limit + 1); i++) {
  555. // output specification:
  556. // ~~.~~~ x ~~ = ~~~~~.~~~
  557. System.out.printf("%2.3f x %02d = %5.3f%n", num, i, (num*i));
  558. }
  559. }
  560. }