0% found this document useful (0 votes)
212 views

Ron Dai Learn Java With Math Using Fun Projects and Games Apress 2020 3 PDF

Uploaded by

naarkota
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

Ron Dai Learn Java With Math Using Fun Projects and Games Apress 2020 3 PDF

Uploaded by

naarkota
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CHAPTER 31

IOU Computation
IOU means “Intersection Over Union.” It is used as a metric in image
detection technology. This metric computes a ratio of the overlap area
between two rectangles over their union area. For simplicity, the two
rectangles are in the same direction, as you will see R1 and R2 in Figure 31-­1.

Figure 31-1.  Two rectangles and their overlap

To figure out this ratio, we need to find out their overlap area named X.
If the areas for the two rectangles are R1.area and R2.area, then

IOU = X / (R1.area + R2.area – X)

We define the location of a rectangle by x_min, y_min, x_max, and


y_max. Its four vertices can be represented by the four coordinates: (x_min,
y_min), (x_min, y_max), (x_max, y_max), (x_max, y_min), started from the left
bottom vertex, going clockwise.
Let’s first find out under what circumstances there will be no overlap
area between R1 and R2, as shown in Figure 31-2.

© Ron Dai 2019 203


R. Dai, Learn Java with Math, https://doi.org/10.1007/978-1-4842-5209-3_31
Chapter 31 IOU Computation

Figure 31-2.  Two rectangles that are apart from each other

It will be when:

R1.x_max <= R2.x_min,      (1)

or R1.x_min >= R2.x_max, (2)

or R1.y_max <= R2.y_min, (3)

or R1.y_min >= R2.y_max  (4)

If one of the conditions from (1) to (4) is valid, the overlap area is 0.
Next, we notice that the overlap area is actually surrounded by four
lines, as shown in Figure 31-3.

x = max(R1.x_min, R2.x_min), x = min(R1.x_max,


R2.x_max)

y = max(R1.y_min, R2.y_min), y = min(R1.y_max,


R2.y_max)

Figure 31-3.  Two rectangles and their overlap areas

204
Chapter 31 IOU Computation

According to the mathematical inferences, we can come up with a


coding design solution as shown:
There are two classes, Rectangle and IntersectionOverUnion.
The Rectangle class defines a data model for a rectangle on an x-y
coordinate system.

public class Rectangle {


       public float x_min;
       public float x_max;
       public float y_min;
       public float y_max;

       public Rectangle(float xmin, float ymin, float xmax,


float ymax) {
              if (xmin >= xmax || ymin >= ymax) {
throw new IllegalArgumentException("Not a valid rectangle!");
              }
              this.x_min = xmin;
              this.y_min = ymin;
              this.x_max = xmax;
              this.y_max = ymax;
       }

       public float getWidth() {


              return this.x_max - this.x_min;
       }
       public float getHeight() {
              return this.y_max - this.y_min;
       }
}

205
Chapter 31 IOU Computation

The IntersectionOverUnion class contains the main() method, which


drives the execution.

public class IntersectionOverUnion {


       public static void main(String[] args) {
              // test case 1
              Rectangle r1 = new Rectangle(3f, 2f, 5f, 7f);
              Rectangle r2 = new Rectangle(4f, 1f, 6f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));

              // test case 2


              r1 = new Rectangle(3f, 2f, 5f, 7f);
              r2 = new Rectangle(1f, 1f, 6f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));

              // test case 3


              r1 = new Rectangle(3f, 2f, 5f, 7f);
              r2 = new Rectangle(6f, 1f, 7f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));
       }

       public static float getIOU(Rectangle r1, Rectangle r2) {


              float areaR1 = r1.getHeight() * r1.getWidth();
              float areaR2 = r2.getHeight() * r2.getWidth();
              float overlapArea = 0f;
              if (r1.x_min >= r2.x_max || r1.x_max <= r2.x_min ||
                     r1.y_min >= r2.y_max || r1.y_max <= r2.y_
min) {
                     return 0f;
              }
              overlapArea = computeOverlap(
                                   Math.max(r1.x_min, r2.x_min),
                                   Math.min(r1.x_max, r2.x_max),

206
Chapter 31 IOU Computation

                                   Math.max(r1.y_min, ­
r2.y_min),
                                   
Math.min(r1.y_max, r2.y_
max));
              System.out.println(overlapArea + " / (" + areaR1
                            
+ " + " + areaR2 + " - " +
overlapArea + ")");
              
return overlapArea / (areaR1 + areaR2 -
overlapArea);
       }

       private static float computeOverlap(


                                   float x1,
                                   float x2,
                                   float y1,
                                   float y2) {
              float w = x2 - x1;
              if (w < 0) w = -w;
              float h = y2 - y1;
              if (h < 0) h = -h;
              return w * h;
       }
}

We are not done yet. We need to always think about how to improve
our class design and optimize code. In the Rectangle class, there are
getWidth() and getHeight() methods. What if we add a method called
getArea() to the Rectangle class?
The Rectangle class is updated as:

public class Rectangle {


       public float x_min;
       public float x_max;
       public float y_min;
       public float y_max;
207
Chapter 31 IOU Computation

       public Rectangle(float xmin, float ymin, float xmax,


float ymax) {
              if (xmin >= xmax || ymin >= ymax) {
throw new IllegalArgumentException("Not a valid rectangle!");
              }
              this.x_min = xmin;
              this.y_min = ymin;
              this.x_max = xmax;
              this.y_max = ymax;
       }

       public float getWidth() {


              return this.x_max - this.x_min;
       }
       public float getHeight() {
              return this.y_max - this.y_min;
       }
       public float getArea() {
              return this.getWidth() * this.getHeight();
       }
}

And the rest of the code will look like:

import java.lang.Math;
public class IntersectionOverUnion {
       public static void main(String[] args) {
              // test case 1
              Rectangle r1 = new Rectangle(3f, 2f, 5f, 7f);
              Rectangle r2 = new Rectangle(4f, 1f, 6f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));

              // test case 2

208
Chapter 31 IOU Computation

              r1 = new Rectangle(3f, 2f, 5f, 7f);


              r2 = new Rectangle(1f, 1f, 6f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));

              // test case 3


              r1 = new Rectangle(3f, 2f, 5f, 7f);
              r2 = new Rectangle(6f, 1f, 7f, 8f);
              System.out.println("IOU=" + getIOU(r1, r2));
       }

       public static float getIOU(Rectangle r1, Rectangle r2) {


              float areaR1 = r1.getArea();
              float areaR2 = r2.getArea();
              float overlapArea = 0f;
              if (r1.x_min >= r2.x_max || r1.x_max <= r2.x_min ||
                     
r1.y_min >= r2.y_max || r1.y_max <= r2.y_
min) {
                     return 0f;
              }
              overlapArea = computeOverlap(
                                   Math.max(r1.x_min, r2.x_min),
                                   Math.min(r1.x_max, r2.x_max),
                                   Math.max(r1.y_min, r2.y_min),
                                   Math.min(r1.y_max, r2.y_
max));
              System.out.println(overlapArea + " / (" + areaR1
                            
+ " + " + areaR2 + " - " +
overlapArea + ")");
              
return overlapArea / (areaR1 + areaR2 -
overlapArea);
       }

209
Chapter 31 IOU Computation

       private static float computeOverlap(


                                   float x1,
                                   float x2,
                                   float y1,
                                   float y2) {
              float w = x2 - x1;
              if (w < 0) w = -w;
              float h = y2 - y1;
              if (h < 0) h = -h;
              return w * h;
       }
}

The computation of area is now encapsulated inside the Rectangle


class. This change itself is not big, but we should get used to making small
changes at a time when we are still able to incrementally improve our
program design.

210
CHAPTER 32

Projects
I want to recommend a list of hands-on projects for you to practice
independently. Working through these projects will definitely help you
deepen your understanding of the basic Java programming concepts
described in this book.

P
 roject A
S
 tep 1
Write a class called Rectangle that represents a rectangular two-­
dimensional region. The constructor creates a new rectangle whose top-­
left corner is specified by the given coordinates and with the given width
and height.

public Rectangle(int x, int y, int width, int height)

Your Rectangle objects should have the following methods:

• public int getHeight() - Returns this rectangle’s


height.

• public int getWidth() - Returns this rectangle’s


width.

• public int getX() - Returns this rectangle’s


x-coordinate.

© Ron Dai 2019 211


R. Dai, Learn Java with Math, https://doi.org/10.1007/978-1-4842-5209-3_32
Chapter 32 Projects

• public int getY() - Returns this rectangle’s


y-coordinate.

• public String toString() - Returns a string


representation of this rectangle, such as:

"Rectangle[x=1,y=2,width=3,height=4]"

Step 2
Add the following accessor methods to your Rectangle class from the
previous exercises:

public boolean contains(int x, int y)


public boolean contains(Point p)

The Point class has been defined as shown:

public class Point {


       private int x;
       private int y;

       public Point(int x, int y) {


              this.x = x;
              this.y = y;
       }
       public int getX() {
              return x;
       }
       public int getY() {
              return y;
       }
}

212
Chapter 32 Projects

The two contains() methods return a Boolean state of whether the


given Point or coordinates lie inside the bounds of this Rectangle or not.
For example, a rectangle with [x=2, y=5, width=8, height=10] will return
true for any point from (2, 5) through (10, 15) inclusive, which means the
edges are included.

Project B
Design a program to find the number of days between the current day and
the user’s birthday, given four input values.
The program prompts for the user’s birthday. The prompt lists the
range of values from which to choose. Notice that the range of days printed
is based upon the number of days in the month the user typed. The
program prints the absolute day of the year for the birthday. January 1st is
absolute day #1 and December 31st is absolute day #365. Last, the program
prints the number of days until the user’s next birthday. Different messages
appear if the birthday is today or tomorrow. The following are four runs of
your program and their expected output (user input data is right after the
‘?’ mark):

Please enter your birthday:


What is the month (1-12)? 11
What is the day (1-30)? 6
11/6 is day #310 of 365.

Your next birthday is in 105 days, counted from today.

Project C
The game rule is this: you start with 21 sticks, and two players take turns
either taking one or two sticks. The player who takes the last stick loses.
Can you design a program to simulate one of the two players in the game?
One player is a user and the other player is the computer.

213
Chapter 32 Projects

Project D
Write a method named hasVowel() that returns whether a string has
included any vowel (a single-letter string containing a, e, i, o, or u, case-­
insensitively).

Project E
Write a method named gcd() that accepts two integers as parameters and
returns the greatest common divisor (GCD) of the two numbers. The GCD
of two integers a and b is the largest integer that is a factor of both a and b.
The GCD of any number and 1 is 1, and the GCD of any number and 0 is
the number.
One efficient way to compute the GCD of two numbers is to use
Euclid’s algorithm, which states the following:
GCD(A, B) = GCD(B, A % B)
GCD(A, 0) = Absolute value of A
For example:

• gcd(24, 84) returns 12

• gcd(105, 45) returns 15

• gcd(0, 8) returns 8

Project F
Write a method named toBinary() that accepts an integer as a parameter
and returns a string of that number’s representation in binary. For
example, the call of toBinary(42) should return “101010”.

214
Chapter 32 Projects

Project G
Use the four numbers on the following cards to create a math expression
that equals 24. Each card can be used only once. Treat ace as a number
“1”. You may use +, -, *, /, ( and ) in the math expression. Please find all
possible answers.

215
CHAPTER 33

Java Intermediate
Solutions
For your reference, in this chapter I’ll provide you with answer hints to
some of the problems in the earlier chapters. For example, “For 16.” means
“Hints for problems in Chapter 16.”

For 16. Pythagorean Triples


1. Instead of using “c,” we may check whether (a2 + b2)
is a perfect square number, which is taking a square
root of it and validating if it is an integer value.

2. Use the example code and check whether the


resulting value of (a2 + b2) matches the form
of “4n + 1”.

For 17. Strong Typed Programming


       public boolean isCollinear(Point p) {
              if (p.getX() == p1.getX() && p1.getX() ==
p2.getX()) {
                     return true;
              }
© Ron Dai 2019 217
R. Dai, Learn Java with Math, https://doi.org/10.1007/978-1-4842-5209-3_33
Chapter 33 Java Intermediate Solutions

              if (this.getSlope(p) == this.getSlope()) {


                     return true;
              }
              return false;
       }

public double getSlope(Point p) {


       if (this.p1.x == this.p.x) {
              throw new
IllegalStateException("Denominator cannot be 0");
       }
       return (double)(this.p.y - this.p1.y) / (this.p.x -
this.p1.x);
}

For 18. Conditional Statements


1. It is rewritten as shown here.

       if (num < 10 && num > 0) {


              System.out.println("It's a one-digit
number");
       }
       else if (num < 100) {
              System.out.println("It's a two-digit
number");
       }
       else if (num < 1000) {
              System.out.println("It's a three-digit
number");
       }

218
Chapter 33 Java Intermediate Solutions

       else if (num < 10000) {


              System.out.println("It's a four-digit
number");
       }
       else {
              System.out.println("The number is not
between 1 & 9999");
       }

2. A simplified version is shown here.

if (a == 0) {
       if (b == 0) {...}
       else {...}
} else {
       if (b != 0) {...}
}

For 19. Switch Statement


switch(color) {
       case 'R':
              System.out.println("The color is red");
              break;
       case 'G':
              System.out.println("The color is green");
              break;
       case 'B':
              System.out.println("The color is black");
              break;

219
Chapter 33 Java Intermediate Solutions

       case 'C':
       default:
              System.out.println("Some other color");
              break;
}

For 21. Counting


1. Define x as the number of children and (2200 – x)
is the number of adults, then 1.5 ∗ x + 4 ∗ (2200 – x)
= 5,050. Iterate x = 0 up to 2200 to find a solution for x.
And it is obvious that there is no more than one
solution.

2. Define x as the number of correct answers and


(10 – x) as the number of incorrect answers, then
5 ∗ x – 2 (10 – x) = 29. Iterate x from 0 up to 10 to find
a possible solution for x.

3. Iterate a positive integer from 0 to 2001 and check its


divisibility with 3, 4, and 5.

4. Iterate every three-digit integer number, from 100


up to 999, and check its digits.

5. Use a recursive method (referring to the example)


to repeatedly pick a plant five times from the three
types of plants (defining three types as A, B, C).
And then remove duplicates from the combinations.
For example: {A, A, B, B, C} is a duplicate of {A, B, A,
B, C}.

220
Chapter 33 Java Intermediate Solutions

For 23. Exploratory Experimentation of Pi


Utilize the following formula with integer number “r” and approximate the
value of “e.”

1 1 1 1
e =1+ + + +¼
1! 2 ! 3 ! r!

F or 24. Classes in Object-Oriented


Programming
1. a)

2. b)

3.

         NumberHolder nh = new NumberHolder();


         Nh.anInt = 5;
         Nh.aFloat = 3.2;
         System.out.printIn("anInt=" + Nh.anInt + "; aFloat=" +
Nh.aFloat);

4. (A), (D)

5. (B)

For 26. Inheritance – Code Reuse


1. (c)

2. (b), (d), (e), (f )

221
Chapter 33 Java Intermediate Solutions

For 27. Encapsulation and Polymorphism


1.

public interface GeometricObject {


public abstract double getPerimeter();
       public abstract double getArea();
}

2.

       public class Circle implements GeometricObject {


       private final double PI = 3.14159;
       protected double radius;
       public Circle(double radius) {
              this.radius = radius;
       }

       // Implement methods defined in the interface


       @Override
       public double getPerimeter() {
       return 2 * PI * this.radius;
       }

       @Override
       public double getArea() {
              return PI * this.radius * this.radius;
       }
}

222
Chapter 33 Java Intermediate Solutions

F or 28. Array – a Simple and Efficient Data


Structure
1. (d)

2. { 0, 4, 0, 0, 11, 0, 0, 2 }

For 29. Common Pitfalls


1. If you want to get an integer value, why not take an
integer input at the beginning?

This is a corrected version. It is significantly


simplified.

Scanner user_input = new Scanner(System.in);


System.out.println("a=");
int a = user_input.nextInt();
System.out.println("b=");
int b = user_input.nextInt();

2. Does myArray[3] equal “13”?

Pay attention to the definition of the index of an


array element.

3. Is it necessary to check stringsArray.length


= 0? And, is it a good approach to do countMe.
toLowerCase() inside the for-loop?

223
Chapter 33 Java Intermediate Solutions

This is a recommended version:

public static int CountStrings(String[] stringsArray,


String countMe) {
       int occurences = 0;
       String keyword = countMe.toLowerCase();
       for (int i = 0; i < stringsArray.length; i ++) {
              
if (stringsArray[i].toLowerCase().
contains(keyword)) {
                     occurences ++;
              }
       }
       return occurences;
}

4. Has the myRect ever been initialized?

There is an important line to update in the main()


method as shown here:

public class SomethingIsWrong {


       public static void main(String[] args) {
               Rectangle myRect = new Rectangle();
               myRect.width = 40;
               myRect.height = 50;
               
System.out.println("myRect's area is
" + myRect.area());
       }
}

224
Chapter 33 Java Intermediate Solutions

5. Since the variable temp has been assigned with the


value of the first element in array1, do we need to
iterate from i=0 inside the for-loop?

The simple fix is to change from for (int i = 0;


... to for (int = 1; ... in the original function
as shown.

public static int getMaxLength(ArrayList<String>


array1)  {
       if(array1.isEmpty()) {
              return 0;
       }
       else {
              String temp= array1.get(0);
              for (int i = 1; i < array1.size(); i++) {
                     if (array1.get(i).length() >
temp.length() ) {
                            temp= array1.get(i);
                     }
              }
              return temp.length();
       }
}

6. Check the if/else clause.

The scope of “y > 31 && z > 12” is already covered


by the scope of “z > 12 || y > 31”. Therefore,
the “else if (...)” part in the original code is
meaningless.

225
Chapter 33 Java Intermediate Solutions

7. Review the actual usage of the Scanner.

Due to the same reason stated in 1, the code can be


corrected as shown:

System.out.println("What month were you born in?


(1-12)");
Scanner sc = new Scanner(System.in);
int al = sc.nextInt();

8. Check the if/else clause

The scope of numToTake > 2 has included the scope


of numToTake >= 2 && numToTake < 3. The if and
else if conditional clauses need to be rewritten.

226
Index
A Collatz conjecture
defining, 5
Abstraction, 171, 182
program, 5, 6
Algorithms
Collinearity, 107
creation, real-world
Conditional operators, 64–67
objects, 39, 40
Conditional statements, 218, 219
swap values, 40–41
bigger number identification, 109
Array, 223
example, 111, 114
character, 185
if clauses, 112
data types, 185
if/else if structure, 110
defined, 185
if/else structure, 109, 110
element values, 186
nested if/else structure, 110
index, 185
quadrants, 114, 115
size, 186
tree-like structure, 111
contains() method, 213
B convertToBaseN() method, 144
Basic projects, 85–87 countBase10Numbers() method, 143
Counting, 220
countNumbers2(), 136
C for-loop, 137, 139, 140
class instantiation, 29 isDistinct(…), 135
Class variables/instance single loop, 131
variables, 33 switch statement, 145
Coding mistakes, 73, 74 tables, 132
Coding structure, 81 tickets, 131
Coin flip game, 93, 94, 96 Curly braces, 82

© Ron Dai 2019 227


R. Dai, Learn Java with Math, https://doi.org/10.1007/978-1-4842-5209-3
INDEX

D example, 53
exp() method, 54
Design considerations
list of numbers, 53
Demo class, 199
structure, 49
Game class, 195, 196
main() method, 199
MyClass class, 197, 198 G
Rectangle class, 193–195
gcd() method, 214
static fields, 199
General rules
test class, 200
conditional operation, 80, 81
double getSlope() method, 105
input in console, 80
do-while loop, 60–61
output in console, 79
repeat an operation, 80
E variable name, 79
getSlope() method, 106
Encapsulation, 181, 182, 222
Getters method, 163
Error correction, 77, 78
Greatest common divisor (GCD), 214
Exception handling, 76–77

F H
hasVowel() method, 214
Factorization
Hexadecimal–base 16 number
definition, 147
system, 15
finding factors, 147, 148
iterations, 149
square root, 150–153 I
Fields, 163 if/else structure, 64, 109, 120
for loop if structure, 63
arithmetic sequence, 51 Inheritance, 221
counting strategy, 51, 52 Car class, 177
example, 49, 50 Driver class, 178
formula, 50, 51 isFourWheelDrive() method, 177
list of numbers, 54 Sedan class, 177, 178
Math Input, read user data, 44

228
INDEX

Integer to month name, example methods, 29


if/else ladder, 120, 121 eclipse launched, 26
switch conditional main(), 30
statement, 121, 122 public static void main
Interface (String[] args), 30
Auto, 171 running application, 29
Car class, 172 Java Runtime Environment
circumstances, 173 (JRE), 24, 25
definition, 171 Java virtual machine (JVM), 20, 30
design, 173
MovingObject, 174
Intersection over union (IOU) L
getHeight() method, 207, 208 Local variables, 33
getWidth() method, 207, 208 Logical operators
IntersectionOverUnion operations, 67, 68
class, 206, 207 quadrant method, 70
Rectangle class, 205, 207–210 Venn diagram, 69
rectangles, 203, 204
isPalindrome() method, 142, 143
isPalindrome2() method, 143
M
main() method, 30
Math expression, 215
J, K
Java bytecode, 20–22
Java Development Kit (JDK), 24 N
Java, features Number
class, 20 binary to numeral system, 15
bytecode, 20–22 bit, 17
object oriented, 19 bitwise, 17, 18
Java program decimal to binary, 11–14
class, 29 hexadecimal–base 16 number
vs. class file, 31 system, 15
creation octal–base 8 number system, 16
java class, 28 Numeral systems, 9, 10

229
INDEX

O algorithm, 157
Calculus, 161
Object-Oriented programming, 221
for-loop, 159
access modifiers, 164
Java programming, 161
Account class, 169
long value type, 159, 160
characteristics, 163–165
main method(), 158
class vs. object, 166, 167
Math.random() method, 158
field vs. parameter, 169
population
Game class, 168
calculation, 155, 156
Name class, 166
Pitfalls, 189–191, 223–226
non-fields, 166
Point class, 106, 212
NumberHolder class, 168
Polymorphism, 183, 222
Point class, 167
Primitive types, 35–36
public int getAge() method, 164
Programming tips, 75, 76
public Student() method, 164
Properties, 163
structural view, 165
Pythagorean
public String getFirstName()
primes, 101
method, 164
triples, 97–101, 217
public String getLastName()
method, 164
public void setAge(int age) R
method, 164
Rectangle class, 211, 212
Vehicle class, 166
Reference types, 36
Octal–base 8 number system, 16
reverse() method, 142
Output
System.out.println, 44, 45
example, 45 S
problems, 47 Scanner utility class, 43
special characters, 44 Setters method, 163
Slope of a line, 105, 106
P, Q Source, 25
Package, 25 Stick game, 213
Pi experimentation, 221 StringBuffer class, 142

230
INDEX

Switch Statement, 219 V


days in month
Variables
example, 123, 124
assign value, 37
integer to month name
data types, 36, 37
example, 121, 122
definition, 33
structure, 119
name
System.out.println, 44
defining, 34
example, 34, 35
T primitive types, 35
Ternary operator, 116 reference types, 36
toBinary() method, 214 resulting value, 37, 38
Tracing moving objects types, 33
bouncing ball, 127, 128 Venn diagram, 69
snail example, 129, 130
Type casting, 103–105
W, X, Y, Z
While loop
U example, 58, 59
User’s birthday prediction structure, 57
program, 213 Workspace, 24, 25

231

You might also like