Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1.  
  2.  
  3. package prog4;
  4.  
  5. import java.util.Scanner;
  6. import java.util.Random;
  7.  
  8. public class Prog4 {
  9.  
  10.  
  11.     public static void main(String[] args) {
  12.         int sum, order; //Sum that the square should add up to and
  13.                         //order is number of rows and columns
  14.  
  15.         Scanner scan = new Scanner(System.in);
  16.  
  17.         System.out.println("\t-MAGIC SQUARE GENERATOR-");
  18.         System.out.print("Enter the sum: ");
  19.         sum = scan.nextInt();
  20.         System.out.print("Enter the order of the square: ");
  21.         order = scan.nextInt();
  22.         int[] square = new int[2*order];
  23.         square = magicSquare(sum, order);
  24.  
  25.         int[][] fullSquare = new int[order][order];
  26.        
  27.  
  28.         for(int y=0;y<order;y++)
  29.         {
  30.             for(int x=0;x<order;x++)
  31.             {
  32.                 fullSquare[y][x]=square[order+y-1]+square[x];
  33.                 System.out.printf("%3d ", fullSquare[y][x]);
  34.             }
  35.             System.out.println();
  36.         }
  37.  
  38.  
  39.     }
  40.    
  41.     public static int[] magicSquare(int sum, int order){
  42.  
  43.             int i, arraySum=0; //counter variable and arraySum to keep track
  44.                                //of total sum of array values
  45.             int[] squareArray = new int[2*order]; //declare array for numbers
  46.            
  47.             Random rand = new Random(); //Create random number generator
  48.  
  49.  
  50.             //Populate array with random integers:
  51.             for(i=0; i<(2*order-1); i++)
  52.             {
  53.                 squareArray[i] = rand.nextInt(sum/(2*order)+1);
  54.                 arraySum+=squareArray[i];
  55.             }
  56.  
  57.             //Make sure the last value of the array insures the sum is equal to
  58.             //to the sum specified:
  59.             squareArray[i] = sum-arraySum;
  60.  
  61.  
  62.             return squareArray;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement