You are given a 2-Dimensional array (matrix) and a scale factor. You need to write a method to scale the array according to the scale factor. The signature of the method should be
public static int[][] scale1(int[][] arr, int scale)
For example, if you are given a 2*3 array and scale factor is 3, the output array will be 6*9; the input and output arrays will be as follows:
Input
1 2 3
4 5 6
Output
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
package com.jee.heartin.problem;
import java.util.Scanner;
public class Scale2DArray {
public static int[][] scaleArray(int[][] arr, int scale) {
int[][] resultArr;
int rowCount = 0;
int columnCount = 0;
boolean check = true;
rowCount = arr.length;
if (rowCount == 0)
check = false;
if (check) {
columnCount = arr[0].length;
System.out.println("Row count = " + rowCount);
System.out.println("Column count = " + columnCount);
int resultRow = rowCount * scale;
int resultCol = columnCount * scale;
resultArr = new int[resultRow][resultCol];
int r = 0;
int count = 0;
int c;
for (int i = 0; i < resultRow; i++) {
c = 0;
for (int j = 0; j < columnCount; j++) {
for (int k = 0; k < scale; k++) {
resultArr[i][c] = arr[r][j];
c++;
}
}
count++;
if (count >= scale) {
r++;
count = 0;
}
}
return resultArr;
}
else {
System.out.println("Parent array does not have any element!!");
return null;
}
}
//Tester method
public static void main(String[] args) {
int[][] arr;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the no. of rows for the 2D array : ");
int r = scan.nextInt();
System.out.println("Enter the no. of columns for the 2D array : ");
int c = scan.nextInt();
arr = new int[r][c];
System.out.println("Enter the elements into the 2D array : ");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print("Enter integer for row " + i + " col " + j
+ ": ");
arr[i][j] = scan.nextInt();
}
}
System.out.println("The 2D array:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print(" " + arr[i][j]);
}
System.out.println("");
}
System.out.println("Enter the scale factor:");
int scale = scan.nextInt();
int[][] scaledArray = scaleArray(arr, scale);
if (scaledArray == null) {
System.out.println("The array cannot be scaled!!");
} else {
System.out.println("The resulting scaled array:");
for (int i = 0; i < scaledArray.length; i++) {
for (int j = 0; j < scaledArray[i].length; j++) {
System.out.print(" " + scaledArray[i][j]);
}
System.out.println("");
}
}
}
}
that was huge..........but interesting !! thanx