Z OLD Homework 01 - james-bern/CS136 GitHub Wiki
- introduce 2 program structures (straight-shot-through-main/script and loop/game)
- introduce Cow.java
Play with this simple number system converter app
- Your whole life* you have been writing numbers in decimal aka base-10.
- When I type Java code
int a = 123, I am expressing the right hand side in decimal.-
123means...$1 * 100 + 2 * 10 + 3 * 1$ -
$1 * 10^2 + 2 * 10^1 + 3 * 10^0$ - Note that
$10$ is the base of the factors$10^2$ ,$10^1$ , and$10^0$ . Hence, base-10. - (Recall that a non-negative number raised to the zeroth power equals one.)
- Note that
-
- Internally, computers represent integers in binary aka base-2.
-
123could be written as1111011in binary.- To avoid confusion with decimal, a prefix like
0bis typically added, _i.e., we might actually write0b1111011. -
1111011in binary means...$1 * 64 + 1 * 32 + 1 * 16 + 1 * 8 + 0 * 4 + 1 * 2 + 1 * 1$ $1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 0 * 2^2 + 1 * 2 ^ 1 + 1 * 2 ^ 0$
- To avoid confusion with decimal, a prefix like
-
Hexadecimal aka base-16 is often used to represent colors, e.g.,
#FF00FFis magenta.- the digits
$0, ..., 9$ have the same meaning as in base-10, and$A, ..., F$ correspond to the numbers$10, ..., 15$ -
123could be written as7Bin binary.- A prefix like
0xor#is typically added, _i.e., we might actually write0x7B. -
7Bin hex means...$7 * 16 + 11 * 1$ $7 * 16^1 + 11 * 16^0$
- A prefix like
- the digits
- *There may be times in your life where you used systems other than base-10. E.g., tally marks are base-1 aka unary.
- Unless we're dealing with bitwise operators, we can actually ignore the detail that the computer internally stores integers in binary. Here are three ways of doing the exact same thing:
-
int a = 123;tells the computer "Store the number with decimal representation$123$ in integera." -
int a = 0b1111011;tells the computer "Store the number with binary representation$1111011$ in integera."- Note: The DrJava Interactions pane doesn't support this, but our compiler does. 🙂👍
-
int a = 0x7B;tells the computer "Store the number with hexadecimal representation$7B$ in integera."
-
- Here is how to find the digits of some
int ain base-N.- Algorithm
- Imagine expressing
$a = \cdots + d_2 N^2 + d_1 N^1 + d_0 N^0$ .- Our goal is to find
$\cdots, d_2, d_1, d_0$ .
- Our goal is to find
- The remainder
a % Nreturns$d_0$ . - Dividing
a / Nwill eliminate the last term (d_0 / Nis less than$1$ and Java truncates when dividingint's), returning$\cdots + d_2 N^1 + d_1 N^0$ . - We can repeat this process, extracting one digit at a time, until the result of
a / Nis zero and we are done.
- Imagine expressing
- Example
- Let's find the digits of
123in base-2 (you can follow along in the DrJavaInteractionspane!)-
123 % 2returns1$\to$ // ...1 -
123 / 2returns61 -
61 % 2returns1$\to$ // ...11 -
61 / 2returns30 -
30 % 2returns0$\to$ // ...011 -
30 / 2returns15 -
15 % 2returns1$\to$ // ...1011 -
15 / 2returns7 -
7 % 2returns1$\to$ // ...11011 -
7 / 2returns3 -
3 % 2returns1$\to$ // ...111011 -
3 / 2returns1 -
1 % 2returns1$\to$ // 1111011 -
1 / 2returns0
-
- Let's find the digits of
- Algorithm
static void printStringOneCharacterAtATimeForNoReason(String string) {
for (int i = 0; i < string.length(); ++i) {
char c = string.charAt(i);
System.out.print(c);
}
System.out.println();
}static int numDigits(int n) {
assert n >= 0;
int result = 0;
while (n > 0) {
++result;
n /= 10;
}
return result;
}-
To get an A:
- Implement all functions.
- 🚨 Note: All problems should be solved using techniques like the ones we talked about in the class and on the homework. I.e., magical Java one-liners like
Integer.toBinaryString(int decimal)will typically not score points (even if the autograder is happy). If in any doubt, ask! - You aren't allowed to modify
grade()of the comment that it generates, but you can (and should!) write your own tests directly inmain.
-
To get an S:
- Do everything above.
- Make a Project Euler account, and solve https://projecteuler.net/problem=14 (actually submit it on Project Euler). Once you are successful, include a the answer in a comment at the top of your code file. Note: If you have already done this problem, do any other problem instead.
- 🚨 Hint: Use a
longto store the$n$ instead of anint. Anintdoes not have enough bits to store numbers as large as you will encounter!
- 🚨 Hint: Use a
-
Run
grade()(you can do this whenever you want, as many times as you want), copy the comment it generates, and paste the comment at the top of your code file.- 🚨 You must do this in order to receive points.
- Upload your code file to GradeScope by the due date.
If you hover your mouse over the code box below, a little button will appear in the upper-right corner that you can click to copy the code. Wow!
import java.util.*;
class HW01 {
// returns the length of the hypotenuse of right triangle with legs of lengths a and b
static double pythagoreanTheorem(double a, double b) {
return 0.0;
}
// returns whether n is prime
static boolean isPrime(int n) {
return false;
}
// returns the sum of n's (base-10) digits
// NOTE: don't use recursion
static int digitSum(int n) {
int result = 0;
return result;
}
// returns the sum of hex's (base-16) digits
// NOTE: Hexadecimal works like this 0, ..., 9, A, ..., F
// A is 10, B is 11, ..., F is 15.
// NOTE: do NOT have separate cases for 'A', 'B', 'C', 'D', 'E', and, 'F'
// instead, have only three cases:
// - digit (character) in range ['0', '9']
// - digit (character) in range ['A', 'F']
// - any other digit (crash with an assert false;)
// NOTE: should crash using an assert false; if hex is not a valid hex number
// NOTE: don't use recursion
static int hexDigitSum(String hex) {
int result = 0;
return result;
}
// returns a String representation of n in the following bigendian notation
// 0 -> "0"
// 1 -> "1"
// 2 -> "10"
// 3 -> "11"
// 4 -> "100"
// ...
// NOTE: should crash using an assert if n is negative
// NOTE: don't use recursion
// NOTE: sample solution is ~6 lines
static String getInBinary(int n) {
String result = "";
return result;
}
public static void main(String[] arguments) {
grade();
// System.out.println(pythagoreanTheorem(3.0, 4.0));
}
// Runs some basic tests and estimates your grade.
static void grade() {
GRADER_BEGIN_PROBLEM("pythagoreanTheorem");
try { GRADER_ASSERT(_areApproximatelyEqual(pythagoreanTheorem(3.0, 4.0), 5.0)); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(_areApproximatelyEqual(pythagoreanTheorem(1.0, 1.0), Math.sqrt(2))); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
GRADER_BEGIN_PROBLEM("isPrime");
try { GRADER_ASSERT(isPrime(-3) == false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(0) == false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(1) == false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(2) == true); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(7) == true); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(37) == true); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(isPrime(55) == false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
GRADER_BEGIN_PROBLEM("digitSum");
try { GRADER_ASSERT(digitSum(0) == 0); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(digitSum(22) == 4); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(digitSum(123) == 6); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(digitSum(7770) == 21); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
GRADER_BEGIN_PROBLEM("hexDigitSum");
try { GRADER_ASSERT(hexDigitSum("") == 0); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(hexDigitSum("22") == 4); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(hexDigitSum("F1") == 16); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(hexDigitSum("AB23") == 26); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { try { hexDigitSum("XXX"); GRADER_ASSERT(false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); } } catch (Error error) { _GRADER_HANDLE_ERROR(); }
GRADER_BEGIN_PROBLEM("getInBinary");
try { try { getInBinary(-1); GRADER_ASSERT(false); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); } } catch (Error error) { _GRADER_HANDLE_ERROR(); }
try { GRADER_ASSERT(getInBinary(0).equals( "0")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(getInBinary(1).equals( "1")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(getInBinary(2).equals( "10")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(getInBinary(3).equals( "11")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(getInBinary(4).equals("100")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
try { GRADER_ASSERT(getInBinary(25743).equals("110010010001111")); } catch (Exception exception) { GRADER_HANDLE_EXCEPTION(); }
GRADER_FINISH_GRADING();
}
static boolean _areApproximatelyEqual(double a, double b) {
return Math.abs(a - b) < 1.0e-5;
}
// Feel free to ignore everything below this comment. //////////////////////
static private boolean graderReset = true;
static private int graderCurrentProblemIndex;
static private String gradeCurrentProblemName;
static private boolean graderProblemCurrentlyPassing;
static private int gradeNumProblemsPassed;
static private ArrayList<String> graderPassedProblemNames;
static private ArrayList<String> graderFailedProblemNames;
static private void _GRADER_END_PROBLEM() {
System.out.println();
if (graderProblemCurrentlyPassing) {
++gradeNumProblemsPassed;
graderPassedProblemNames.add(gradeCurrentProblemName);
} else {
graderFailedProblemNames.add(gradeCurrentProblemName);
}
}
static private void GRADER_BEGIN_PROBLEM(String questionName) {
if (graderReset) {
graderReset = false;
graderCurrentProblemIndex = 0;
graderProblemCurrentlyPassing = false;
gradeNumProblemsPassed = 0;
gradeCurrentProblemName = null;
graderPassedProblemNames = new ArrayList<>();
graderFailedProblemNames = new ArrayList<>();
System.out.println("/**");
System.out.println(" * grade()");
System.out.println(" * + means test passed (function produced correct result OR tripped assert)");
System.out.println(" * - means test failed (function produced incorrect result OF failed to trip assert)");
System.out.println(" * x means function crashed (in a way that it wasn't supposed to)");
System.out.println(" * NOTE: grader assumes you have asserts enabled (using DrJava or passed -ea)");
System.out.println(" *");
} else {
_GRADER_END_PROBLEM();
}
gradeCurrentProblemName = questionName;
++graderCurrentProblemIndex;
graderProblemCurrentlyPassing = true;
System.out.print(" * " + questionName + " ");
}
static private void GRADER_ASSERT(boolean shouldBeTrue) {
System.out.print((shouldBeTrue == true) ? '+' : '-');
graderProblemCurrentlyPassing &= shouldBeTrue;
}
static private void GRADER_HANDLE_EXCEPTION() {
System.out.print('x');
graderProblemCurrentlyPassing = false;
}
static private void _GRADER_HANDLE_ERROR() {
System.out.print('+');
}
static private void GRADER_FINISH_GRADING() {
if (graderCurrentProblemIndex != 0) { _GRADER_END_PROBLEM(); }
int numProblems = graderCurrentProblemIndex;
int numProblemsIncorrect = numProblems - gradeNumProblemsPassed;
char grade = 'C'; {
if (numProblemsIncorrect == 0) {
grade = 'A';
} else if (numProblemsIncorrect == 1) {
grade = 'B';
}
}
System.out.println(" * ");
System.out.println(" * Passed all tests " + graderPassedProblemNames);
System.out.println(" * Failed some test " + graderFailedProblemNames);
System.out.println(" * ");
System.out.println(" * Grade ~ " + grade);
System.out.println(" **/");
graderReset = true;
}
}