Exercises from labs 2023-2024
Não pode escolher mais do que 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.

week1.java 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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(1);
  256. numberTriangle(4);
  257. numberTriangle(8);
  258. numberTriangle(29);
  259. }
  260. }
  261. class six7 extends Section {
  262. public six7() {
  263. super(7);
  264. describeDD(4.2, 1.6);
  265. describeDD(47.42, 7.9);
  266. }
  267. /** Simple exposition of double division
  268. * @param num1 Dividend
  269. * @param num2 Divisor
  270. */
  271. public void describeDD(double num1, double num2) {
  272. System.out.println(String.format("Double division of %.2f by %.2f:\t", num1, num2));
  273. DoubleDivisionResult result = doubleDivision(num1, num2);
  274. System.out.println(String.format("Quotient: %d (ie %.2f ✕ %d = %.2f)\tRemainder: %.2f",
  275. result.getQuotient(),
  276. num2,
  277. result.getQuotient(),
  278. (num2 * result.getQuotient()),
  279. result.getRemainder()));
  280. }
  281. }
  282. /* TOASK - is there a better way of returning multiple values in Java?
  283. à la python, ie: return (quotient, remainder)
  284. */
  285. /**
  286. * Wrapper class for returning results from double division
  287. */
  288. final class DoubleDivisionResult {
  289. private int quotient; // that's the number of times something goes into something else
  290. private double remainder; // that's the bit left over
  291. public DoubleDivisionResult(int quotient, double remainder) {
  292. this.quotient = quotient;
  293. this.remainder = remainder;
  294. }
  295. public int getQuotient() {
  296. return quotient;
  297. }
  298. public double getRemainder() {
  299. return remainder;
  300. }
  301. }
  302. /**
  303. * Perform 'double division'
  304. *
  305. * @param dividend Number to be divided
  306. * @param divisor Number to divide by
  307. * @return a {@link DoubleDivisionResult} with the (int) quotient and (double) remainder
  308. */
  309. public DoubleDivisionResult doubleDivision(double dividend, double divisor) {
  310. // example used is 4.2 and 1.6
  311. // should return 2 and 1.0
  312. final boolean DEBUG = false;
  313. double dQuotient = dividend / divisor;
  314. int iQuotient = (int)dQuotient;
  315. double remainder = dividend - (iQuotient * divisor);
  316. if (DEBUG) {
  317. System.out.println(String.format("float quotient: %.2f", dQuotient));
  318. System.out.println(String.format("int quotient: %d", iQuotient));
  319. // TOASK: is there a neater way to do this casting?
  320. }
  321. return new DoubleDivisionResult(iQuotient, remainder);
  322. }
  323. /**
  324. * @param num Size of triangle
  325. */
  326. public void numberTriangle(int num) {
  327. /* Observations:
  328. - for even-sized triangles, preceding number of spaces starts at n=rows and decrements
  329. - for even-sized triangles even numbers have odd spaces and vice versa
  330. */
  331. System.out.println(String.format(""));
  332. int spaces = num;
  333. for (int i = 1; i <= num; i++) {
  334. System.out.println(" ".repeat(spaces)
  335. + String.format("%s ", i).repeat(i)
  336. + " ".repeat(spaces-1)
  337. );
  338. spaces--;
  339. }
  340. System.out.println(String.format(""));
  341. }
  342. /**
  343. * @param num The number to write the times table for
  344. * @param limit How many multiples to show
  345. */
  346. public void writeTimesTable(int num, int limit) {
  347. for (int i = 0; i < (limit + 1); i++) {
  348. System.out.printf("%d\t", num * i);
  349. }
  350. }
  351. /* TOASK - overload example.
  352. Question: is there a better way of doing optional function parameters in java?
  353. */
  354. /**
  355. * Write times table for num (10 entries)
  356. * @param num Number to show times table for
  357. */
  358. public void writeTimesTable(int num) {
  359. int DEFAULT_LIMIT = 10;
  360. writeTimesTable(num, DEFAULT_LIMIT);
  361. }
  362. public void generatePrimes(int upperLimit) {
  363. // handle 2 as a special case
  364. System.out.println(String.format("2"));
  365. // for (int i = 3; i <= upperLimit; i += 2) {
  366. for (int i = 2; i <= upperLimit; i++) {
  367. // TODO: figure out smarter way of doing this, I'm sure primes must be at least 6 apart...
  368. // Something about 2n ± 1 ?
  369. // seive of Erasthotenes ..?
  370. if (isPrime(i)) {
  371. System.out.printf("%d\t", i);
  372. }
  373. }
  374. }
  375. /**
  376. * But is it prime?
  377. * @param num Integer to test for primality
  378. * @return if it's prime
  379. */
  380. public boolean isPrime(int num) {
  381. boolean DEBUG = false;
  382. if ((num == 2) || (num == 1)) {
  383. return true;
  384. }
  385. if (num % 2 == 0){
  386. return false;
  387. } else {
  388. int divisor = 3;
  389. double numSquareRoot = Math.sqrt((double)num);
  390. while (divisor <= numSquareRoot) {
  391. if (num % divisor == 0) {
  392. return false;
  393. }
  394. divisor += 2;
  395. if (DEBUG) {
  396. System.out.printf("%d\t", divisor);
  397. }
  398. }
  399. return true;
  400. }
  401. }
  402. }