Advertisement
CR7CR7

return 2D array

May 10th, 2023
614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. public class GroupByRemainder {
  2.  
  3.     // A method that takes an array of numbers and returns a 2D array of numbers
  4.     // where the first dimension is the remainder of 3 and the second dimension is the list of numbers with that remainder
  5.     public static int[][] groupByRemainder(int[] numbers) {
  6.         // Create an empty 2D array with 3 rows and 0 columns
  7.         int[][] groups = new int[3][0];
  8.  
  9.         // Loop through the array of numbers
  10.         for (int number : numbers) {
  11.             // Compute the remainder of 3
  12.             int remainder = number % 3;
  13.  
  14.             // Get the current length of the row corresponding to the remainder
  15.             int length = groups[remainder].length;
  16.  
  17.             // Create a new array with one more element than the current row
  18.             int[] newRow = new int[length + 1];
  19.  
  20.             // Copy the elements from the current row to the new array
  21.             for (int i = 0; i < length; i++) {
  22.                 newRow[i] = groups[remainder][i];
  23.             }
  24.  
  25.             // Add the number to the end of the new array
  26.             newRow[length] = number;
  27.  
  28.             // Replace the current row with the new array
  29.             groups[remainder] = newRow;
  30.         }
  31.  
  32.         // Return the 2D array
  33.         return groups;
  34.     }
  35.  
  36.     // A main method to test the method
  37.     public static void main(String[] args) {
  38.         // Create an array of numbers
  39.         int[] numbers = {1, 2, 3, 4, 5, 6, 7};
  40.  
  41.         // Call the method and print the result
  42.         int[][] result = groupByRemainder(numbers);
  43.         for (int i = 0; i < result.length; i++) {
  44.             System.out.print(i + " -> ");
  45.             for (int j = 0; j < result[i].length; j++) {
  46.                 System.out.print(result[i][j] + " ");
  47.             }
  48.             System.out.println();
  49.         }
  50.     }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement