4개의 직사각형이 평면에 있는데 밑변이 모두 가로축에 평행하다. 이 직사각형들이 차지하는 면적을 구하는 프로그램을 작성하시오. 이 네 개의 직사각형들은 서로 떨어져 있을 수도 있고 겹쳐 있을 수도 있다. 또한 하나가 다른 하나를 포함할 수도 있으며, 변이나 꼭지점이 겹쳐질 수도 있다.
입력형식
하나의 직사각형은 왼쪽 아래의 꼭지점과 오른쪽 위의 꼭지점의 좌표로 주어진다. 입력은 네 줄이며, 각 줄은 네 개의 정수로 하나의 직사각형을 나타낸다. 첫 번째와 두 번째의 정수는 사각형의 왼쪽 아래 꼭지점의 x좌표, y좌표이고, 세 번째와 네 번째의 정수는 사각형의 오른쪽 위 꼭지점의 x좌표, y좌표이다. 단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수이다.
출력형식
화면에 4개의 직사각형이 차지하는 면적을 출력한다.
입력예제
1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6
출력예제
26
88개의 풀이가 있습니다.
Java 입니다. 뭐 참고로 저는 프로그래밍 초보자입니다^^;;;;
입력 좌표를 정수값만 받기 때문에,
배열 graph[x][y]로 2차원 그래프를 만들어 사용했습니다.
실제 그래프는 점 하나가 좌표값을 갖지만, 여기서는 graph[x][y]는 pixel처럼 1*1 면적을 갖는 정사각형 한 칸이 좌표값(정수)를 갖습니다.
입력값에서 세번째 열 중 Max를 Mx로 두고, 네번째 열 중 Max를 My로 둔 뒤,
배열 선언을 graph[Mx][My] 이렇게 합니다.
직사각형 하나가 a b c d로 입력받았을 경우,
x좌표는 a~(c-1)까지, y좌표는 b~(d-1)까지 해당됩니다.
직사각형에 해당되는 graph[x][y]값을 1 증가시킨 뒤,
graph[x][y]>0인 것 수를 세어서 면적을 계산했습니다. 길가의풀님, 이거 엽기적인가요???ㅎㅎㅎ
#예제를 그래프형식으로 출력한것
1 2 4 4 → (1,2)~(3,3)
2 3 5 7 → (2,3)~(4,6)
3 1 6 5 → (3,1)~(5,4)
7 3 8 6 → (7,3)~(7,5)
26
y축 (Max:7)
6 _ _ 1 1 1 _ _ _
5 _ _ 1 1 1 _ _ 1
4 _ _ 1 2 2 1 _ 1
3 _ 1 2 3 2 1 _ 1
2 _ 1 1 2 1 1 _ _
1 _ _ _ 1 1 1 _ _
0 _ _ _ _ _ _ _ _
0 1 2 3 4 5 6 7 x축 (Max:8)
제 코드에서 /*그래프그리기*/ 부분이 위의 그래프 형식을 출력합니다.
이 부분을 빼시면 문제에서 요구하는 대로 면적 결과만 출력합니다.
package h_four_boxes;
import java.util.Scanner;
public class Boxes {
public static void main(String[] args) {
int N=4, i,j, Mx=0,My=0, x,y, area=0;
Scanner in=new Scanner(System.in);
int[][] input=new int[N][4];
//입력할 x,y좌표는 1이상 1000이하 정수
for(i=0;i<N;i++) for(j=0;j<4;j++) input[i][j]=in.nextInt(); //입력
//그래프를 만들기 위한 최대 x,y값(Mx,My) 구하기
for(i=0;i<N;i++) if(input[i][2]>Mx) Mx=input[i][2];
for(i=0;i<N;i++) if(input[i][3]>My) My=input[i][3];
int[][] graph=new int[Mx][My]; //그래프 만듦.
for(x=0;x<Mx;x++) for(y=0;y<My;y++) graph[x][y]=0; //그래프초기화
for(i=0;i<N;i++){
for(x=input[i][0]; x<input[i][2]; x++)
for(y=input[i][1]; y<input[i][3]; y++) graph[x][y]++;
}
for(x=0;x<Mx;x++) for(y=0;y<My;y++) if(graph[x][y]>0) area++; //면적계산
System.out.println(area);
/*그래프그리기*/
System.out.println("y축 (Max:"+My+")");
for(y=My-1;y>=0;y--){
System.out.print(y+" ");
for(x=0;x<Mx;x++)
if(graph[x][y]>0) System.out.print(graph[x][y]+" ");
else System.out.print("_ ");
System.out.println();
} System.out.print(" ");
for(x=0;x<Mx;x++) System.out.print(x+" ");
System.out.println("x축 (Max:"+Mx+")");
/*그래프그리기 ends*/
}
}
rectangle = function(data){
range.x=diff(range(data[,c(1,3)]))
range.y=diff(range(data[,c(2,4)]))
logical.mat=matrix(F, range.x, range.y)
apply(data, 1, function(x) {logical.mat[seq.int(x[1], x[3]-1, by=1), seq.int(x[2], x[4]-1, by=1)] <<- T})
return(logical.mat)
}
R로 짰습니다. 전체 범위를 구한 다음 논리 행렬을 생성해서 해당되는 칸을 TRUE로 처리했습니다.
> data=matrix(c(1, 2, 4, 4,
+ 2, 3, 5, 7,
+ 3, 1, 6, 5,
+ 7, 3, 8, 6), 4, 4, byrow=T)
>
> rectangle(data)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] FALSE TRUE TRUE FALSE FALSE FALSE
[2,] FALSE TRUE TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE TRUE TRUE
[4,] TRUE TRUE TRUE TRUE TRUE TRUE
[5,] TRUE TRUE TRUE TRUE FALSE FALSE
[6,] FALSE FALSE FALSE FALSE FALSE FALSE
[7,] FALSE FALSE TRUE TRUE TRUE FALSE
> sum(rectangle(data))
[1] 26
결과입니다.
Perl
use strict;
my %h;
while(<>){
chomp;
my @n=split " ",$_;
for my $x ($n[0]..$n[2]-1){
for my $y ($n[1]..$n[3]-1){
$h{"$x,$y"}++
}
}
}
print scalar keys %h
Sub Main()
Dim cnt As Integer = Val(Console.ReadLine)
Dim rcts As New List(Of Rectangle)
Dim mapRct As Rectangle
For i As Integer = 0 To cnt - 1
Dim arr() As Integer = Array.ConvertAll(Split(Console.ReadLine, " "), Function(d As String) CInt(Val(d)))
Dim pt1 As New Point(arr(0), arr(1))
Dim pt2 As New Point(arr(2), arr(3))
Dim rct As Rectangle = New Rectangle(pt1, New Size(Math.Abs(pt2.X - pt1.X), Math.Abs(pt2.Y - pt1.Y)))
If i = 0 Then
mapRct = rct
Else
mapRct = Rectangle.Union(mapRct, rct)
End If
rcts.Add(rct)
Next
Dim r As Integer = 0
Dim map(mapRct.Width - 1, mapRct.Height - 1) As Byte
For Each rct As Rectangle In rcts
For x As Integer = rct.X - mapRct.X To rct.Right - mapRct.X - 1
For y As Integer = rct.Y - mapRct.Y To rct.Bottom - mapRct.Y - 1
If map(x, y) <> 1 Then
map(x, y) = 1
r += 1
End If
Next
Next
Next
Console.WriteLine("Result: " & r)
Console.ReadLine()
End Sub
백수의 노가다 .....
#include <stdio.h>
#include <stdlib.h>
struct Square {
int x, y;
int x1, y1;
int x2, y2;
int x3, y3;
int area;
};
Square Intersection(Square s1, Square s2);
void init(Square* s);
void main(void) {
int total = 0;
Square s[4];
Square is[8];
scanf("%d %d %d %d", &s[0].x, &s[0].y, &s[0].x3, &s[0].y3);
scanf("%d %d %d %d", &s[1].x, &s[1].y, &s[1].x3, &s[1].y3);
scanf("%d %d %d %d", &s[2].x, &s[2].y, &s[2].x3, &s[2].y3);
scanf("%d %d %d %d", &s[3].x, &s[3].y, &s[3].x3, &s[3].y3);
init(&s[0]);
init(&s[1]);
init(&s[2]);
init(&s[3]);
is[0] = Intersection(s[0], s[1]);
is[1] = Intersection(s[0], s[2]);
is[2] = Intersection(s[1], s[2]);
init(&is[0]);
is[3] = Intersection(is[0], s[2]);
is[4] = Intersection(s[0], s[3]);
is[5] = Intersection(s[1], s[3]);
is[6] = Intersection(s[2], s[3]);
init(&is[3]);
is[7] = Intersection(is[3], s[3]);
total = s[0].area + s[1].area + s[2].area + s[3].area
- is[0].area - is[1].area - is[2].area + is[3].area
- is[4].area - is[5].area - is[6].area + 2*is[7].area;
printf("\n%d", total);
}
void init(Square* s) {
s->x1 = s->x3;
s->y1 = s->y;
s->x2 = s->x;
s->y2 = s->y3;
s->area = (s->x3 - s->x) * (s->y3 - s->y);
}
Square Intersection(Square s1, Square s2) {
Square s;
if(s2.x < s1.x3 && s2.x3 > s1.x3 && s2.y < s1.y3 && s2.y3 > s1.y3 && s2.x < s1.x1 && s2.x3 > s1.x1 && s2.y < s1.y1 && s2.y3 > s1.y1 ) {
s.area = (s1.x3-s2.x) * (s1.y3 - s1.y);
s.x = s2.x;
s.y = s1.y;
s.x3 =s1.x3;
s.y3 =s1.y3;
}
else if(s2.x < s1.x3 && s2.x3 > s1.x3 && s2.y < s1.y3 && s2.y3 > s1.y3 && s2.x < s1.x2 && s2.x2 > s1.x2 && s2.y < s1.y2 && s2.y3 > s1.y2 ) {
s.area = (s1.y3-s2.y) * (s1.x3 - s1.x);
s.x = s1.x;
s.y = s2.y;
s.x3 = s1.x3;
s.y3 = s1.y3;
}
else if(s2.x < s1.x && s2.x3 > s1.x && s2.y < s1.y && s2.y3 > s1.y && s2.x < s1.x1 && s2.x3 > s1.x1 && s2.y < s1.y1 && s2.y3 > s1.y1 ) {
s.area = (s1.y3 -s1.y) * (s2.x3 - s1.x);
s.x = s1.x;
s.y = s1.y;
s.x3 =s2.x3 ;
s.y3 =s1.y3 ;
}
else if(s2.x < s1.x && s2.x3 > s1.x && s2.y < s1.y && s2.y3 > s1.y && s2.x < s1.x2 && s2.x3 > s1.x2 && s2.y < s1.y2 && s2.y3 > s1.y2 ) {
s.area = (s2.y3 - s1.y * s1.x3 -s1.x);
s.x = s1.x;
s.y = s1.y;
s.x3 = s1.x3;
s.y3 = s2.y3;
}
else if(s2.x > s1.x3 && s2.x3 < s1.x3 && s2.y > s1.y3 && s2.y3 < s1.y3 && s2.x > s1.x1 && s2.x3 < s1.x1 && s2.y > s1.y1 && s2.y3 < s1.y1 ) {
s.area = (s2.x3-s1.x) * (s2.y3 - s2.y);
s.x = s1.x;
s.y = s2.y;
s.x3 =s2.x3;
s.y3 =s2.y3;
}
else if(s2.x > s1.x3 && s2.x3 < s1.x3 && s2.y > s1.y3 && s2.y3 < s1.y3 && s2.x > s1.x2 && s2.x2 < s1.x2 && s2.y > s1.y2 && s2.y3 < s1.y2 ) {
s.area = (s2.y3-s1.y) * (s2.x3 - s2.x);
s.x = s2.x;
s.y = s1.y;
s.x3 = s2.x3;
s.y3 = s2.y3;
}
else if(s2.x > s1.x && s2.x3 < s1.x && s2.y > s1.y && s2.y3 < s1.y && s2.x > s1.x1 && s2.x3 < s1.x1 && s2.y > s1.y1 && s2.y3 < s1.y1 ) {
s.area = (s2.y3 -s2.y) * (s1.x3 - s2.x);
s.x = s2.x;
s.y = s2.y;
s.x3 =s1.x3 ;
s.y3 =s2.y3 ;
}
else if(s2.x > s1.x && s2.x3 < s1.x && s2.y > s1.y && s2.y3 < s1.y && s2.x > s1.x2 && s2.x3 < s1.x2 && s2.y > s1.y2 && s2.y3 > s1.y2 ) {
s.area = (s1.y3 - s2.y * s2.x3 -s2.x);
s.x = s2.x;
s.y = s2.y;
s.x3 = s2.x3;
s.y3 = s1.y3;
}
else if(s2.x < s1.x3 && s2.x3 > s1.x3 && s2.y < s1.y3 && s2.y3 > s1.y3 ) {
s.area = (s1.y3 - s2.y) * (s1.x3 - s2.x);
s.x = s2.x;
s.y = s2.y;
s.x3 = s1.x3;
s.y3 = s1.y3;
}
else if(s2.x < s1.x1 && s2.x3 > s1.x1 && s2.y < s1.y1 && s2.y3 > s1.y1) {
s.area = (s1.x3 -s2.x) * (s2.y3-s1.y);
s.x = s2.x;
s.y = s1.y;
s.x3 = s1.x3;
s.y3 = s2.y3;
}
else if(s2.x < s1.x2 && s2.x3 > s1.x2 && s2.y < s1.y2 && s2.y3 > s1.y2) {
s.area = (s2.x3 -s1.x) * (s1.y3 -s2.y);
s.x = s1.x;
s.y = s2.y;
s.x3 = s2.x3;
s.y3 = s1.y3;
}
else if(s2.x < s1.x && s2.x3 > s1.x && s2.y < s1.y && s2.y3 > s1.y) {
s.area = (s1.x3 -s2.x) * (s2.y3 -s1.y);
s.x = s1.x;
s.y = s1.y;
s.x3 = s2.x3;
s.y3 = s2.y3;
}
else if(s1.x <= s2.x && s1.y <= s2.y && s1.x1 <= s2.x1 && s1.y1 >= s2.y1 && s1.x2 <= s2.x2 && s1.y2 >= s2.y2 &&s1.x3 >= s2.x3 && s1.y3 >= s2.y3) {
s.area = (s2.x3 - s2.x) * (s2.y3 - s2. y);
s.x = s2.x;
s.y = s2.y;
s.x3 = s2.x3;
s.y3 = s2.y3;
}
else if(s1.x >= s2.x && s1.y >= s2.y &&s1.x1 >= s2.x1 && s1.y1 <= s2.y1 && s1.x2 >= s2.x2 && s1.y2 <= s2.y2 &&s1.x3 <= s2.x3 && s1.y3 <= s2.y3) {
s.area = (s1.x3 - s1.x) * (s1.y3 - s1. y);
s.x = s1.x;
s.y = s1.y;
s.x3 = s1.x3;
s.y3 = s1.y3;
}
else {
s.x = 0;
s.y = 0;
s.x3 = 0;
s.y3 = 0;
s.area = 0;
}
return s;
}
def area(x1,y1,x2,y2):
area = [0 for _ in range(x2)]
tmp = 0
for i in range(y1-1,y2-1): tmp += 2**i
for i in range(x1-1,x2-1): area[i] = tmp
return area
def add_area(*zone):
area = [0 for i in range(max(len(i) for i in zone))]
for j in zone:
for k in range(len(j)):
area[k] |= j[k]
return area
a = [[1,2,4,4],[2, 3, 5, 7],[3, 1, 6, 5],[7, 3, 8, 6]]
x = [area(*i) for i in a]
print(sum(bin(i).count('1') for i in add_area(*x)))
0 000000
6 000110
6 000110
6 000110
area = [0,6,6,6]
파이썬입니다.
import unittest
class RectError(RuntimeError):
pass
class Rect:
def __init__(self, lx, ly, rx, ry):
self.lx = lx
self.ly = ly
self.rx = rx
self.ry = ry
def size(self):
return abs(self.rx - self.lx) * abs(self.ry-self.ly)
def intersect(self, other):
try:
lx, rx = self.get(self.lx, self.rx, other.lx, other.rx)
ly, ry = self.get(self.ly, self.ry, other.ly, other.ry)
return Rect(lx,ly,rx,ry)
except RectError:
return Rect(0,0,0,0)
def __eq__(self, other):
return self.lx == other.lx \
and self.ly == other.ly \
and self.rx == other.rx \
and self.ry == other.ry
def __repr__(self):
return str((self.lx,self.ly))+str((self.rx,self.ry))
def get(self, sleft, sright, oleft, oright):
if oleft <= sleft <= oright:
if sright <= oright: return sleft, sright
else: return sleft, oright
elif sleft <= oleft <= sright:
if oright <= sright: return oleft, oright
else: return oleft, sright
else:
raise RectError("intersection does not exists!")
def comb(fromSet,choice):
if choice==0:
yield []
else:
for i, pivot in enumerate(fromSet):
for each in comb(fromSet[i+1:],choice-1):
yield [pivot]+each
def intersectSum(*rect):
result = 0
for rectGroup in rect:
for targetRect in rectGroup:
seed = targetRect[0]
for t in targetRect[1:]:
seed = seed.intersect(t)
result += seed.size()
return result
def calc(*rect):
result = 0
for i in range(len(rect)):
sign = i%2 and -1 or 1
result += sign * intersectSum(comb(rect, i+1))
return result
class SumOfRectTest(unittest.TestCase):
def testTwoRectNoIntersect(self):
A = Rect(0,0,1,1)
B = Rect(1,1,2,2)
self.assertEquals(2, A.size()+B.size())
self.assertEquals(0, A.intersect(B).size())
def testTwoRectIntersect(self):
A = Rect(0,0,2,2)
B = Rect(1,1,3,3)
self.assertEquals(8, A.size()+B.size())
self.assertEquals(1, A.intersect(B).size())
def testInterSect1(self):
A = Rect(0,0,2,2)
B = Rect(1,1,3,3)
C = Rect(1,1,2,2)
self.assertEquals(C, A.intersect(B))
self.assertEquals(C, B.intersect(A))
self.assertEquals(C, A.intersect(C))
self.assertEquals(C, C.intersect(B))
self.assertEquals(C, C.intersect(A))
self.assertEquals(C, B.intersect(C))
def testThreeRect1(self):
A = Rect(-1,-1,1,1)
B = Rect(0,0,2,2)
C = Rect(1,1,3,3)
self.assertEquals(4+4+4, A.size()+B.size()+C.size())
self.assertEquals(1, A.intersect(B).size())
self.assertEquals(1, B.intersect(C).size())
self.assertEquals(0, A.intersect(C).size())
self.assertEquals(0, A.intersect(B).intersect(C).size())
def testThreeRect2(self):
A = Rect(0,0,2,2)
B = Rect(1,1,3,3)
C = Rect(0,1,2,3)
self.assertEquals(1, A.intersect(B).intersect(C).size())
def testFourRect1(self):
A = Rect(0,0,2,2)
B = Rect(1,1,3,3)
C = Rect(1,0,3,2)
D = Rect(-1,0,1,3)
self.assertEquals(0, A.intersect(B).intersect(C).intersect(D).size())
self.assertEquals(1, A.intersect(B).size())
self.assertEquals(2, A.intersect(C).size())
self.assertEquals(2, A.intersect(D).size())
self.assertEquals(2, B.intersect(C).size())
self.assertEquals(0, B.intersect(D).size())
self.assertEquals(0, C.intersect(D).size())
self.assertEquals(1, A.intersect(B).intersect(C).size())
self.assertEquals(4+4+4+6, A.size()+B.size()+C.size()+D.size())
self.assertEquals(12, A.size()+B.size()+C.size()+D.size() -(1+2+2+2+0+0)+1)
def testFourRect2(self):
A = Rect(0,0,2,2)
B = Rect(0,-1,2,1)
C = Rect(-1,-1,1,1)
D = Rect(-1,0,1,2)
self.assertEquals(2, A.intersect(B).size())
self.assertEquals(1, A.intersect(C).size())
self.assertEquals(2, A.intersect(D).size())
self.assertEquals(2, B.intersect(C).size())
self.assertEquals(1, B.intersect(D).size())
self.assertEquals(2, C.intersect(D).size())
self.assertEquals(1, A.intersect(B).intersect(C).size())
self.assertEquals(1, A.intersect(B).intersect(D).size())
self.assertEquals(1, A.intersect(C).intersect(D).size())
self.assertEquals(1, B.intersect(C).intersect(D).size())
self.assertEquals(1, A.intersect(B).intersect(C).intersect(D).size())
self.assertEquals(4+4+4+4, A.size()+B.size()+C.size()+D.size())
self.assertEquals(9, 4+4+4+4-(2+1+2+2+1+2)+(1+1+1+1)-1)
self.assertEquals(9, calc(A,B,C,D))
def test1(self):
A = Rect(0,0,2,1)
B = Rect(0,0,1,2)
C = Rect(-1,-1,1,1)
D = Rect(-2,0,-1,3)
self.assertEquals(9, calc(A,B,C,D))
def test2(self):
A = Rect(0,0,2,2)
B = Rect(1,1,3,3)
C = Rect(2,2,4,4)
D = Rect(3,3,5,5)
self.assertEquals(13, calc(A,B,C,D))
def test3(self):
A = Rect(1,2,4,4)
B = Rect(2,3,5,7)
C = Rect(3,1,6,5)
D = Rect(7,3,8,6)
E = Rect(1,2,4,4)
self.assertEquals(26, calc(A,B,C,D,E))
if __name__ == "__main__":
unittest.main()
다른 풀이들의 해법과 유사하네요. 가독성이 좋게끔 java로 구현했습니다.
package com.ong.test;
public class FourRect {
private static final int[] rect1 = {1, 2, 4, 4};
private static final int[] rect2 = {2, 3, 5, 7};
private static final int[] rect3 = {3, 1, 6, 5};
private static final int[] rect4 = {7, 3, 8, 6};
enum MIN_MAX{MIN, MAX};
public static void main(String[] args) {
// find min, max of possible area
int minX = findMinMax(MIN_MAX.MIN, rect1[0], rect2[0], rect3[0], rect4[0]);
int minY = findMinMax(MIN_MAX.MIN, rect1[1], rect2[1], rect3[1], rect4[1]);
int maxX = findMinMax(MIN_MAX.MAX, rect1[2], rect2[2], rect3[2], rect4[2]);
int maxY = findMinMax(MIN_MAX.MAX, rect1[3], rect2[3], rect3[3], rect4[3]);
int possibleAreaWidth = maxX - minX;
int possibleAreaHeight = maxY - minY;
int[][] field = new int[possibleAreaHeight][possibleAreaWidth];
fillField(field, rect1, minX, minY);
fillField(field, rect2, minX, minY);
fillField(field, rect3, minX, minY);
fillField(field, rect4, minX, minY);
System.out.println(sumFields(field));
}
private static void fillField(int[][] field, int[] rect, int offsetX, int offsetY) {
for(int i = rect[1] - offsetY; i < rect[3] - offsetY; i++) { // row
for(int j = rect[0] - offsetY; j < rect[2] - offsetY; j++) { // column
field[i][j] = 1;
}
}
}
private static int sumFields(int[][] field) {
int sum = 0;
for(int i = 0; i < field.length; i++) { // row
for(int j = 0; j < field[i].length; j++) { // column
sum += field[i][j];
}
}
return sum;
}
private static int findMinMax(MIN_MAX minMax, int... values) {
int result = values[0];
for(int input : values) {
if(MIN_MAX.MIN.equals(minMax)) {
result = Math.min(result, input);
} else {
result = Math.max(result, input);
}
}
return result;
}
}
C#으로 작성했습니다. 가장 큰 x와 y를 구한 후 한칸 한칸 체크해가면서 아무 box에나 들어가는지 확인했습니다.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodingDojang
{
class CodingDojang
{
static void Main(string[] args)
{
var stopwatch = Stopwatch.StartNew();
FourBoxes.Answer();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Console.Read();
}
}
public static class FourBoxes
{
public static void Answer()
{
var inputs = new List<Rectangle>();
for(int i = 0; i < 4; i++)
{
var input = Console.ReadLine().Split(' ').ToList();
inputs.Add(new Rectangle(input[0], input[1], input[2], input[3]));
}
FourBoxes(inputs);
}
public class Coordinate
{
public int X { get; set; }
public int Y { get; set; }
public Coordinate(string x, string y)
{
X = int.Parse(x);
Y = int.Parse(y);
}
}
public class Rectangle
{
public Coordinate Max { get; set; }
public Coordinate Min { get; set; }
public Rectangle(string x1, string y1, string x2, string y2)
{
Min = new Coordinate(x1, y1);
Max = new Coordinate(x2, y2);
}
}
public static void FourBoxes(List<Rectangle> inputs)
{
var maxX = inputs.Max(i => i.Max.X);
var maxY = inputs.Max(i => i.Max.Y);
var area = 0;
for(int i = 0; i < maxX; i++)
for(int j = 0; j < maxY; j++)
if(AreaRectangle(inputs, i, j)) area++;
Console.WriteLine(area);
}
public static bool AreaRectangle(List<Rectangle> inputs, int x, int y)
{
for(int i = 0; i < inputs.Count; i++)
if(inputs[i].Min.X <= x && inputs[i].Max.X > x
&& inputs[i].Min.Y <= y && inputs[i].Max.Y > y)
return true;
return false;
}
}
}
C입니다. 알고리즘은 직사각형을 모눈으로 나눠서 모눈의 위치를 리스트에 저장했습니다. 모눈의 위치를 정수에 일대일대응시키기 위해서 군수열을 이용했습니다(수1이 쓰이다니). 예를 들어 한 직사각형에 대해서 직사각형 내의 모눈들의 위치를 모조리 데이터베이스에 저장하고, 다음 직사각형의 내의 모눈들을 데이터베이스에 이미 있지 않으면 데이터베이스에 저장하도록 했습니다. 데이터베이스에 있는 총 모눈의 수를 세면 그게 바로 전체 넓이가 됩니다.
#include <stdio.h>
typedef struct box
{
int x1,y1,x2,y2;
} Box;
int max(int *arr)
{
int i,result;
result=0;
for(i=0;i<4;i++)
if (result<arr[i]) result = arr[i];
return result;
}
int min(int *arr)
{
int i,result;
result=arr[0];
for(i=1;i<4;i++)
if (result>arr[i]) result = arr[i];
return result;
}
int isin(int *arr, int size, int x)
{
int i;
for(i=0;i<8;i++)
if (arr[i]==x) return 1;
return 0;
}
int main()
{
int xs[8], ys[8];
Box boxes[4];
int i,a,b,c,d;
for(i=0;i<4;i++)
{
scanf("%d %d %d %d", &a, &b, &c, &d);
boxes[i].x1 = a;
xs[2*i]=a;
boxes[i].y1 = b;
ys[2*i]=b;
boxes[i].x2 = c;
xs[2*i+1]=c;
boxes[i].y2 = d;
ys[2*i+1]=d;
}
int unit_num;
int size;
size = (max(xs)-min(xs))*(max(ys)-min(ys));
int units[size];
int k,j,temp;
for(k=0;k<4;k++)
{
for(i=boxes[k].x1;i<boxes[k].x2;i++)
{
for(j=boxes[k].y1;j<boxes[k].y2;j++)
{
temp = (i+j)*(i+j-1)/2+j+1;
if (!isin(units, size, temp)) units[unit_num++]=temp;
}
}
}
printf("%d\n", unit_num);
return 0;
}
boxes = []
for i in range(4):
boxes.append(map(int, raw_input().split()))
bb = [float('inf'),float('inf'),-float('inf'),-float('inf')]
for (a,b,c,d) in boxes:
if a<bb[0]: bb[0]=a
if b<bb[1]: bb[1]=b
if c>bb[2]: bb[2]=c
if d>bb[3]: bb[3]=d
bb_map = [[0 for i in range(bb[2]-bb[0]+1)] for i in range(bb[3]-bb[1]+1)]
def draw_rect(box):
for i in range(box[1],box[3]):
for j in range(box[0],box[2]):
bb_map[i-bb[1]][j-bb[0]] = 1
for box in boxes:
draw_rect(box)
print sum(map(sum, bb_map))
python3입니다. set에 좌표들을 다 때려박고 원소 갯수를 셌습니다.
locs = set()
def sol(tc):
for (lx, ly, rx, ry) in tc:
for i in range(lx, rx):
for j in range(ly, ry):
locs.add((i, j))
return len(locs)
tc = [(1, 2, 4, 4), (2, 3, 5, 7), (3, 1, 6, 5), (7, 3, 8, 6)]
print(sol(tc))
def fill_plane(plane, coordinate):
for x in range(coordinate[0],coordinate[2]):
for y in range(coordinate[1],coordinate[3]):
plane[y][x] = 1
if __name__ == '__main__':
Plane = [[0]*1000 for x in range(1000)]
for x in range(4):
coordinate = input("Enter the data of #%d square: " % (x+1))
coordinate = [int(c) for c in coordinate.split()]
fill_plane(Plane,coordinate)
Area = sum([sum(x) for x in Plane])
print('총 면적: %d' % Area)
파이썬 3.0입니다. 평면을 만들어놓고, 사각형을 1로 색칠한 후, 그 값을 더하는 방식을 사용했습니다.
from itertools import product
co = [[int(x) for x in raw_input().split()] for y in range(4)]
print len(reduce(lambda x,y:x|y,[{p for p in product( range(x1,x2),range(y1,y2) )}
for (x1,y1,x2,y2) in co]))
Python으로 작성했습니다. 면적에 해당하는 좌표를 리스트에 집어넣고 중복되는 영역은 무시하고 리스트 원소의 갯수를 센다.
def getArea(rects):
pointList = set()
for rect in rects:
for x in range(rect[0], rect[2]):
for y in range(rect[1], rect[3]
pointList.add((x,y))
return len(pointList)
rects=[]
print("Input rectangle 4 points or enter for quit")
while True:
v = input()
if v == "":
break
else:
rects.append([int(x) for x in v.split(" ")])
print("area : %d" % getArea(rects))
결과
Input rectangle 4 points or enter for quit
1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6
area : 26
sample = '''1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6'''
def place(li, co):
lx, ly, rx, ry = co
for x in range(lx, rx):
for y in range(ly, ry):
li[x][y] = 1
if __name__ == '__main__':
ra = list((list((int(y) for y in x.split())) for x in (sample.split('\n'))))
h = max(max(x) for x in ra)
area = list((list((0 for y in range(h+1))) for x in range(h+1)))
for x in ra:
place(area, x)
print(sum((x.count(1))for x in area))
파이썬 3.5.1 입니다. 답은 26.
Ruby
tiles = ->rect { x1,y1,x2,y2 = rect; [*x1...x2].product [*y1...y2] }
area = ->rects { rects.sum([], &tiles).uniq.size }
or
rects.flat_map {|x1,y1,x2,y2|[*x1...x2].product [*y1...y2]}.uniq.size #=>26
Test
rects = [[1,2,4,4],[2,3,5,7],[3,1,6,5],[7,3,8,6]]
expect(area[rects]).to eq 26
4개의 사각형을 모두 둘러싸는 최소의 사각형을 구해 그 넓이를 구하고, 사각형의 모든 좌표는 정수값이라는 점에 착안, 둘러싼 영역의 각 좌표 x, y에 대해 x + 0.5, y + 0.5 가 A, B, C, D 사각형의 어느 것에도 속해있지 않다면, 전체 넓이에서 1씩 빼서 답을 구합니다.
inputs = []
for _ in range(4):
ax, ay, bx, by = [int(x) for x in input().split()[:4]]
inputs.append(((ax, ay), (bx, by)))
# get sx, sy ~ ex, ey
sx = min([x[0] for (x, _) in inputs])
sy = min([x[1] for (x, _) in inputs])
ex = max([x[0] for (_, x) in inputs])
ey = max([x[1] for (_, x) in inputs])
def hasPoint(a, b, px, py):
ax, ay = a
bx, by = b
return ax < px + 0.5 < bx and ay < py + 0.5 < by
for x in range(sx, ex):
for y in range(sy, ey):
for a, b in inputs:
if hasPoint(a, b, x, y):
break
else:
s -= 1
print(s)
파이썬 3.4.2
matr = set()
lis = []
for i in range(4):
lis.append(tuple(map(int,input().split())))
for p in lis:
x1 = p[0]
y1 = p[1]
x2 = p[2]
y2 = p[3]
for x in range(x1,x2):
for y in range(y1,y2):
matr.add((x,y)) # (x,y)는 (x,y)부터 (x+1,y+1)까지의 정사각형을 나타냅니다 똑같은 것이 집합에서는 하나로 취급되어 중복되는 것은 없어진다.
print(len(matr))
a=[]
coll=[]
roww=[]
l=0
for i in range(4):
a.append(input().split(" "))
for i in range(4):
coll.append(int(a[i][0]))
coll.append(int(a[i][2]))
roww.append(int(a[i][1]))
roww.append(int(a[i][3]))
coll.sort()
roww.sort()
summ=[[0 for row in range(roww[-1])] for col in range(coll[-1])]
for k in range(4):
for i in range(int(a[k][0]),int(a[k][2])):
for j in range(int(a[k][1]),int(a[k][3])):
summ[i][j]=1
for i in range(coll[-1]):
for j in range(roww[-1]):
l=l+summ[i][j]
print(l)
PHP로 짜봤습니다.
$input = array();
$input[] = array(1,2,4,4);
$input[] = array(2,3,5,7);
$input[] = array(3,1,6,5);
$input[] = array(7,3,8,6);
$area = array(array());
$sum = 0;
foreach($input as $in) {
for($i=$in[0]; $i<$in[2]; $i++) {
for($j=$in[1]; $j<$in[3]; $j++) {
if(!isset($area[$i][$j])) {
$area[$i][$j] = true;
$sum++;
}
}
}
}
echo $sum;
package main
import "fmt"
var board = [1000][1000]bool{}
type Rect struct {
l, t, r, b int
}
func main() {
var r Rect
for k := 0; k < 4; k++ {
fmt.Scan(&r.l, &r.b, &r.r, &r.t)
for j := r.b; j < r.t; j++ {
for i := r.l; i < r.r; i++ {
board[j][i] = true
}
}
}
sum := 0
for j := 0; j < 1000; j++ {
for i := 0; i < 1000; i++ {
if board[j][i] {
sum++
}
}
}
fmt.Print(sum)
}
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int findMax(int ary[4][4]);
int main(void) {
int ary[4][4] = { 0 };
int maxX, maxY, count = 0;
for (int i = 0; i < 4; i++) {
std::cin >> ary[i][0] >> ary[i][1] >> ary[i][2] >> ary[i][3];
std::cin.ignore(1, ',');
}
maxX = findMax(ary);
maxY = maxX;
std::vector < std::vector <int>> boxes(maxY+1, std::vector<int>(maxX+1));
for (int i = 0; i < maxY; i++) {
boxes[i].assign(boxes[i].size(), 0);
}
for (int num = 0; num < 4; num++) {
for (int y = ary[num][1]; y < ary[num][3]; y++) {
for (int x = ary[num][0]; x < ary[num][2]; x++) {
boxes[y][x]++;
}
}
}
for (int y = 0; y < maxY; y++) {
for (int x = 0; x < maxX; x++) {
if (boxes[y][x] > 0)
count++;
}
}
std::cout << "Result : " << count << std::endl;
return 0;
}
int findMax(int ary[4][4]) {
std::vector <int> st;
for (int i = 0; i < 4; i++) {
int max = *std::max_element(ary[i], ary[i] + 4);
st.push_back(max);
}
int max = *std::max_element(st.begin(), st.end());
return max;
}
배열 1개요소를 1픽셀로 계산하고 작성했습니다
Delphi 2010
function ComparePointItem(Item1, Item2: Pointer): Integer;
begin
result := Integer(Item1) - Integer(Item2);
end;
procedure TForm4.btnFourBoxesClick(Sender: TObject);
type
TPoint2d = Record
X, Y: Double;
end;
TBox2d = Record
s, e: TPoint2d;
end;
procedure SetPoint(var P: TPoint2d; a1, a2: Double);
begin
P.X := a1;
P.Y := a2;
end;
procedure SwapDouble(var a1, a2: Double);
var
tmp: Double;
begin
tmp := a1;
a1 := a2;
a2 := tmp;
end;
procedure Setbox(var Box: TBox2d; a1, a2, a3, a4: Double);
begin
if a1 > a3 then
SwapDouble(a1, a3);
if a2 > a4 then
SwapDouble(a2, a4);
SetPoint(Box.s, a1, a2);
SetPoint(Box.e, a3, a4);
end;
function Pt_InRange(p1, fmin, fmax: TPoint2d): boolean;
begin
result := (fmin.X <= p1.X) and (fmax.X >= p1.X) and (fmin.Y <= p1.Y) and (fmax.Y >= p1.Y)
end;
var
Box: array [0 .. 3] of TBox2d;
AX, AY: array [0 .. 10] of Double;
C: TPoint2d;
i, j, k, XCnt, YCnt: Integer;
List: TList;
bOk: boolean;
Area, d: Double;
begin
// Set Box Value
Setbox(Box[0], 1, 2, 4, 4);
Setbox(Box[1], 2, 3, 5, 7);
Setbox(Box[2], 3, 1, 6, 5);
Setbox(Box[3], 7, 3, 8, 6);
List := TList.create;
try
// X방향 분할
for i := 0 to 3 do
begin
k := Trunc(Box[i].s.X);
List.Add(Pointer(k));
k := Trunc(Box[i].e.X);
List.Add(Pointer(k));
end;
List.Sort(ComparePointItem); // 순서 정렬
Memo1.Lines.Clear;
k := -1;
XCnt := 0;
for i := 0 to List.count - 1 do
if k <> Integer(List[i]) then
begin
k := Integer(List[i]);
AX[XCnt] := k;
Inc(XCnt);
end;
List.Clear; // 초기화
// Y방향 분할
for i := 0 to 3 do
begin
k := Trunc(Box[i].s.Y);
List.Add(Pointer(k));
k := Trunc(Box[i].e.Y);
List.Add(Pointer(k));
end;
List.Sort(ComparePointItem); // 순서 정렬
k := -1;
YCnt := 0;
for i := 0 to List.count - 1 do
if k <> Integer(List[i]) then
begin
k := Integer(List[i]);
AY[YCnt] := k;
Inc(YCnt);
end;
Area := 0;
for i := 0 to XCnt - 2 do
for j := 0 to YCnt - 2 do
begin
// Range의 Center점 구하기
C.X := (AX[i] + AX[i + 1]) / 2;
C.Y := (AY[j] + AY[j + 1]) / 2;
// 해당 Box가 포함되면
bOk := False;
for k := 0 to 3 do
if Pt_InRange(C, Box[k].s, Box[k].e) then
begin
bOk := true;
break;
end;
// 해당 면적을 더함.
if bOk then
begin
d := (AX[i + 1] - AX[i]) * (AY[j + 1] - AY[j]);
Area := Area + d;
end;
end;
Memo1.Lines.Add(format('Four Boxes Area: %0.0f', [Area]));
finally
List.Free;
end;
end;
Python 3
coords = []
maxval = 0
for x in range(4):
coords.append(list(map(int, input().split())))
maxval = max(max(coords[x]), maxval)
mapping = [[0 for x in range(maxval)] for y in range(maxval)]
for x in coords:
for y in range(x[0], x[2]):
for z in range(x[1], x[3]):
mapping[y][z] = 1
print(sum(map(sum, mapping)))
int main(int argc, const char * argv[]) {
box boxes[4] = {
{1,2,4,4},
{2,3,5,7},
{3,1,6,5},
{7,3,8,6},
};
printf("%d\n", area(boxes, 4));
return 0;
}
box 타입은..
typedef struct box box;
struct box{
int x1,y1,x2,y2;
};
area()를 살펴보자.
int area(box boxes[], int n) {
// x좌표와 y좌표를 모두 모을 배열..
int *xs = (int*)calloc(n*2, sizeof(int));
int *ys = (int*)calloc(n*2, sizeof(int));
// 모두 모아...
for (int i=0; i<n*2; i+=2) {
xs[i] = boxes[i/2].x1;
xs[i+1] = boxes[i/2].x2;
ys[i] = boxes[i/2].y1;
ys[i+1] = boxes[i/2].y2;
}
// 정렬!
qsort(xs, n*2, sizeof(int), intComp);
qsort(ys, n*2, sizeof(int), intComp);
// 이제 사각형 전체를 감싸는 16x16 격자가 생겼음.
// 하나씩 보고 사각형에 들어가면 면적을 더한다..
int area = 0;
for (int i=0; i<n*2-1; i++) {
int x = xs[i];
for (int j=0; j<n*2-1; j++) {
int y = ys[j];
// (x,y)를 왼쪽 아래 꼭지점으로 하는 사각형이
// 주어진 상자들에 포함되어 있는지 보자..
for (int k = 0; k < n; k++) {
if (contains(boxes[k], x, y)) {
area += (xs[i+1] - x) * (ys[j+1] - y);
break;
}
}
}
}
free(xs);
free(ys);
return area;
}
사각형이 어떤 점을 포함하려면..
int contains(box b, int x, int y) {
return x >= b.x1 && x < b.x2 && y >= b.y1 && y < b.y2;
}
_list =[''.join(input().split(' ')) for x in range(4)]
last = [int(max(list(''.join(_list)[::2]))),int(max(list(''.join(_list)[1::2])))]
load =[list(map(int,x)) for x in _list]
bus, count = [0,0], 0
while bus <= last:
step = 0
for x in range(len(_list)):
if load[x][0] <= bus[0] < load[x][2] and load[x][1] <= bus[1] < load[x][3]:
step = 1
if bus[1] > last[1]:
bus[0] += 1
bus[1] = 0
else:
bus[1] += 1
count += step
print(count)
#### 2017.01.26 D-392 ####
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
public class FourBoxes {
public static void main(String[] args) throws FileNotFoundException {
Integer[][] round = new Integer[1000][1000];
Integer[][] points = new Integer[4][4];
String path = FourBoxes.class.getResource("").getPath();
Scanner sc = new Scanner(new File(path + "FourBoxes.txt"));
IntStream.range(0, 1000).forEach(i -> Arrays.fill(round[i], 0));
IntStream.range(0, 4).forEach(i -> IntStream.range(0, 4).forEach(j -> points[i][j] = sc.nextInt()));
IntStream.range(0, 4).forEach(i -> IntStream.range(points[i][0], points[i][2]).forEach(j -> IntStream.range(points[i][1], points[i][3]).forEach(k -> round[k][j] = 1)));
System.out.println(Arrays.stream(round).flatMap(x -> Arrays.stream(x)).filter(i -> i == 1).count());
}
}
#include <stdio.h>
#include <stdlib.h>
int arr[1000][1000] = {};
void four(int a, int b, int c, int d)
{
int copyonex = a + 1;
int copyoney = b + 1;
for (; copyonex <= c; copyonex++)
{
for (copyoney = b + 1; copyoney <= d; copyoney++)
{
arr[copyonex][copyoney] = 1;
}
}
}
int main(void)
{
int onex = 0, oney = 0; // 할 때 마다 +1 (x,y)->(y,x)
int twox = 0, twoy = 0; // 변동이 없음
for (int i = 0; i < 4; i++)
{
scanf_s("%d %d %d %d", &onex, &oney, &twox, &twoy);
four(onex, oney, twox, twoy);
}
//카운드
int count = 0;
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 1000; j++)
{
count += arr[i][j];
}
}
printf("넓이 : %d", count);
return 0;
}
import numpy as np
sheet = np.zeros((1000, 1000))
def f_rect(A):
global sheet
for i in range(len(A)):
f_fill(A[i])
# print sheet
return sheet.sum()
def f_fill(a):
global sheet
for i in range(a[0],a[2]):
for j in range(a[1],a[3]):
sheet[i][j] = 1
#26
arr = np.array([[1,2,4,4],[2,3,5,7],[3,1,6,5],[7,3,8,6]])
print f_rect(arr)
xy=[[0 for col in range(1000)]for row in range(1000)]
s1=[1,2,4,4]
s2=[2,3,5,7]
s3=[3,1,6,5]
s4=[7,3,8,6]
def rectangle(x):
x1=x[0]
y1=x[1]
x2=x[2]
y2=x[3]
i=x1
j=y1
while i<x2:
j=y1
while j<y2:
xy[i][j]=1
j+=1
i+=1
def total_range(xy):
cnt=0
for i in range(1000):
for j in range(1000):
if xy[i][j]==1:
cnt+=1
return cnt
rectangle(s1)
rectangle(s2)
rectangle(s3)
rectangle(s4)
print(total_range(xy))
javascript(ES6)
var getPoint = function(line) {
var [, x1, y1, x2, y2] = /^(\d)\s(\d)\s(\d)\s(\d)$/g.exec(line);
return {
"x1" : x1,
"y1" : y1,
"x2" : x2,
"y2" : y2
};
};
var getArea = function(input) {
var inputs = input.split("\n").map(v => v.trim());
var coordinates = [];
for (line of inputs) {
var p = getPoint(line);
for (let x = p.x1; x < p.x2; x++) {
for (let y = p.y1; y < p.y2; y++) {
if (!coordinates[x]) coordinates[x] = [];
coordinates[x][y] = 1;
}
}
}
return coordinates.reduce((a,b) => a.concat(b))
.reduce((a,b) => a + b);
}
var input =
`1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6`;
console.log(getArea(input));
Python
inputstr = \
"""1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6 """
data = list(map(int, inputstr.split()))
size = max(data)
arr = [0 for i in range(size*size)]
for k in range(0, 16, 4):
x1, y1, x2, y2 = data[k], data[k+1], data[k+2], data[k+3]
for i in range(x1, x2):
for j in range(y1, y2):
arr[i*size + j] = 1
print(sum(arr)) #26
"길가의풀"님 답변을 참고해서 수정
data = list(map(int, inputstr.split()))
rects = set() # set of 1x1 unit areas
for k in range(0, 16, 4):
[x1, y1, x2, y2] = data[k:k+4]
for i in range(x1, x2):
for j in range(y1, y2):
rects.add((i,j))
print(len(rects))
[Python 3.6] 사각형 내부 좌표를 Set에 넣고(중복 제거) Set의 길이 반환
def calcArea(inStr):
lineData = inStr.strip().split("\n")
rectArea = set()
for line in lineData:
axisArr = list(map(int, line.strip().split()))
for x in range(axisArr[0], axisArr[2]):
for y in range(axisArr[1], axisArr[3]):
rectArea.add((x, y))
print(len(rectArea))
inStr = """
1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6
"""
calcArea(inStr)
Python 3로 풀었습니다. Set을 이용하여 간단하지만 무식하게 풀 수 있습니다.
input = '''1 2 4 4\n2 3 5 7\n3 1 6 5\n7 3 8 6'''
rect_set = set()
for rect_str in input.split('\n'):
rect = [int(c) for c in rect_str.split()]
for x in range(rect[0], rect[2]):
for y in range(rect[1], rect[3]):
rect_set.add((x, y))
print(len(rect_set))
public class Calculate {
public static void main(String[] args) {
int [][] rectangles = {{1,2,4,4}, {2,3,5,7}, {3,1,6,5}, {7,3,8,6}}; //입력값
int maxX = 0;
int maxY = 0;
int sum = 0;
for (int i=0 ; i<rectangles.length ; i++){
if( maxX < rectangles[i][2]) maxX = rectangles[i][2];
if( maxY < rectangles[i][3]) maxY = rectangles[i][3];
}
int [][] bigSquare = new int[maxY][maxX];
for(int i=0 ; i<rectangles.length ; i++){
for (int x=rectangles[i][0] ; x<rectangles[i][2] ; x++){
for (int y=rectangles[i][1] ; y<rectangles[i][3] ; y++){
bigSquare[y][x] = 1;
}
}
}
for(int x=0 ; x<maxX ; x++)
for(int y=0 ; y<maxY ; y++)
sum += bigSquare[y][x];
System.out.println(sum);
}
}
# python 3.6
inp = """1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6"""
inp = [s.split(" ") for s in inp.split("\n")]
# (x,y): (1,1)~(2,2) 안의 격자가 채워지면 plot[1][1]=1이 되는 개념 적용
plot = [[0 for x in range(1, 1001)] for y in range(1, 1001)]
for lst in inp:
cord = [int(c) for c in lst]
for y in range(cord[1], cord[3]):
for x in range(cord[0], cord[2]):
plot[y - 1][x - 1] = 1
print(sum([sum(ylst) for ylst in plot])) # 1인 격자의 합 출력
public class ex10 { public static void main(String[] args) { int[][] rect = {{1,2,4,4}, {2,3,5,7}, {3,1,6,5}, {7,3,8,6}};
int sum = 0;
int[][] Big = new int[1000][1000];
for(int i=0; i<rect.length; i++) {
for(int j= rect[i][0]; j<rect[i][2]; j++) {
for(int k=rect[i][1]; k<rect[i][3]; k++) {
Big[j][k] = 1;
}
}
}
for(int i=0; i<1000; i++) {
for(int j=0; j<1000; j++) {
sum += Big[i][j];
}
}
System.out.println(sum);
}
}
Java 입니다.
public class level_3_four_boxes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("첫번째 사각형의 왼쪽아래 꼭지점 좌표(x1, y1)와 오른쪽 위 좌표(x2, y2)를 순서대로 입력하세요. 단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수입니다. (입력 예시. 1 2 4 4)");
int x1 = sc.nextInt(), y1 = sc.nextInt(), x2 = sc.nextInt(), y2 = sc.nextInt();
System.out.println("두번째 사각형의 왼쪽아래 꼭지점 좌표(x3, y3)와 오른쪽 위 좌표(x4, y4)를 순서대로 입력하세요. 단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수입니다. (입력 예시. 1 2 4 4)");
int x3 = sc.nextInt(), y3 = sc.nextInt(), x4 = sc.nextInt(), y4 = sc.nextInt();
System.out.println("세번째 사각형의 왼쪽아래 꼭지점 좌표(x5, y5)와 오른쪽 위 좌표(x6, y6)를 순서대로 입력하세요. 단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수입니다. (입력 예시. 1 2 4 4)");
int x5 = sc.nextInt(), y5 = sc.nextInt(), x6 = sc.nextInt(), y6 = sc.nextInt();
System.out.println("네번째 사각형의 왼쪽아래 꼭지점 좌표(x7, y7)와 오른쪽 위 좌표(x8, y8)를 순서대로 입력하세요. 단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수입니다. (입력 예시. 1 2 4 4)");
int x7 = sc.nextInt(), y7 = sc.nextInt(), x8 = sc.nextInt(), y8 = sc.nextInt();
int area = 0;
int box[][] = new int[1000][1000];
sc.close();
for(int i = 0; i < 1000; i++) // 모든 칸을 0으로 채움.
{
for(int j = 0; j < 1000; j++)
{
box[i][j] = 0;
}
}
for(int i = x1; i < x2; i++)
{
for(int j = y1; j < y2; j++)
{
box[i][j] = 1;
}
}
for(int i = x3; i < x4; i++)
{
for(int j = y3; j < y4; j++)
{
box[i][j] = 1;
}
}
for(int i = x5; i < x6; i++)
{
for(int j = y5; j < y6; j++)
{
box[i][j] = 1;
}
}
for(int i = x7; i < x8; i++)
{
for(int j = y7; j < y8; j++)
{
box[i][j] = 1;
}
}
for(int i = 0; i < 1000; i++)
{
for(int j = 0; j < 1000; j++)
{
area = area + box[i][j];
}
}
System.out.println("각각의 직사각형들이 차지하는 면적의 넓이 (중복된 범위는 하나로 따짐) : " + area);
}
}
파이썬 3.6
"""
아이디어>
1) x,y 좌표 최대 범위의 2차원 배열[x][y]를 0을 요소로 하여 생성합니다.
2) 각 직사각형의 영역안의 배열 요소의 값을 1로 채웁니다.
3) 모든 직사각형의 영역을 1로 채운 후 각 배열의 sum 값을 누적 합산 합니다.
"""
data ="""1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6"""
def area(square):
for y in range(int(square[1]),int(square[3])):
for x in range(int(square[0]),int(square[2])):
square_area[y][x] = 1
return square_area
def main(square_list):
area_total = 0
for square in square_list:
area(square)
for column in square_area:
area_total += sum(column)
print(area_total)
if __name__ == "__main__":
square_list = [i.split(' ') for i in data.split('\n')]
square_area = [[ 0 for i in range(1,10001)] for h in range(1,1001)]
main(square_list)
* 결과값
26
var _sum_set = new Set;
function _set_rec (a,b,c,d) {
var array = new Array;
for ( var i = a; i < c; i++) {
for (var j = b; j < d; j++) {
array.push(String(i)+String(j));
}
}
return array;
}
function _add_set (a, b, c, d) {
var _array_1 = _set_rec(a,b,c,d);
var x = c - a;
var y = d - b;
var cons = x * y;
for ( var k = 0; k < cons; k++) {
_sum_set.add(_array_1[k]);
}
return _sum_set;
}
_add_set(1,2,4,4)
_add_set(2,3,5,7)
_add_set(3,1,6,5)
_add_set(7,3,8,6)
console.log(_sum_set.size)
package fourBoxes;
public class FourBoxes {
public int fourBoxes(int[][] arr) {
int[][] boxes = new int[10][10];
for (int[] ele : arr)
for (int i = ele[1]; i < ele[3]; i++)
for (int j = ele[0]; j < ele[2]; j++)
boxes[i][j] = 1;
int result = 0;
for (int[] elements : boxes)
for (int ele : elements)
if (ele == 1)
result++;
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FourBoxes fb = new FourBoxes();
System.out
.println(fb.fourBoxes(new int[][] { { 1, 2, 4, 4 }, { 2, 3, 5, 7 }, { 3, 1, 6, 5 }, { 7, 3, 8, 6 } }));
}
}
def area(a):
result = 0
xcoordinate = list()
ycoordinate = list()
for i in a:
xcoordinate.append(i[0])
xcoordinate.append(i[2])
ycoordinate.append(i[1])
ycoordinate.append(i[3])
xcoordinate = sorted(list(set(xcoordinate)))
ycoordinate = sorted(list(set(ycoordinate)))
for i in range(len(xcoordinate)-1):
for j in range(len(ycoordinate)-1):
if any([all([k[0] <= xcoordinate[i], k[1] <= ycoordinate[j], k[2] >= xcoordinate[i+1], k[3] >= ycoordinate[j+1]]) for k in a]):
result += (xcoordinate[i+1]-xcoordinate[i]) * (ycoordinate[j+1]-ycoordinate[j])
return "{0}".format(result)
l = list()
while len(l) < 4:
n = input("좌표를 입력하시오 :")
l.append(list(map(int, n.split(' '))))
print(area(l))
import java.util.Scanner;
public class FouBoxes {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String[] input = new String[4];
for(int i=0; i<4; i++){
input[i] = sc.nextLine();
}
sc.close();
int[][] plane = new int[1001][1001];
int x1, x2, y1, y2;
for(int i=0; i<input.length; i++){
String[] point = input[i].split(" ");
x1 = Integer.parseInt(point[0]);
y1 = Integer.parseInt(point[1])-1;
x2 = Integer.parseInt(point[2]);
y2 = Integer.parseInt(point[3])-1;
for(int k = x1; k < x2; k++){
for(int j = y1; j < y2; j++){
plane[k][j] = 1;
}
}
}
int area = 0;
for(int i=0; i< 1001; i++){
for(int j=0; j<1001; j++){
if(plane[i][j] == 1){
area++;
}
}
}
System.out.println(area);
}
}
1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6
26
def inn(poi, box):
minx=min(box[0], box[2])-1
maxx=max(box[0], box[2])
miny=min(box[1], box[3])-1
maxy=max(box[1], box[3])
if (poi[0]>minx) and (poi[0]<maxx) and (poi[1]>miny) and (poi[1]<maxy):
return 1
return 0
points=[[1,2,4,4], [2,3,5,7], [3,1,6,5], [7,3,8,6]]
mi = [min([point[0] for point in points]+[point[2] for point in points]),min([point[1] for point in points]+[point[3] for point in points])]
ma = [max([point[0] for point in points]+[point[2] for point in points]),max([point[1] for point in points]+[point[3] for point in points])]
re=0
for col in range(mi[0], ma[0]):
for row in range(mi[1], ma[1]):
for point in points:
if inn([col,row],point)==1:
re=re+1
break
print(re)
#include <stdio.h>
int inn(int i, int j, int box[4]) {
int minx, maxx, miny, maxy;
int poi[2] = { i,j };
minx = box[0] > box[2] ? box[2] - 1 : box[0] - 1;
maxx = box[0] < box[2] ? box[2] : box[0];
miny = box[1] > box[3] ? box[3] - 1 : box[1] - 1;
maxy = box[1] < box[3] ? box[3] : box[1];
if ((poi[0] > minx)*(poi[0] < maxx)*(poi[1] > miny)*(poi[1] < maxy)) {
return 1;
}
return 0;
}
int main() {
int mix = 1000, miy=1000, max = 0, may=0, re=0, st=0;
int points[4][4] = { {1,2,4,4},{2,3,5,7},{3,1,6,5},{7,3,8,6} };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
mix = mix < points[i][2 * j] ? mix : points[i][2 * j];
miy = miy < points[i][2 * j+1] ? miy : points[i][2 * j+1];
max = max > points[i][2 * j ] ? max : points[i][2 * j ];
may = may > points[i][2 * j+1] ? may : points[i][2 * j+1];
}
}
for (int i = mix; i < max; i++) {
for (int j = miy; j < may; j++) {
st = 1;
for (int k = 0; k < 4; k++) {
if (inn(i,j, points[k]) *st) {
re = re + 1;
st = 0;
}
}
}
}
printf("%d", re);
return 0;
}
def main():
arr = [[1,2,3,4], [2,3,5,7], [3,1,6,5], [7,3,8,6]]
draw_arr = {}
for i in range(4):
x1, y1, x2, y2 = arr[i]
for x in range(x1,x2):
for y in range(y1,y2):
draw_arr[(x,y)] = 1
print(len(draw_arr))
main()
/* Four Boxes */
package main
import "fmt"
var grid [1001][1001]bool
func main() {
var x1, y1, x2, y2 int
for line := 1; line <= 4; line++ {
fmt.Scanf("%d %d %d %d\n", &x1, &y1, &x2, &y2)
draw(x1, y1, x2, y2)
}
fmt.Println(area())
}
func draw(x1, y1, x2, y2 int) {
for y := y1; y < y2; y++ {
for x := x1; x < x2; x++ {
grid[y][x] = true
}
}
}
func area() int {
count := 0
for y := 0; y <= 1000; y++ {
for x := 0; x <= 1000; x++ {
if grid[y][x] == true {
count++
}
}
}
return count
}
Swift입니다. 사각형의 한 칸을 넓이 1로 보고, 각 칸의 위치를 문자열로 Set에 더한 후, Set의 크기를 이용해서 넓이를 구했습니다.
import Foundation
var input = [[1,2,4,4], [2,3,5,7], [3,1,6,5], [7,3,8,6]]
var map: Set<String> = []
func drawRect(_ x: Int, _ y: Int, _ x2: Int, _ y2: Int) {
for i in y..<y2 {
for j in x..<x2 {
map.insert("\(i)_\(j)")
}
}
}
for rect in input {
drawRect(rect[0], rect[1], rect[2], rect[3])
}
print(map.count)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
public class FourBoxes {
public static void main(String[] args) throws FileNotFoundException {
Integer[][] round = new Integer[1000][1000];
Integer[][] points = new Integer[4][4];
String path = FourBoxes.class.getResource("").getPath();
Scanner sc = new Scanner(new File(path + "FourBoxes.txt"));
IntStream.range(0, 1000).forEach(i -> Arrays.fill(round[i], 0));
IntStream.range(0, 4).forEach(i -> IntStream.range(0, 4).forEach(j -> points[i][j] = sc.nextInt()));
IntStream.range(0, 4).forEach(i -> IntStream.range(points[i][0], points[i][2]).forEach(j -> IntStream.range(points[i][1], points[i][3]).forEach(k -> round[k][j] = 1)));
System.out.println(Arrays.stream(round).flatMap(x -> Arrays.stream(x)).filter(i -> i == 1).count());
}
}
def capa(mylist) :
boxlist = []
for i in mylist :
for x in range(i[0],i[2]):
for y in range(i[1],i[3]):
boxlist.append("({0},{1})".format(x,y))
boxset = set(boxlist)
return len(boxset)
print(capa([[1,2,4,4],[2,3,5,7],[3,1,6,5],[7,3,8,6]]))
public class FourBoxes {
public static void main(String[] args) {
int[][] input = { { 1, 2, 4, 4 }, { 2, 3, 5, 7 }, { 3, 1, 6, 5 }, { 7, 3, 8, 6 } };
int size[] = new int[4];
for (int i = 0; i < size.length; i++) {
if (i <= size.length / 2 - 1) {
size[i] = 100;
} else if (i > size.length / 2 - 1) {
size[i] = 0;
}
}
for (int i = 0; i < size.length; i++) {
for (int j = 0; j < size.length; j++) {
if (j <= size.length / 2 - 1) {
if (size[j] > input[i][j]) {
size[j] = input[i][j];
}
} else if (j > size.length / 2 - 1) {
if (size[j] < input[i][j]) {
size[j] = input[i][j];
}
}
}
}
int[][] area = new int[size[2]][size[3]];
for (int k = 0; k < 4; k++) {
for (int i = 0; i < input[k][2]; i++) {
for (int j = 0; j < input[k][3]; j++) {
if (i >= input[k][0] && j >= input[k][1]) {
area[i][j] += 1;
}
}
}
}
int count = 0;
for (int i = 0; i < size[2]; i++) {
for (int j = 0; j < size[3]; j++) {
System.out.print(area[i][j]);
if (area[i][j] > 0) {
count++;
}
}
System.out.println();
}
System.out.println();
System.out.println(count);
}
}
#include<iostream>
#include"stdafx.h"
class square
{
private:
int x1, y1, x2, y2;
public:
square() { x1 = 0, y1 = 0, x2 = 0, y2 = 0; }
friend istream& operator>>(istream& is, square& my_square);
friend ostream& operator<<(ostream& os, square& my_square);
void board_size(square sq[])
{
x1 = sq[0].x1, y1 = sq[0].y1;
x2 = sq[0].x2, y2 = sq[0].y2;
for (int i = 1; i < 4; i++)
{
x1 = min(x1, sq[i].x1);
y1= min(y1, sq[i].y1);
x2 = max(x2, sq[i].x2);
y2 = max(y2, sq[i].y2);
}
}
int return_x() { return x2; }
int return_y() { return y2; }
void Cal(int ** board,int &size)
{
for (int i = y1; i < y2; i++)
{
for (int j = x1; j < x2; j++)
{
if (board[i][j] == 0)
board[i][j] = 1, size++;
else continue;
}
}
}
};
istream& operator>>(istream& is, square& my_suqare)
{
cin >> my_suqare.x1 >> my_suqare.y1 >> my_suqare.x2 >> my_suqare.y2;
return is;
}
ostream& operator<<(ostream& os, square& my_square)
{
cout << my_square.x1 << " " << my_square.y1 << " " << my_square.x2 << " " << my_square.y2 << endl;
return os;
}
int main()
{
square sq[4], temp_board;
cin >> sq[0] >> sq[1] >> sq[2] >> sq[3];
temp_board.board_size(sq);
int x_size = temp_board.return_x();
int y_size = temp_board.return_y();
int **board;
int size=0;
board = new int*[y_size];
for (int i = 0; i < y_size; i++)
board[i] = new int[x_size];
for (int i = 0; i < y_size; i++)
for (int j = 0; j < x_size; j++)
board[i][j] = 0;
for (int i = 0; i < 4; i++)
{
sq[i].Cal(board,size);
for (int i = 0; i < y_size; i++)
{
for (int j = 0; j < x_size; j++)
{
cout << board[i][j];
}
cout << endl;
}
}
for (int i = 0; i < y_size; i++)
delete[] * (board);
delete[] board;
cout << size << endl;
}
커찮아서 입력시 예외처리 안했습니다. 원하시면 연산자 오버로딩 쪽에다가 하시면 될것같네요
Python
import numpy as np
x = np.zeros(shape=[4, 2])
y = np.zeros(shape=[4, 2])
for i in range(4):
x1, y1, x2, y2 = map(int, input().split(' '))
x[i][0] = x1; x[i][1] = x2;
y[i][0] = y1; y[i][1] = y2;
x1_min = np.min(x, axis=0)[0]
x2_max = np.max(x, axis=0)[1]
y1_min = np.min(y, axis=0)[0]
y2_max = np.max(y, axis=0)[1]
ans = 0
for i in range(int(x1_min), int(x2_max)):
tmp_i = i + 0.5
for j in range(int(y1_min), int(y2_max)):
tmp_j = j + 0.5
#print(tmp_i, tmp_j)
if any([True if k1 < tmp_i < k2 and k3 < tmp_j < k4 else False for k1, k2, k3, k4 in np.hstack([x, y])]):
ans += 1
#print(tmp_i, tmp_j)
print(ans)
using System;
using System.Linq;
namespace CD010
{
class Program
{
static void Main(string[] args)
{
Box box;
while (true)
{
var input = Console.ReadLine(); // input x1 y1 x2 y2
if (input.Trim() == "") // enter to print area
{
Console.WriteLine(Box.Area());
break;
}
box = new Box(input);
}
}
}
class Box
{
static bool[,] Grid = new bool[1001, 1001]; // initialize with false
public Box(string Coord)
{
var cnv = Coord.Split().Select(s => int.Parse(s)).ToArray();
for (int y = cnv[1]; y < cnv[3]; y++) // y1, y2
{
for (int x = cnv[0]; x < cnv[2]; x++) // x1, x2
{
Grid[y, x] = true;
}
}
}
public static int Area()
{
int count = 0;
foreach (var cell in Grid)
{
if (cell) count++;
}
return count;
}
}
}
파이썬 3:
rs = [[1,2,4,4],[2,3,5,7],[3,1,6,5],[7,3,8,6]]
min_x = min(c[0] for c in rs)
min_y = min(c[1] for c in rs)
max_x = max(c[2] for c in rs)
max_y = max(c[3] for c in rs)
area_count = 0
for x in range(min_x, max_x):
x += 0.5
for y in range(min_y, max_y):
y += 0.5
for i in range(len(rs)):
if (x > rs[i][0] and x < rs[i][2]) and (y > rs[i][1] and y < rs[i][3]):
area_count += 1
print(area_count)
class Program
{
//<input>
//1 2 4 4
//2 3 5 7
//3 1 6 5
//7 3 8 6
static int TotalCnt = 0;
static void Main(string[] args)
{
CoordInate coordinate = new CoordInate();
string[] strInput = Console.ReadLine().Split(' ');
coordinate.calc(strInput, TotalCnt++);
string[] strInput1 = Console.ReadLine().Split(' ');
coordinate.calc(strInput1, TotalCnt++);
string[] strInput2 = Console.ReadLine().Split(' ');
coordinate.calc(strInput2, TotalCnt++);
string[] strInput3 = Console.ReadLine().Split(' ');
coordinate.calc(strInput3, TotalCnt++);
}
}
class CoordInate
{
bool[,] bCoordinate = new bool[10, 10];
int nFst, nSec, nTrd, nFur;
int nCnt = 0;
public void calc(string[] input, int nTotalCnt)
{
nFst = int.Parse(input[0]);
nSec = int.Parse(input[1]);
nTrd = int.Parse(input[2]);
nFur = int.Parse(input[3]);
for (int i = nFst; i < nTrd; i++)
{
for (int j = nSec; j < nFur; j++)
{
bCoordinate[i, j] = true;
}
}
if (nTotalCnt >= 3)
{
for (int i = 0; i < bCoordinate.GetLength(0); i++)
{
for (int j = 0; j < bCoordinate.GetLength(1); j++)
{
if (bCoordinate[i, j])
{
nCnt++;
}
}
}
Console.WriteLine(nCnt.ToString());
}
}
}
#좌표는 list로 표현된다
#rec은 직사각형을 표현하는 객체이다
class rec:
def __init__(self, x1, y1, x2, y2):
self.left_down = [x1, y1]
self.right_up = [x2, y2]
def set_position(self, x1, y1, x2, y2):
self.left_down = [x1, y1]
self.right_up = [x2, y2]
def get_left_down(self):
return self.left_down
def get_right_up(self):
return self.right_up
def get_x1(self):
return self.left_down[0]
def get_x2(self):
return self.right_up[0]
def get_y1(self):
return self.left_down[1]
def get_y2(self):
return self.right_up[1]
#두 선분의 intersection을 구한다.
def two_line_intersection(line1, line2):
if(line1[0] > line2[0]): line1, line2 = line2, line1 #선분 sort
if(line1[1] <= line2[0]): return None #겹치지 않음
else: #겹침
if(line1[1] >= line2[1]): #포함
return line2
else: #포함은 안하지만 겹침
return [line2[0], line1[1]]
#두 사각형의 intersection을 구한다
#(x좌표끼리의 intersection) and (y좌표끼리의 intersection)
def two_rec_intersection(rec1, rec2):
#x좌표끼리의 intersection 구하기
x_line1 = [rec1.get_x1(), rec1.get_x2()]
x_line2 = [rec2.get_x1(), rec2.get_x2()]
x_result = two_line_intersection(x_line1, x_line2)
if(x_result is None): #겹치지 않음
return rec(0,0,0,0)
#y좌표끼리의 intersection 구하기
y_line1 = [rec1.get_y1(), rec1.get_y2()]
y_line2 = [rec2.get_y1(), rec2.get_y2()]
y_result = two_line_intersection(y_line1, y_line2)
if(y_result is None): #겹치지 않음
return rec(0,0,0,0)
#겹치면
return rec(x_result[0], y_result[0], x_result[1], y_result[1])
#직사각형의 넓이를 구한다
def square(rec1):
return (rec1.get_x2()-rec1.get_x1())*(rec1.get_y2()-rec1.get_y1())
#이제부터 Main
#직사각형 4개 입력
coor = list(map(int, input().split()))
rec1 = rec(coor[0], coor[1], coor[2], coor[3])
coor= list(map(int, input().split()))
rec2 = rec(coor[0], coor[1], coor[2], coor[3])
coor = list(map(int, input().split()))
rec3 = rec(coor[0], coor[1], coor[2], coor[3])
coor = list(map(int, input().split()))
rec4 = rec(coor[0], coor[1], coor[2], coor[3])
#넓이 계산
result = 0
rec1_2 = two_rec_intersection(rec1, rec2)
rec1_3 = two_rec_intersection(rec1, rec3)
rec1_4 = two_rec_intersection(rec1, rec4)
rec2_3 = two_rec_intersection(rec2, rec3)
rec2_4 = two_rec_intersection(rec2, rec4)
rec3_4 = two_rec_intersection(rec3, rec4)
rec1_2_3 = two_rec_intersection(rec1, rec2_3)
rec1_2_4 = two_rec_intersection(rec1, rec2_4)
rec1_3_4 = two_rec_intersection(rec1, rec3_4)
rec2_3_4 = two_rec_intersection(rec2, rec3_4)
rec1_2_3_4 = two_rec_intersection(rec1, rec2_3_4)
result = square(rec1) + square(rec2) + square(rec3) + square(rec4) - square(rec1_2) - square(rec1_3) - square(rec1_4) - square(rec2_3) - square(rec2_4) - square(rec3_4) + square(rec1_2_3) + square(rec1_2_4) + square(rec1_3_4) + square(rec2_3_4) - square(rec1_2_3_4)
print(result)
res = [[0]*99 for i in range(99)]
x=[0]*8
y=[0]*8
x[0],y[0],x[1],y[1] = map(int, input().split(' '))
x[2],y[2],x[3],y[3] = map(int, input().split(' '))
x[4],y[4],x[5],y[5] = map(int, input().split(' '))
x[6],y[6],x[7],y[7] = map(int, input().split(' '))
s_range=[0,2,4,6]
s_sum=0
for k in s_range:
for i in range(x[k+1]-x[k]):
for j in range(y[k+1]-y[k]):
res[y[k]+j][x[k]+i]=1
for i in range(99):
s_sum+=sum(res[i])
print(s_sum)
#include <stdio.h>
typedef struct box
{
int x1,y1,x2,y2;
} Box;
int max(int *arr)
{
int i,result;
result=0;
for(i=0;i<4;i++)
if (result<arr[i]) result = arr[i];
return result;
}
int min(int *arr)
{
int i,result;
result=arr[0];
for(i=1;i<4;i++)
if (result>arr[i]) result = arr[i];
return result;
}
int isin(int *arr, int size, int x)
{
int i;
for(i=0;i<8;i++)
if (arr[i]==x) return 1;
return 0;
}
int main()
{
int xs[8], ys[8];
Box boxes[4];
int i,a,b,c,d;
for(i=0;i<4;i++)
{
scanf("%d %d %d %d", &a, &b, &c, &d);
boxes[i].x1 = a;
xs[2*i]=a;
boxes[i].y1 = b;
ys[2*i]=b;
boxes[i].x2 = c;
xs[2*i+1]=c;
boxes[i].y2 = d;
ys[2*i+1]=d;
}
int unit_num;
int size;
size = (max(xs)-min(xs))*(max(ys)-min(ys));
int units[size];
int k,j,temp;
for(k=0;k<4;k++)
{
for(i=boxes[k].x1;i<boxes[k].x2;i++)
{
for(j=boxes[k].y1;j<boxes[k].y2;j++)
{
temp = (i+j)*(i+j-1)/2+j+1;
if (!isin(units, size, temp)) units[unit_num++]=temp;
}
}
}
printf("%d\n", unit_num);
return 0;
}
김슈타인님 풀이를 복붙했습니다. 혹시라도 참고하실까봐 적어놓습니다.
#include <cstdio>
typedef struct point {
int xpos;
int ypos;
}Point;
typedef struct rectangle {
Point pos[2]; // 왼쪽 꼭지점과 오른쪽 꼭지점
}Rectangle;
int arr[1000][1000]; // 도화지
int main() {
Rectangle rec[4]; // 직사각형
int num; // n번째 직사각형
int area = 0; // 넓이
int k = 0;
for (int i = 0; i < 4; i++) { // 4개의 직사각형의
for (int j = 0; j < 2; j++) // 좌우 꼭지점의 좌표입력받기
scanf("%d %d", &rec[i].pos[j].xpos, &rec[i].pos[j].ypos);
}
// 4개의 직사각형의
// 왼쪽꼭지점의 x좌표부터 오른쪽꼭지점의 x좌표까지
// 왼쪽꼭지점의 y좌표부터 오른쪽꼭지점의 y좌표까지
for (num = 0; num < 4; num++) {
for (int i = rec[num].pos[k].xpos; i < rec[num].pos[k + 1].xpos; i++) {
for (int j = rec[num].pos[k].ypos; j < rec[num].pos[k + 1].ypos; j++) {
arr[i][j] = 1;
}
}
}
// 도화지를 순회하며 넓이 체크
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (arr[i][j] == 1) area++;
}
}
printf("넓이 : %d\n", area);
return 0;
}
white <- matrix(0, nrow = 1000, ncol = 1000)
rectangle <- function(x, white){
coord <- x
white[(coord[1]):(coord[3] - 1), (coord[2]):(coord[4] - 1)] <- 1
return(white)
}
input_coord <- matrix(c(1, 2, 4, 4,
2, 3, 5, 7,
3, 1, 6, 5,
7, 3, 8, 6), ncol = 4, byrow = T)
for (i in 1:nrow(input_coord)){
white <- rectangle(input_coord[i, ], white)
}
sum(white)
loc,fl = [],set()
for x in range(4):
loc.append(input().split())
for t in loc:
for x in range(int(t[0]),int(t[2])):
for y in range(int(t[1]),int(t[3])):
fl.add(str(x)+str(y))
print(len(fl))
area_box = []
def area(no1,no2,no3,no4):
for i in range(no1,no3):
for j in range(no2,no4):
area_box.append((i,j))
for i in range(4):
box_pts = input()
no1,no2,no3,no4 = box_pts.split(' ')
area(int(no1),int(no2),int(no3),int(no4))
len(set(area_box))
package problem10;
import java.util.Scanner;
public class solution {
public static void main(String[] args) {
int[] x_arr = new int [8];
int[] y_arr = new int [8];
Scanner scan = new Scanner(System.in);
System.out.println("첫번째 사각형의 좌표를 입력해주세요(x1, y1 , x2, y2)");
x_arr[0] = scan.nextInt();
y_arr[0] = scan.nextInt();
x_arr[1] = scan.nextInt();
y_arr[1] = scan.nextInt();
System.out.println("두번째 사각형의 좌표를 입력해주세요(x3, y3 , x4, y4)");
x_arr[2] = scan.nextInt();
y_arr[2] = scan.nextInt();
x_arr[3] = scan.nextInt();
y_arr[3] = scan.nextInt();
System.out.println("세번째 사각형의 좌표를 입력해주세요(x5, y5 , x6, y6)");
x_arr[4] = scan.nextInt();
y_arr[4] = scan.nextInt();
x_arr[5] = scan.nextInt();
y_arr[5] = scan.nextInt();
System.out.println("네번째 사각형의 좌표를 입력해주세요(x7, y7 , x8, y8)");
x_arr[6] = scan.nextInt();
y_arr[6] = scan.nextInt();
x_arr[7] = scan.nextInt();
y_arr[7] = scan.nextInt();
// 배열 생성을 위한 x, y중 최대값 출력
int x_max =x_arr[0];
int y_max =y_arr[0];
for(int i=1 ; i < x_arr.length; i++) {
if(x_max < x_arr[i]) {
x_max = x_arr[i];
}
}
for(int i=1 ; i < y_arr.length; i++) {
if(y_max < y_arr[i]) {
y_max = y_arr[i];
}
}
int[][] matrix = new int[x_max][y_max];
for(int i=0; i < y_max; i++) {
for(int j=0; j < x_max; j++) {
matrix[j][i]=0;
}
}
// 첫번째 사각형을 배열의 값을 1로 치환
for(int i= x_arr[0] ; i< x_arr[1]; i++ ) { //x축
for(int j= y_arr[0] ; j < y_arr[1] ; j++ ) { //y축
matrix[i][j] = 1;
}
}
// 두번째 사각형을 배열의 값을 1로 치환
for(int i= x_arr[2] ; i< x_arr[3]; i++ ) { //x축
for(int j= y_arr[2] ; j < y_arr[3] ; j++ ) { //y축
matrix[i][j] = 1;
}
}
// 세번째 사각형을 배열의 값을 1로 치환
for(int i= x_arr[4] ; i< x_arr[5]; i++ ) { //x축
for(int j= y_arr[4] ; j < y_arr[5] ; j++ ) { //y축
matrix[i][j] = 1;
}
}
// 네번째 사각형을 배열의 값을 1로 치환
for(int i= x_arr[6] ; i< x_arr[7]; i++ ) { //x축
for(int j= y_arr[6] ; j < y_arr[7] ; j++ ) { //y축
matrix[i][j] = 1;
}
}
int area = 0;
for(int j=0; j < y_max; j++) {
for(int i=0; i < x_max; i++) {
if(matrix[i][j]==1) {
area+=matrix[i][j];
}
}
}
System.out.println("넓이는 "+area+" 입니다.");
}
}
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main() {
vector< vector<int> > input = { {1,2,4,4},{2,3,5,7},{3,1,6,5},{7,3,8,6} };
int area = 0;
int max_x = 0, max_y = 0;
for (vector<int> iter : input) {
for (int i = 2; i < 4; i++) {
if (i % 2 == 0) {
if (max_x < iter[i]) max_x = iter[i];
}
else {
if (max_y < iter[i]) max_y = iter[i];
}
}
}
char **matrix = new char*[max_x + 1];
for (int x = 0; x < max_x + 1; x++) matrix[x] = new char[max_y + 1];
for (int i = 0; i < max_x + 1; i++) for (int j = 0; j < max_y + 1; j++) matrix[i][j] = 0;
for (vector<int> iter : input) {
for (int i = (iter[0]); i < iter[2]; i++) for (int j = iter[1]; j < iter[3]; j++) matrix[i][j] = 1;
}
for (int i = 0; i < max_x + 1; i++) for (int j = 0; j < max_y + 1; j++) if(matrix[i][j]) area++;
cout << area;
return 0;
}
result = []
for i in range(1, 5) :
globals()['POINTS{}'.format(i)] = input("INPUT : ").split(" ")
for s in range(int(globals()['POINTS{}'.format(i)][1]), int(globals()['POINTS{}'.format(i)][3])) :
for k in range(int(globals()['POINTS{}'.format(i)][0]), int(globals()['POINTS{}'.format(i)][2])) :
if not (str(k), str(s)) in result :
result.append((str(k), str(s)))
else :
continue
print(len(result))
왼쪽 아래 꼭지점을 기준으로한 변 1의 정사각형의 개수를 세는 식으로 계산했습니다. 결과
INPUT : 1 2 4 4
INPUT : 2 3 5 7
INPUT : 3 1 6 5
INPUT : 7 3 8 6
26
만든 김에, 원하는 박스의 개수만큼 계산하는 코드도 만들어봤습니다.
TNoB = int(input("The numbers of boxes : "))
result = []
for i in range(1, TNoB+1) :
globals()['POINTS{}'.format(i)] = input("INPUT : ").split(" ")
for s in range(int(globals()['POINTS{}'.format(i)][1]), int(globals()['POINTS{}'.format(i)][3])) :
for k in range(int(globals()['POINTS{}'.format(i)][0]), int(globals()['POINTS{}'.format(i)][2])) :
if not (str(k), str(s)) in result :
result.append((str(k), str(s)))
else :
continue
print(len(result))
결과
The numbers of boxes : 5
INPUT : 1 2 4 4
INPUT : 2 3 5 7
INPUT : 3 1 6 5
INPUT : 7 3 8 6
INPUT : 8 8 10 10
30
Javascript(ES6)...
`평면을 나타내는 배열 canvas 정의하고 내부를 0 으로 채움, 사각형에 해당하는 영역을 좌표에 맞춰 canvas 안에 숫자 1 로 채움, 면적을 구할 땐 1 이 들어간 요소의 개수 혹은 모든 요소들의 합으로 구함`;
class CustomCanvas {
constructor() {
this.canvas = Array.from(Array(10), () => Array(10).fill(0));
}
// 사각형 추가 함수, 체이닝을 위해 this 리턴
add_rect(lx, ly, rx, ry) {
for(let x = lx; x < rx; x++) {
for(let y = ly; y < ry; y++) {
this.canvas[x][y] = 1;
}
}
return this;
}
// 넓이 출력 함수, canvas 배열 안 모든 요소의 합계로 넓이를 구함
print_area() {
// self executive 재귀 함수로 구현
let area = (function sumarr(arr) {
let result = 0;
for(let v of arr) {
if(Array.isArray(v)) { result += sumarr(v); } else { result += v; }
}
return result;
})(this.canvas);
console.log(area);
}
}
new CustomCanvas().add_rect(1, 2, 4, 4).add_rect(2, 3, 5, 7).add_rect(3, 1, 6, 5).add_rect(7, 3, 8, 6).print_area(); // 26
Python 3...
class Canvas:
def __init__(self, canvas = None):
self.canvas = canvas if canvas is not None else [x[:] for x in [[0] * 1000] * 1000]
# 주어진 사각형을 캔버스에 추가
def add_rect(self, lx, ly, rx, ry):
for x in range(lx, rx):
for y in range(ly, ry):
self.canvas[x][y] = 1
return self
# 넓이 출력 함수, canvas 배열 안 모든 요소의 합계로 넓이를 구함
def print_area(self):
area = sum(sum(x) for x in self.canvas)
print(area)
Canvas().add_rect(1, 2, 4, 4).add_rect(2, 3, 5, 7).add_rect(3, 1, 6, 5).add_rect(7, 3, 8, 6).print_area() # 26
#include <iostream>
#include <vector>
#include <ctime>
#define SIZE 1000
/*
4개의 직사각형이 평면에 있는데 밑변이 모두 가로축에 평행하다. 이 직사각형들이 차지하는 면적을 구하는 프로그램을 작성하시오.
이 네 개의 직사각형들은 서로 떨어져 있을 수도 있고 겹쳐 있을 수도 있다.
또한 하나가 다른 하나를 포함할 수도 있으며, 변이나 꼭지점이 겹쳐질 수도 있다.
입력형식:
하나의 직사각형은 왼쪽 아래의 꼭지점과 오른쪽 위의 꼭지점의 좌표로 주어진다.
입력은 네 줄이며, 각 줄은 네 개의 정수로 하나의 직사각형을 나타낸다.
첫 번째와 두 번째의 정수는 사각형의 왼쪽 아래 꼭지점의 x좌표, y좌표이고,
세 번째와 네 번째의 정수는 사각형의 오른쪽 위 꼭지점의 x좌표, y좌표이다.
단, x좌표와 y좌표는 1 이상이고 1000 이하인 정수이다.
출력형식:
화면에 4개의 직사각형이 차지하는 면적을 출력한다.
입력예제:
1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6
출력예제:
26
*/
using namespace std;
struct Pos {
int x, y;
Pos(int x_, int y_) :x(x_), y(y_){ }
};
void Func(int **arr, vector<pair<Pos, Pos>> &v) {
int count = 0;
for (int i = 0; i < v.size(); i++) {
for (int j = v[i].first.y; j < v[i].second.y; j++) {
for (int k = v[i].first.x; k < v[i].second.x; k++) {
arr[j][k] = 1;
}
}
}
for(int i=0; i<SIZE; i++)
for (int j = 0; j < SIZE; j++) {
if (arr[i][j] == 1) { count++; }
}
cout << "4개의 사각형의 넓이는:" << count << endl;
}
int main() {
clock_t s, e;
s = clock();
int **arr = new int*[SIZE];
for (int i = 0; i < SIZE; i++)
arr[i] = new int[SIZE];
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
arr[i][j] = 0;
vector<pair<Pos, Pos>> v;
v.push_back(make_pair(Pos(1, 2), Pos(4, 4)));//예제의경우
v.push_back(make_pair(Pos(2, 3), Pos(5, 7)));//예제의경우
v.push_back(make_pair(Pos(3, 1), Pos(6, 5)));//예제의경우
v.push_back(make_pair(Pos(7, 3), Pos(8, 6)));//예제의경우
Func(arr, v);
for (int i = 0; i < SIZE; i++)
delete[] arr[i];
delete[] arr;
e = clock();
clock_t mr = e - s;
double result = (double)(mr / CLOCKS_PER_SEC);
cout << "수행시간:" << result << "s" <<"("<<mr<<"ms)"<<endl;
}
def square_area(points):
base = [[0]*10 for _ in range(10)]
for n, s in enumerate(points):
for i in range(s[1], s[3]):
for j in range(s[0], s[2]):
base[i][j] = n + 1
sum_area = sum(i > 0 for x in base for i in x)
print(sum_area)
if __name__ == '__main__':
points = [(1, 2, 4, 4), (2, 3, 5, 7), (3, 1, 6, 5), (7, 3, 8, 6)]
square_area(points)
import java.util.*;
public class a {
public static void Width(int[][] num){
ArrayList<Integer[]> list = new ArrayList<Integer[]>();
HashSet<String> set = new HashSet<String>();
for(int i=0;i<4;i++){
int x1 = num[i][0];
int y1 = num[i][1];
int x2 = num[i][2];
int y2 = num[i][3];
int [] x_num = new int[x2-x1];
int [] y_num = new int[y2-y1];
for(int j=0;j<x2-x1;j++){
x_num[j] = j+x1;
}
for(int k=0;k<y2-y1;k++){
y_num[k] = k+y1;
}
for(int b=0;b < x_num.length;b++){
for(int c=0;c < y_num.length;c++){
list.add(new Integer[] {x_num[b],y_num[c]});
}
}
}
for(int i=0;i<list.size();i++){
int xx = (list.get(i)[0]);
int yy = (list.get(i)[1]);
String zz = String.valueOf(xx)+String.valueOf(yy);
set.add(zz);
}
System.out.println(set);
System.out.println(set.size()); // set의 size가 넓이가 된다
}
public static void main(String[] args){
int [][] rectangles = {{1,2,4,4}, {2,3,5,7}, {3,1,6,5}, {7,3,8,6}};
Width(rectangles);
}
}
inp="""1244
2357
3165
7386"""
lst=[list(ln) for ln in inp.split("\n")]
s1=set()
def square(lx, ly, rx, ry):
for x in range(lx, rx):
for y in range(ly, ry):
s1.add((x,y))
for ln in lst:
x1,y1,x2,y2=ln
square(int(x1),int(y1),int(x2),int(y2))
print(len(s1))
답
26
matrix룰 만들고 0으로 초기화를 시켜줍니다. 구조체 Point를 만들고 4개의 int를 만들어주고 입력을 받습니다. mark라는 함수를 만들어 Point안에 있는 값들을 검사하여 직사각형 안에 있으면 해당하는 matrix 값을 1로 만들어주고 main함수에서 matrix안에 있는 1의 값들의 합을 계산하여 만들어줍니다. 여기에는 Point를 만들어줄 때 0<a<x, 0<b<y 등의 조건들을 포함하지 않았습니다.
추가한 기능으로서는 직사각형을 4개뿐만 아니라 N개를 만들 수 있게 한 것이며 맨 처음에 사각형의 갯수를 기입하시면 됩니다.
#include <iostream>
using namespace std;
int matrix[1000][1000] ={0,};
typedef struct Point {
int a;
int b;
int x;
int y;
} Point;
void mark(const Point&);
int main() {
int N;
cin >> N;
Point* points = new Point[N];
for(int i =0;i<N;i++) {
cin >> points[N].a >> points[N].b;
cin >> points[N].x >> points[N].y;
mark(points[N]);
}
int count=0;
for(int i =0;i<1000;i++) {
for(int j=0;j<1000;j++) {
if(matrix[i][j]==1) count++;
}
}
cout << count << endl;
return 0;
}
void mark(const Point& point) {
for(int i =0;i<point.x-point.a;i++) {
for(int j=0;j<point.y-point.b;j++) {
matrix[point.a+i][point.b+j]=1;
}
}
}
inp = [list(map(int, input().split())) for _ in range(4)]
def four_boxes(l):
dots = []
for i in l: # [1,2,4,4]
for x in range(i[0], i[2]):
for y in range(i[1], i[3]):
dots.append([x, y])
result = []
for i in dots:
if i in result:
pass
else:
result.append(i)
return len(result)
if __name__ == '__main__':
print(four_boxes(inp))
from itertools import product
from itertools import combinations
ax1,ay1,ax2,ay2 = map(int,input("좌표 : ").split())
bx1,by1,bx2,by2 = map(int,input("좌표 : ").split())
cx1,cy1,cx2,cy2 = map(int,input("좌표 : ").split())
dx1,dy1,dx2,dy2 = map(int,input("좌표 : ").split())
ax = set(list(range(ax1,ax2+1))) #각각의 좌표의 최소 최댓값
ay = set(list(range(ay1,ay2+1)))
bx = set(list(range(bx1,bx2+1)))
by = set(list(range(by1,by2+1)))
cx = set(list(range(cx1,cx2+1)))
cy = set(list(range(cy1,cy2+1)))
dx = set(list(range(dx1,dx2+1)))
dy = set(list(range(dy1,dy2+1)))
SA = (max(ax)-min(ax))*(max(ay)-min(ay)) # 각각의 넓이
SB = (max(bx)-min(bx))*(max(by)-min(by))
SC = (max(cx)-min(cx))*(max(cy)-min(cy))
SD = (max(dx)-min(dx))*(max(dy)-min(dy))
total = SA+SB+SC+SD # 겹쳐지든 상관없이 모든 사각형 넓이를 더한다.
X=[ax,bx,cx,dx]
Y=[ay,by,cy,dy]
G = list((combinations(X,2)))
W = list((combinations(Y,2)))
E = list((combinations(X,3)))
R = list((combinations(Y,3)))
for i,q in zip(range(len(G)),range(len(W))): #0~5까지 총 6회 반복
try:
(max(list(G[i])[0]&list(G[i])[1])-min(list(G[i])[0]&list(G[i])[1]))*(max(list(W[i])[0]&list(W[i])[1])-min(list(W[i])[0]&list(W[i])[1]))
except:
pass
else:
total-=((max(list(G[i])[0]&list(G[i])[1])-min(list(G[i])[0]&list(G[i])[1]))*(max(list(W[i])[0]&list(W[i])[1])-min(list(W[i])[0]&list(W[i])[1])))
for j,k in zip(range(len(E)),range(len(R))):
try:
(max(list(E[j])[0]&list(E[j])[1]&list(E[j])[2])-min(list(E[j])[0]&list(E[j])[1]&list(E[j])[2]))*(max(list(R[k])[0]&list(R[k])[1]&list(R[k])[2])-min(list(R[k])[0]&list(R[k])[1]&list(R[k])[2]))
except:
pass
else:
total+=((max(list(E[j])[0]&list(E[j])[1]&list(E[j])[2])-min(list(E[j])[0]&list(E[j])[1]&list(E[j])[2]))*(max(list(R[k])[0]&list(R[k])[1]&list(R[k])[2])-min(list(R[k])[0]&list(R[k])[1]&list(R[k])[2])))
try:
(max(ax&bx&cx&dx)-min(ax&bx&cx&dx))*(max(ax&by&cy&dy)-min(ay&by&cy&dy))
except:
pass
else:
total-=(max(ax&bx&cx&dx)-min(ax&bx&cx&dx))*(max(ax&by&cy&dy)-min(ay&by&cy&dy))
print(total)
해결법은 한참전에 알았는데 코드로 옮기는게 오래걸렸네요.,.
import sys
mod = sys.modules[__name__]
for i in range(4):
setattr(mod, 'x_1{}'.format(i+1),int(input("{}번째 직사각형의 왼쪽 아래 x좌표: ".format(i+1))))
setattr(mod, 'x_2{}'.format(i+1),int(input("{}번째 직사각형의 오른쪽 위 x좌표: ".format(i+1))))
setattr(mod, 'y_1{}'.format(i+1),int(input("{}번째 직사각형의 왼쪽 아래 y좌표: ".format(i+1))))
setattr(mod, 'y_2{}'.format(i+1),int(input("{}번째 직사각형의 오른쪽 위 y좌표: ".format(i+1))))
print("입력값들")
print("="*50)
print(str(x_11)+" "+str(y_11)+" "+str(x_21)+" "+str(y_21))
print(str(x_12)+" "+str(y_12)+" "+str(x_22)+" "+str(y_22))
print(str(x_13)+" "+str(y_13)+" "+str(x_23)+" "+str(y_23))
print(str(x_14)+" "+str(y_14)+" "+str(x_24)+" "+str(y_24))
print("="*50)
count=0
x_values=[x_11,x_12,x_13,x_14,x_21,x_22,x_23,x_24]
y_values=[y_11,y_12,y_13,y_14,y_21,y_22,y_23,y_24]
for i in range(min(x_values),max(x_values)):
for j in range(min(y_values),max(y_values)):
if (x_11<i+0.5<x_21 and y_11<j+0.5<y_21) or\
(x_12<i+0.5<x_22 and y_12<j+0.5<y_22) or\
(x_13<i+0.5<x_23 and y_11<j+0.5<y_21) or\
(x_14<i+0.5<x_24 and y_12<j+0.5<y_22):
count+=1
print("총 넓이" + str(count))
최대한 직관적으로 코드를 작성해 보았습니다
# 1. 두 사각형의 겹치는지 판단하는 함수
def inter (a,b):
arr_ax = [i for i in range(a[0],a[2]+1)]
arr_ay = [i for i in range(a[1],a[3]+1)]
arr_bx = [i for i in range(b[0],b[2]+1)]
arr_by = [i for i in range(b[1],b[3]+1)]
if len(set(arr_ax) & set(arr_bx))>1 and len(set(arr_ay) & set(arr_by))>1:
return True
else:
False
# 2. 1을 활용하여 사각형이 겹치면, 겹치는 영역의 좌표를 반환 & 안겹치면 0,0,0,0 을 반환
def intersection (a,b):
if inter(a,b):
if a[0]>=b[0]: x1=a[0]
else: x1=b[0]
if a[1]>=b[1]: y1=a[1]
else: y1=b[1]
if a[2]>=b[2]: x2=b[2]
else: x2=a[2]
if a[3]>=b[3]: y2=b[3]
else: y2=a[3]
else:
x1=y1=x2=y2=0
arr=[x1,y1,x2,y2]
return arr
#3. 사각형의 넓이를 구하는 함수
def area (arr):
return (abs(arr[2]-arr[0]))*(abs(arr[3]-arr[1]))
#4. 네 사각형의 꼭지점을 입력 받는 함수
arr= []
for i in range(4):
while True:
print(i+1,'번째',end='')
n = list(map(int,input('직사각형의 꼭지점을 차례로 입력하시오:').split(" ")))
if min(n)>=1 and max(n)<=1000:
arr.append(n)
break
#5. 2번함수를 이용하여, 네 사각형의 총 면적을 구하는 함수(집합의 합집합 활용)
def total_area (arr):
A = arr[0]
B = arr[1]
C = arr[2]
D = arr[3]
AB = intersection(A,B)
AC = intersection(A,C)
AD = intersection(A,D)
BC = intersection(B,C)
BD = intersection(B,D)
CD = intersection(C,D)
ABC = intersection(AB,C)
ABD = intersection(AB,D)
BCD = intersection(BC,D)
ACD = intersection(AC,D)
ABCD = intersection(ABC,D)
result1 = area(A)+area(B)+area(C)+area(D)
result2 = area(AB)+area(AC)+area(AD)+area(BC)+area(BD)+area(CD)
result3 = area(ABC)+area(ABD)+area(BCD)+area(ACD)
result4 = area(ABCD)
return result1-result2+result3+result4
print(total_area(arr))
// Rust
// interval union 함수를 만든 후, x가 가능한 범위를 구하고,
// 각 x에서 해당하는 y interval들을 구해, interval union으로 면적을 더했습니다.
// 두 직사각형의 관계가 가능한 각 경우의 수를 따지면 좀 더 멋지게 풀 수 있을것 같지만...
fn boxes() {
let input_ = "1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6";
let mut input = vec![];
for line in input_.lines() {
let lvec: Vec<usize> = line.trim().split_whitespace()
.map(|s| s.parse::<usize>().unwrap())
.collect();
input.push(lvec);
}
let mut xs = vec![];
let mut ys = vec![];
for lvec in input {
xs.push((lvec[0], lvec[2]));
ys.push((lvec[1], lvec[3]));
}
let xrange = interval_union(&xs);
let mut res = 0;
for xx in xrange { // xx = (1, 6), (7, 8)
for x in xx.0..xx.1 {
let mut yrange = vec![];
for i in 0..4 {
if xs[i].0 <= x && x < xs[i].1 { yrange.push(ys[i]);}
}
yrange = interval_union(&yrange);
for yy in yrange {
res += yy.1 - yy.0;
}
}
}
println!("{}", res);
} fn interval_union(vs_: &Vec<(usize, usize)>) -> Vec<(usize, usize)> {
let mut vs = vs_.clone();
vs.sort();
let mut i = 0;
let mut j = 1;
while i < vs.len() - 1 {
while j < vs.len() {
if vs[i].1 >= vs[j].0 {
if vs[i].1 <= vs[j].1 { vs[i].1 = vs[j].1; vs.remove(j);}
else { vs.remove(j);}
} else { j += 1;}
}
i += 1;
j = i+1;
}
vs
}
import numpy as np
import pandas as pd
inp = '''1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6'''
pts = inp.splitlines()
pl = point_list = []
for point in pts:
pl.append(list(map(int,point.split(' '))))
df = pd.DataFrame(pl)
df.columns = ['x1', 'y1', 'x2', 'y2']
x_min, x_max = min(df['x1']), max(df['x2'])
y_min, y_max = min(df['y1']), max(df['y2'])
def judge(x,y):
if [(p[0] < x+0.5 < p[2]) & (p[1] < y+0.5 < p[3]) for p in pl].count(True) > 0:
return 1
else:
return 0
cnt = 0
for x in range(x_min, x_max):
for y in range(y_min, y_max):
if judge(x,y) == 1:
cnt += 1
print(cnt)
// ** Four Boxes
import java.util.Scanner;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Comparator;
public class CalculateArea {
static ArrayList<ArrayList<Integer>> list = new ArrayList<>();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
CalculateArea calculateArea = new CalculateArea();
int numberOfRectangle;
while(true) {
System.out.print("Enter number of rectangle: ");
numberOfRectangle = scan.nextInt();
if(numberOfRectangle<1)
System.out.println("The number of rectangle is less than 1.");
else
break;
}
calculateArea.inputData(numberOfRectangle);
int[][] matrix = calculateArea.denoteArea(numberOfRectangle);
int area = calculateArea.calculateAreaOfMatrix(matrix);
System.out.printf("Total area is %d. \n", area);
}
private void inputData(int numberOfRectangle) {
for(int i=0; i<numberOfRectangle; i++) {
System.out.print("Enter the information: ");
ArrayList<Integer> newRectangle = new ArrayList<>();
for(int j=0; j<4; j++)
newRectangle.add(scan.nextInt());
list.add(newRectangle);
}
}
private int[][] denoteArea(int numberOfRectangle) {
int size_x = list.get(0).get(0);
int size_y = list.get(0).get(1);
int[][] matrix = new int[size_y][size_x];
ListIterator<ArrayList<Integer>> iter = list.listIterator();
while(iter.hasNext()) {
ArrayList<Integer> current = iter.next();
matrix = checkSizeOfMatrix(matrix, current);
for(int j=current.get(1); j<current.get(3); j++)
for(int i=current.get(0); i<current.get(2); i++)
matrix[j][i] += 1;
}
return matrix;
}
private int[][] checkSizeOfMatrix(int[][] matrix, ArrayList<Integer> current) {
int max_x = Math.max(current.get(2), matrix[0].length);
int max_y = Math.max(current.get(3), matrix.length);
int[][] newMatrix = new int[max_y][max_x];
for(int j=0; j<matrix.length; j++)
for(int i=0; i<matrix[0].length; i++)
newMatrix[j][i] = matrix[j][i];
return newMatrix;
}
private int calculateAreaOfMatrix(int [][] matrix) {
int max_y = matrix.length;
int max_x = matrix[0].length;
int area = 0;
for(int j=0; j<max_y; j++)
for(int i=0; i<max_x; i++)
if(matrix[j][i]!=0)
area++;
return area;
}
}
N개의 사각형 갯수와 사각형 갯수를 입력하면 종합 면적을 출력해줍니다.
import numpy as np
import cv2
num_box = 5
def data():
boxes = [ [0,0,0,0] for i in range(num_box)]
for i in range(num_box):
boxes[i] = list(map(int, input().split()))
return boxes # boxes = [ [x0, y0], [x1, y1], .... [x3, y3] ]
boxes = data() # boxes = [ [x0, y0], [x1, y1], .... [x3, y3] ]
max_x = 0
max_y = 0
for i in range(num_box):
max_x = max(max_x, max(boxes[i][0::2]))
max_y = max(max_y, max(boxes[i][1::2]))
box = [ [0]*max_x for _ in range(num_box)]
for i in range(num_box):
for j in range(max_y):
if j in range(boxes[i][1], boxes[i][3]):
box[i][j] = 2**(boxes[i][2]) - 2**boxes[i][0]
area_bin = [0 for _ in range(max_y)]
area = 0
for i in range(max_y):
for j in range(num_box):
area_bin[i] = area_bin[i] | box[j][i]
print(str(bin(area_bin[i] + 2 ** (max_x + 1)))[3:])
area += str(bin(area_bin[i]))[2:].count('1')
print('area = ', area)
# Plot
xN = 50
org = (50,100)
font=cv2.FONT_HERSHEY_SIMPLEX
img = np.zeros((600, 600, 3), np.uint8)
for i in range(num_box):
img = cv2.rectangle(img, (boxes[i][0]*xN, boxes[i][1]*xN), (boxes[i][2]*xN, boxes[i][3]*xN), (255, 0, 0), 1)
org1 = (boxes[i][0]*xN, boxes[i][1]*xN)
org2 = (boxes[i][0]*xN, boxes[i][3]*xN)
org3 = (boxes[i][2]*xN, boxes[i][1]*xN)
org4 = (boxes[i][2]*xN, boxes[i][3]*xN)
text1 = '({0}, {1})'.format(boxes[i][0], boxes[i][1])
text2 = '({0}, {1})'.format(boxes[i][0], boxes[i][3])
text3 = '({0}, {1})'.format(boxes[i][2], boxes[i][1])
text4 = '({0}, {1})'.format(boxes[i][2], boxes[i][3])
cv2.putText(img, text1, org1, font, 0.4, (0,0,255), 1 )
cv2.putText(img, text2, org2, font, 0.4, (0,0,255), 1 )
cv2.putText(img, text3, org3, font, 0.4, (0,0,255), 1 )
cv2.putText(img, text4, org4, font, 0.4, (0,0,255), 1 )
cv2.imshow('rectangle', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
아직 함수랑 클래스에 약해서 if문이랑 for문으로 해결해봤습니다
파이썬 독학 과정이라 힘드네요
a = [[[1,2],[4,4]],[[2,3],[5,7]],[[3,1],[6,5]],[[7,3],[8,6]]]
S = 0
for i in range(0,4):
S += abs((a[i][1][0]-a[i][0][0])*(a[i][1][1]-a[i][0][1]))
List= []
List2= []
for i in range(0,4):
a1 = list(range(min(a[i][0][0],a[i][1][0]),max(a[i][0][0],a[i][1][0])+1))
List.append(a1)
for k in range(0,4):
A1 = list(range(min(a[k][0][1],a[k][1][1]),max(a[k][0][1],a[k][1][1])+1))
List2.append(A1)
S1 = 0
for i in range(0,3):
for k in range(i,3):
if len(set(List[i]) & set(List[k+1])) != 0 and len(set(List2[i]) & set(List2[k+1])) != 0:
S1 += (len(set(List[i]) & set(List[k+1]))-1)*(len(set(List2[i]) & set(List2[k+1]))-1)
print(S-S1)
Logic은 단순하고 확실하게, 반복작업은 컴퓨터에게 ...
boxs = [[1, 2, 4, 4], [2, 3, 5, 7], [3, 1, 6, 5], [7, 3, 8, 6]]
area = 0
for x in range(1, 1001):
for y in range(1, 1001):
exist = any(x in range(ele[0], ele[2]) and y in range(ele[1], ele[3]) for ele in boxs)
if exist:
area += 1
print(area)
면적을 구하는 범위(1 <= x <= 1000, 1 <= y <= 1000)가 더 커지는 경우,
실행시간을 줄이기 위해 코딩 앞쪽에 박스 들의 Min/Max X, Y를 먼저 구하여 범위를 한정하는 코드를 추가하면 됨
inp = """1 2 4 4
2 3 5 7
3 1 6 5
7 3 8 6"""
def set_map(coordinates):
map = set()
for coord in coordinates:
for x in range(coord[0], coord[2]):
for y in range(coord[1],coord[3]):
map.add((x,y))
return len(map)
lines = inp.split('\n')
coordinates = [[int(i) for i in line.split()] for line in lines]
print("면적: ", set_map(coordinates))
#정사각형 꼭지점이 제대로입력 됬는지 확인
def pointcheck(n):
global endnumber
endnumber=1
if len(n)!=4:
endnumnber=0
return
if n[0]>=n[2] or n[1]>=n[3]:
print("Wrong data!!!")
endnumber=0
return
else:
endnumber=1
return
#면적 좌표를 리스트로 만들어서 집합안에 입력
def areacal(n):
global rawd
rawd=set()
for i in range(n[0],n[2]):
for j in range(n[1],n[3]):
pointn=[i,j]
rawd.add(tuple(pointn))
return
#좌표 입력
squarepoint=set()
sq1=list(map(int,input().split()))
sq2=list(map(int,input().split()))
sq3=list(map(int,input().split()))
sq4=list(map(int,input().split()))
#좌표 오류 탐색 후 면적 좌표 집합으로 넘기기
while True:
pointcheck(sq1)
pointcheck(sq2)
pointcheck(sq3)
pointcheck(sq4)
if endnumber==0:
break
else:
areacal(sq1)
squarepoint.update(rawd)
areacal(sq2)
squarepoint.update(rawd)
areacal(sq3)
squarepoint.update(rawd)
areacal(sq4)
squarepoint.update(rawd)
print(len(squarepoint))
break
y_x_coordinate=list()
line=0
while line<1001:
x_coordinate=list()
x=0
while x<1001:
x_coordinate.append(0)
x+=1
y_x_coordinate.append(x_coordinate)
line+=1
a=0
while a<4:
left_bottom_x,left_bottom_y,right_up_x,right_up_y=map(int,input().split())
if left_bottom_x>=1 and left_bottom_y<=1000 and right_up_x>=1 and right_up_y<=1000:
for y in range(left_bottom_y,right_up_y):
for x in range(left_bottom_x,right_up_x):
y_x_coordinate[y][x]+=1
a+=1
for y in range(1,1001):
for x in range(1,1001):
if 1!=y_x_coordinate[y][x] and 0!=y_x_coordinate[y][x]:
y_x_coordinate[y][x]=1
area=0
for y in range(1,1001):
for x in range(1,1001):
area+=y_x_coordinate[y][x]
print(area)
JAVA입니다. 다른 분들 풀이를 보니 사람들 생각은 다 똑같은 것 같네요 ㅎㅎ
package four_boxes;
public class Box {
int x1, y1, x2, y2;
public Box(int x1, int y1, int x2, int y2, Cell[][] cells) {
this.x1 = Math.min(x1, x2);
this.y1 = Math.min(y1, y2);
this.x2 = Math.max(x1, x2);
this.y2 = Math.max(y1, y2);
//좌표가 작은 쪽이 x1, y1
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
cells[x][y].setOccupied(true);
}
}
}
}
package four_boxes;
public class Cell {
/*좌표계
* (0, 0) (1, 0) (2, 0)
* (0, 1) (1, 1) (2, 1)
* (0, 2) (1, 2) (2, 2)
*/
int x, y; //왼쪽 위 꼭짓점의 x좌표, y좌표
boolean occupied; //칸에 상자가 위치하는지 여부
public Cell(int x, int y) {
this.x = x;
this.y = y;
occupied = false;
}
void setOccupied(boolean state) {
occupied = state;
}
}
package four_boxes;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Box[] boxes = new Box[4];
Cell[][] cells = new Cell[1001][1001];
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
cells[i][j] = new Cell(i, j);
}
}
for (int i = 0; i < 4; i++) {
String boxStr = sc.nextLine();
String[] boxStrs = boxStr.split(" ");
boxes[i] = new Box(Integer.parseInt(boxStrs[0]), Integer.parseInt(boxStrs[1]),
Integer.parseInt(boxStrs[2]), Integer.parseInt(boxStrs[3]), cells);
}
int count = 0;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if(cells[i][j].occupied) {
count += 1;
}
}
}
System.out.println(count);
}
}