MagicSquare.MagicSquare.java Source code

Java tutorial

Introduction

Here is the source code for MagicSquare.MagicSquare.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MagicSquare;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.*;

/**
 *
 * @author Absalom
 */
public class MagicSquare extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int n = Integer.valueOf(request.getParameter("num"));
        int[][] array = new int[n][n];
        if (n == 0 | n % 2 == 0) {
            array[0][0] = -1;
        } else {

            int x = 0;
            int y = n / 2;

            int xa = x;
            int ya = y;

            for (int i = 0; i < n * n; i++) {
                if (array[x][y] == 0) {
                    xa = x;
                    ya = y;
                    array[x][y] = i + 1;
                    x--;
                    y++;
                } else {
                    y = ya;
                    x = xa;
                    x++;
                    i--;
                }

                if (y == -1) {
                    y = n - 1;
                }
                if (x == -1) {
                    x = n - 1;
                }
                if (y == n) {
                    y = 0;
                }
                if (x == n) {
                    x = 0;
                }
            }
        }
        String resp = "";
        for (int no = 0; no < n; no++) {
            for (int ni = 0; ni < n; ni++) {
                if (ni + 1 == n) {
                    resp += array[no][ni] + "";
                } else {
                    resp += array[no][ni] + ",";
                }
            }
            if (no + 1 == n) {
                resp += "";
            } else {
                resp += ";";
            }

        }
        //        JSONObject json = new JSONObject();
        //        json.put("hola", array);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(resp);
    }

}