Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GroupByRemainder {
- // A method that takes an array of numbers and returns a 2D array of numbers
- // where the first dimension is the remainder of 3 and the second dimension is the list of numbers with that remainder
- public static int[][] groupByRemainder(int[] numbers) {
- // Create an empty 2D array with 3 rows and 0 columns
- int[][] groups = new int[3][0];
- // Loop through the array of numbers
- for (int number : numbers) {
- // Compute the remainder of 3
- int remainder = number % 3;
- // Get the current length of the row corresponding to the remainder
- int length = groups[remainder].length;
- // Create a new array with one more element than the current row
- int[] newRow = new int[length + 1];
- // Copy the elements from the current row to the new array
- for (int i = 0; i < length; i++) {
- newRow[i] = groups[remainder][i];
- }
- // Add the number to the end of the new array
- newRow[length] = number;
- // Replace the current row with the new array
- groups[remainder] = newRow;
- }
- // Return the 2D array
- return groups;
- }
- // A main method to test the method
- public static void main(String[] args) {
- // Create an array of numbers
- int[] numbers = {1, 2, 3, 4, 5, 6, 7};
- // Call the method and print the result
- int[][] result = groupByRemainder(numbers);
- for (int i = 0; i < result.length; i++) {
- System.out.print(i + " -> ");
- for (int j = 0; j < result[i].length; j++) {
- System.out.print(result[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement