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 | import java.util.Random; /** * 5*5 행렬 1~25 랜덤하게 수 대입하고 25개의 각 요소에 대해서 그요소와 이웃한 요소와의 차의 절대값 구하기 * * @author cjson * */ public class AbsoluteValue { static int[][] arr; static Random random; static int[] dx = { -1, 1, 0, 0 }; static int[] dy = { 0, 0, 1, -1 }; static int result = 0; public static void main(String[] args) { arr = new int[5][5]; random = new Random(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { arr[i][j] = random.nextInt(25) + 1; // 0~25 랜덤함수 생성 } } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { System.out.print(arr[i][j] + " "); // 랜덤함수 어떻게 생성되는지 확인하기 위해서 적어줌. } System.out.println(); } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { result = 0; check(i, j); // 절대값을 구하는 함수 호출 System.out.println("절대값의 합 : " + result); } System.out.println(); } }// end of main public static void check(int x, int y) { for (int i = 0; i < dx.length; i++) { int nx = x + dx[i]; // 북남동서 로 이동하면서 검사 int ny = y + dy[i]; // 북남동서 로 이동하면서 검사 if (nx >= 0 && ny >= 0 && nx < arr.length && ny < arr.length) { // (0,0) 일따 북이나 서로 가버리면 배열의 범위 넘어가버려서 Array // out of bounds 에러 발생 result += Math.abs(arr[x][y] - arr[nx][ny]); // Math.abs() 절대값으로 만드는 함수 } } return; } }// end of class | cs |
'Algorithm 문제풀이' 카테고리의 다른 글
백준 N과M(3) (0) | 2019.03.17 |
---|---|
백준 N과M(2) (0) | 2019.03.17 |
백준 N과M(1) (0) | 2019.03.17 |
K번째 접미어 찾기 (0) | 2019.02.26 |
k번째 문자열 찾기 (0) | 2019.02.26 |