-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructTheRectangle.java
More file actions
68 lines (57 loc) · 2 KB
/
ConstructTheRectangle.java
File metadata and controls
68 lines (57 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class Solution {
public class Factor{
int first;
int second;
public Factor(int first, int second){
this.first = first;
this.second = second;
}
public String toString(){
return "("+first+","+second+")";
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Factor)) {
return false;
}
Factor factor = (Factor) o;
return first == factor.first &&
second == factor.second;
}
}
public int[] constructRectangle(int area) {
//Find all factors for the number represented by "area"
Set<Factor> factors = findFactors(area);
//For each factor pair apply first two rules given.
factors = factors.stream()
.filter(factor -> {return (factor.first >= factor.second);})
.collect(Collectors.toSet());
//To satisfy third rule, Collect the remainaing and find Optimal.
Factor optimalFactor = null;
int minDiff = Integer.MAX_VALUE;
for(Factor factor: factors){
int currentDiff = factor.first - factor.second;
if(minDiff > currentDiff){
minDiff = currentDiff;
optimalFactor = factor;
}
}
return new int[]{optimalFactor.first, optimalFactor.second};
}
public Set<Factor> findFactors(int n){
Set<Factor> factorList = new HashSet<>();
int sqrt = (int)Math.sqrt(n);
for(int i=1; i<=sqrt; i++){
if(n % i == 0){
factorList.add(new Factor(i, n/i));
factorList.add(new Factor(n/i, i));
}
}
return factorList;
}
}