PS/code-up
설탕과자뽑기(반복문 인덱스 계산)
easy16
2022. 4. 22. 23:21
아래 문제를 통해 반복문 내 인덱스 계산에 따른 성능 향상을 위한 기법을 엿볼 수 있다.
배열 index안의 내용을 조작하지 않고, 인덱스의 기본위상(초기값)을 설정하면 성능상의 이점이 있다.
ex1)의 경우 매번 index를 얻기 위해 덧셈 연산을 하지만
ex2)의 경우 덧셈 연산 없이 index를 바로 참조가능.
import java.util.Scanner;
class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
int w = sc.nextInt();
int [][]arr = new int[h+1][w+1];
int n = sc.nextInt();
for ( int i = 0 ; i < n ; ++i) {
int l = sc.nextInt();
int d = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
//ex1)
/*
for ( int j = 0 ; j < l ; ++j ) {
if( d == 0) {
arr[x][y+j]=1;
} else {
arr[x+j][y]=1;
}
}
*/
//ex2)
if( d == 0) {
for ( int j = y ; j < y+l ; ++j )
arr[x][j]=1;
} else {
for ( int j = x ; j < x+l ; ++j )
arr[j][y]=1;
}
}
for (int i = 1 ; i <= h; ++i) {
for ( int j = 1; j <= w; ++j)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}