diff --git a/AP1403 - Algorithms/src/main/java/Exercises.java b/AP1403 - Algorithms/src/main/java/Exercises.java index 15a2133..70ac853 100644 --- a/AP1403 - Algorithms/src/main/java/Exercises.java +++ b/AP1403 - Algorithms/src/main/java/Exercises.java @@ -9,11 +9,19 @@ public class Exercises { note: you should return the indices in ascending order and every array's solution is unique */ public int[] productIndices(int[] values, int target) { - // todo + for (int i = 0; i < values.length; i++) { + for (int j = i + 1; j < values.length; j++) { + if (values[i] * values[j] == target) { + int[] arr = { i , j }; + return arr; + } + } + } return null; } - /* + + /*+ given a matrix of random integers, you should do spiral traversal in it e.g. if the matrix is as shown below: 1 2 3 @@ -25,8 +33,43 @@ public int[] productIndices(int[] values, int target) { so you should walk in that matrix in a curl and then add the numbers in order you've seen them in a 1D array */ public int[] spiralTraversal(int[][] values, int rows, int cols) { - // todo - return null; + int[] answer = new int[rows * cols]; // آرایه خروجی + int index = 0; // اندیس برای پر کردن آرایه خروجی + + int srow = 0, erow = rows - 1; + int scol = 0, ecol = cols - 1; + + while (srow <= erow && scol <= ecol) { + for (int i = scol; i <= ecol; i++) { + answer[index] = values[srow][i]; + index ++; + } + srow ++; + + for (int i = srow; i <= erow; i++) { + answer[index] = values[i][ecol]; + index ++; + } + ecol --; + + if (srow <= erow) { + for (int i = ecol; i >= scol; i--) { + answer[index] = values[erow][i]; + index ++; + } + erow --; + } + + if (scol <= ecol) { + for (int i = erow; i >= srow; i--) { + answer[index] = values[i][scol]; + index ++; + } + scol ++; + } + } + + return answer; } /*