My omitRow function omits the wrong row - java

This project involves three classes. Star creates the stars, Starfield creates a matrix of stars, and StarfieldSimualation is the runner
When I omit row 0, it omits the bottom row, instead of the top one. But, it works for rows 1-4. Thanks in advance for the help.
Starfield Code
public class Starfield
{
private Star[][] Sky;
public Starfield(int rows, int cols)
{
if(rows < 0 || cols < 0)
{
rows = cols = 1;
}
Sky = new Star[rows][cols];
}
public String toString()
{
String S = "";
for (Star[] row: Sky)
{
for(Star X: row)
{
if(X != null)
{
S+= X.getImage() + "\t";
}
else
{
S += "- \t";
}
}
S += "\n";
}
return S;
}
public void addStar(String Image, String Constellation, int row, int col)
{
if(row < 0 || row >= Sky.length || col < 0 || col >= Sky[0].length)
{
return;
}
Sky[row][col] = new Star(Image, Constellation, row, col);
}
public Star[][] omitRow(int r)
{
int i, j, k;
k = 0;
Star[][] rowless = new Star[Sky.length - 1][Sky[0].length];
for(i = 0; i < Sky.length-1; i++)
{
for(j = 0; j < Sky[0].length; j++)
{
k++;
}
}
Star[] ans = new Star[k];
k = 0;
for(i = 0; i < Sky.length; i++)
{
for(j = 0; j < Sky[0].length; j++)
{
if(i != r)
{
ans[k] = Sky[i][j];
k++;
}
}
}
k = 0;
for(i = 0; i < rowless.length; i++)
{
for(j = 0; j < rowless[0].length; j++)
{
if(i != r)
{
rowless[i][j] = ans[k];
k++;
}
}
}
return rowless;
}
Star Code
public class Star
{
private Star[][] Sky;
private String Image, Constellation;
private int row, col;
public Star(String I, String C, int r, int c)
{
Image = I;
Constellation = C;
row = r;
col = c;
}
public String getImage()
{
return Image;
}
public String getConstellation()
{
return Constellation;
}
public int getRow()
{
return row;
}
public int getCol()
{
return col;
}
}
Starfield Simluation Code
public class StarFieldSimulation
{
public static void main(String[] args)
{
Starfield theSky = new Starfield(5,4);
theSky.addStar("*", "Orion", 2, 3);
theSky.addStar("*", "Orion", 2, 2);
theSky.addStar("*", "Orion", 2, 1);
theSky.addStar("*", "Orion", 2, 0);
theSky.addStar("*", "Orion", 1, 3);
System.out.println("IT'S THE SKY EVERYONE");
System.out.println(theSky.toString());
Star[][] minusrow = new Star[4][4];
minusrow = theSky.omitRow(4);
System.out.println("A row has been removed");
System.out.println();
for(Star[] row: minusrow)
{
for(Star X: row)
{
if(X != null)
{
System.out.print(X.getImage() + "\t");
}
else
{
System.out.print("-\t");
}
}
System.out.println();
}
System.out.println();
System.out.println("It's the sky again");
System.out.println(theSky.toString());
}

Related

Minimax debugging. Not sure how to look for where the code is falling apart

First time actually using the site so if I do anything wrong I apologize in advance and will work to correct it given guidance. I am currently working on my senior project. It is a game very similar to tic-tac-toe but the height and width of the board are of variable sizes and the amount in a row needed to win is also variable (all chosen by the user through jcomboboxes).
the problem is that the miniMax method will often select a tile that's already been chosen. I'm not entirely sure how to figure out the source of the problem, after having done quite a few hours of research. I just need to be pointed in the right direction on the means of finding the source but will gladly take any help I can get
attached below is the code. I provided all of the code for the program so that it can be compiled and tested, hopefully, with ease. If this is the wrong thing to do I apologize, let me know and I will correct.
I found various examples of the minimax algorithm being implemented and ended up using the one in the following link: simplest MiniMax algorithm for TicTacToe AI in Java
I also tried implementing the following: https://medium.com/#pelensky/unbeatable-tic-tac-toe-minimax-in-java-e1ad687ed821
but that led to numerous stackoverflow errors that I couldn't see how to reasonably mitigate without redoing the entire algorithm.
I am currently working with the former and it works to an extent but the AI doesn't appear to make intelligent decisions and will often try to choose a tile that's already been selected.
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Konnexion extends JPanel
{
ArrayList<JButton> buttons = new ArrayList<JButton>();
private static int totalButtons;
private JLabel winStat;
private JLabel lossStat;
protected JLabel drawStat;
JPanel gameBoard;
JButton exitButton;
int wins = 0;
int losses = 0;
int draws = 0;
Game game;
public Konnexion(int height, int width, int connects, String ai)
{
JPanel gameStats = new JPanel();
gameStats.setLayout(new GridLayout(1,3));
winStat = new JLabel("Wins: " + wins);
lossStat = new JLabel("Losses: " + losses + " ");
drawStat = new JLabel("Draws: " + draws);
gameStats.add(winStat);
gameStats.add(lossStat);
gameStats.add(drawStat);
add(gameStats);
totalButtons = (height * width) - 1;
gameBoard = new JPanel();
gameBoard.setLayout(new GridLayout(height,width));
initializebuttons();
add(gameBoard);
JPanel menuButtons = new JPanel();
menuButtons.setLayout(new GridLayout(1,1));
exitButton = new JButton();
exitButton.setText("Exit Game");
exitButton.addActionListener(new buttonListener());
menuButtons.add(exitButton);
add(menuButtons);
game = new Game(totalButtons, height, width, connects, ai);
}
public void initializebuttons()
{
for(int i = 0; i <= totalButtons; i++)
{
buttons.add(i, new JButton());
buttons.get(i).setText("");
buttons.get(i).setPreferredSize(new Dimension(75,75));
buttons.get(i).addActionListener(new buttonListener());
gameBoard.add(buttons.get(i));
}
}
public void resetButtons()
{
for(int i = 0; i <= totalButtons; i++)
{
buttons.get(i).setText("");
}
game.resetGameState();
}
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource(); //get the particular button that was clicked
if (buttonClicked.getText().equals(""))
{
buttonClicked.setText(Game.getSymbol(game.getCurrentPlayer()));
game.setMarker(buttons.indexOf(buttonClicked), game.getSymbol(game.getCurrentPlayer()));
if (Game.getSymbol(game.getCurrentPlayer()).equals("X"))
{
game.changeCurrentPlayer();
if (game.hasWon("X", Game.cells)) {
wins++;
winStat.setText("Wins: " + wins);
JOptionPane.showConfirmDialog(null, "Player X Wins!!!");
resetButtons();
game.resetGameState();
}
}
else
{
game.changeCurrentPlayer();
if (game.hasWon("O", Game.cells)) {
losses++;
lossStat.setText("Losses: " + losses + " ");
JOptionPane.showConfirmDialog(null, "Player O Wins!!!");
resetButtons();
game.resetGameState();
}
}
if (game.getCurrentPlayer() == 2) {
game.printArrays();
game.copyGameState();
//System.out.println(game.miniMax(game.getCurrentPlayer()));
buttons.get(game.miniMax(game.getCurrentPlayer())).doClick();
}
}
else if (buttonClicked.equals(exitButton))
{
Window window = SwingUtilities.getWindowAncestor(exitButton);
window.dispose();
try {
new MainMenu();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else
{
JOptionPane.showMessageDialog(buttonClicked, "That tile has already been selected!");
}
if (game.checkDraw())
{
draws++;
drawStat.setText("Draws: " + draws);
JOptionPane.showConfirmDialog(null, "It was a Draw!!!");
resetButtons();
}
}
}
}
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Game {
public static int ROWS;
public static int COLS;
public static int WIN_SIZE;
public static int currentPlayer;
public static String[][] cells; //Game state array
String[][] node; //copy of the game state used for minimax method
public Game(int totalButtons, int height, int width, int connects, String difficulty) {
ROWS = height;
COLS = width;
WIN_SIZE = connects;
currentPlayer = 1;
cells = new String[ROWS][COLS];
node = new String[ROWS][COLS];
resetGameState(cells);
resetGameState(node);
}
public void setMarker(int space, String marker) {
int col = space % COLS;
int rows = space / COLS;
cells[rows][col] = marker;
}
public void changeCurrentPlayer() {
if (currentPlayer == 1)
{
currentPlayer = 2;
}
else if (currentPlayer == 2)
{
currentPlayer = 1;
}
}
public int getCurrentPlayer() {
return currentPlayer;
}
public static String getSymbol(int playerNum) {
if (playerNum == 1)
return "X";
else
return "O";
}
public void resetGameState() {
currentPlayer = 1;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
cells[i][j] = "-";
}
}
}
public static void resetGameState(String[][] gameState) {
for (int i = 0; i < gameState.length; i++) {
for (int j = 0; j < gameState[i].length; j++) {
gameState[i][j] = "-";
}
}
}
/**
*
* #param theSeed Value expected in each cell
* #param row Row index to check
* #param col Col index to check
* #param count Number of consecutive elements found in the line.
* #param rowIncrement Increment to the row index for the next evaluation
* #param colIncrement Increment to the col index for the next evaluation
* #return true if there is a winner combination in the line, otherwise false.
*/
private boolean checkLine(String theSeed, int row, int col, int count, int rowIncrement, int colIncrement, String[][] gameCheck) {
if (!areValidIndexes(row, col)) {
return false;
}
if (theSeed.equals(gameCheck[row][col])) {
count++;
if (count >= WIN_SIZE) {
return true;
} else {
return checkLine(theSeed, row + rowIncrement, col + colIncrement, count, rowIncrement, colIncrement, gameCheck);
}
} else {
return false;
}
}
private boolean areValidIndexes(int row, int col) {
if (row >= 0 && row < ROWS &&
col >= 0 && col < COLS) {
return true;
}
return false;
}
private boolean checkRow(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 1, 0, gameCheck);
}
private boolean checkColumn(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 0, 1, gameCheck);
}
private boolean checkForwardDiagonal(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 1, 1, gameCheck);
}
private boolean checkBackwardDiagonal(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, -1, 1, gameCheck);
}
public boolean hasWon(String theSeed, String[][] gameCheck) {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (checkRow(theSeed, row, col, gameCheck) ||
checkColumn(theSeed, row, col, gameCheck) ||
checkForwardDiagonal(theSeed, row, col, gameCheck) ||
checkBackwardDiagonal(theSeed, row, col, gameCheck)) {
return true;
}
}
}
return false;
}
public boolean checkDraw()
{
String s = "";
for (String[] r : cells) {
for (String t : r) {
s += t;
}
}
if (!s.contains("-"))
{
return true;
}
return false;
}
public static boolean checkDraw(String[][] node)
{
String s = "";
for (String[] r : node) {
for (String t : r) {
s += t;
}
}
if (!s.contains("-"))
{
return true;
}
return false;
}
public int checkWin(String[][] gameState) {
if (hasWon("X", gameState))
{
return 1;
}
else if (hasWon("O", gameState))
{
return 2;
}
else
{
return 0;
}
}
public void copyGameState() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
node[i][j] = cells[i][j];
}
}
}
public static int[] getAvailableSpaces() {
String s = "";
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j].equals("-"))
s += ((j * COLS) + i) + ", ";
}
}
String[] split = s.split(", ");
int[] availableSpaces = new int[split.length];
for (int i = 0; i < split.length; i++)
availableSpaces[i] = Integer.parseInt(split[i]);
return availableSpaces;
}
public void resetSpace(int space) {
int col = space % COLS;
int rows = space / COLS;
cells[rows][col] = "-";
}
public int miniMax(int playerNum)
{
//printArrays();
int victor = checkWin(cells); // returns 0 if game is ongoing, 1 for p1, 2 for p2, 3 for tie.
if(victor != 0) //game over
{
return Score(victor);
}
if(playerNum == 2) //AI
{
int bestVal = Integer.MAX_VALUE;
int bestSpot = 0;
for(int i = 0; i < cells.length; i++)
for (int j = 0; j < cells[i].length; j++)
{
if(!cells[i][j].equals("-"))
continue;
cells[i][j] = getSymbol(playerNum);
int value = miniMax(1);
if(value < bestVal)
{
bestVal = value;
bestSpot = (j * COLS) + i;
System.out.println("Best Value: " + bestVal);
System.out.println("Best Spot: " + bestSpot);
}
cells[i][j] = "-";
}
return bestSpot;
}
else
{
int bestVal = Integer.MIN_VALUE;
int bestSpot = 0;
for(int i = 0; i < cells.length; i++)
for(int j = 0; j < cells[i].length; j++)
{
if(!cells[i][j].equals("-"))
continue;
cells[i][j] = getSymbol(playerNum);
int value = miniMax(2);
if(value > bestVal)
{
bestVal = value;
bestSpot = (j * COLS) + i;
}
cells[i][j] = "-";
}
return bestSpot;
}
}
private int Score(int gameState)
{
if(gameState ==2) //O wins.
return 10;
else if(gameState==1) //X wins
return -10;
return 0;
}
public void printArrays() {
String s = "cells: ";
String l = "node: ";
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j <cells[i].length; j++) {
s += cells[i][j];
l += node[i][j];
}
}
System.out.println(s);
System.out.println(l);
}
}

Log rotation in java, limit of logs

I have a class Game which add to the logs score of my game.
Then I want to add the limit, that I can only 2 logs add for example and than logs don't added. But what I should to add in my Game.class that the class will communicate with the file log.properties? Should I use log4j?
Here is my Game.class:
import java.util.Random;
import java.util.logging.Logger;
public class Game {
public static final int numOfFutMarbles = 3; // przyszle kulki
private int score;
Field fieldProcessor = new Field();
Wave wave = new Wave();
Logger logger = Logger.getLogger(Game.class.getName());
Random random = new Random();
public final static int width = 9; // rozmiar planszy
public final static int height = 9;
public Bin[][] field;
public static final int not_sel = -1;
int activeBinX = not_sel;
int activeBinY = not_sel;
public Game() {
this.field = new Bin[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
field[i][j] = new Bin(i, j);
}
}
placeMarbles(5, Marble.new_mar); // liczba kulek na poczatku
placeMarbles(3, Marble.fut_mar); // liczba przyszlych kulek
score = 0;
}
public void BinSelected(int i, int j) {
if (isBinContainsMarble(i, j)) {
activeBinchange(i, j);
}
}
boolean isBinContainsMarble(int i, int j) {
return field[i][j].isBinContainsMarble();
}
public void makeMoveOrSelect(int i, int j) {
if (field[i][j].isBinContainsMarble()) {
activeBinchange(i, j);
return;
}
if (activeBinX == not_sel) {
return;
}
if (wave.isMoveAvailable(field, activeBinX, activeBinY, i, j)) {
makeMove(i, j);
}
}
void makeMove(int x, int y) {
field[x][y].marble = field[activeBinX][activeBinY].marble;
field[x][y].setMarbleState(Marble.inac_mar);
field[activeBinX][activeBinY].marble = null;
activeBinX = not_sel;
activeBinY = not_sel;
boolean isLineRemoved = fieldProcessor.checkField(field);
if (!isLineRemoved) {
placeNewMarbles();
fieldProcessor.checkField(field);
}
calcScores();
wave.createWaveArrayFrom(field);
}
void activeBinchange(int i, int j) {
if (isActiveBinSelected()) {
field[activeBinX][activeBinY].setMarbleState(Marble.inac_mar);
}
field[i][j].setMarbleState(Marble.act_mar);
activeBinX = i;
activeBinY = j;
}
private boolean isActiveBinSelected() {
return activeBinX > not_sel;
}
void placeNewMarbles() {
int remaningFutureMarbles = calcRemaningFutureMarblesAndMakeThemNEW();
placeMarbles(numOfFutMarbles, Marble.fut_mar);
}
int calcRemaningFutureMarblesAndMakeThemNEW() {
int remainingFutureMarblesAmount = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].getMarbleState() == Marble.fut_mar) {
remainingFutureMarblesAmount++;
field[i][j].setMarbleState(Marble.new_mar);
}
}
}
return remainingFutureMarblesAmount;
}
void placeMarbles(int n, int state) {
for (int i = 0; i < n; i++) {
placeMarbleOnEmptySpace(state);
}
}
void placeMarbleOnEmptySpace(int state) { // umieszamy kulke na wolnym miejscu
boolean isPlaced = false;
do {
int i = random.nextInt(width);
int j = random.nextInt(height);
if (field[i][j].getMarbleState() == 0) {
field[i][j].marble = new Marble(state);
isPlaced = true;
}
} while (!isPlaced);
}
public void updateBins() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].marble != null) {
field[i][j].marble.porcessMarbles();
}
}
}
}
public int calcScores() {
int markedForDel = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].marble != null) {
if (field[i][j].marble.MarbleState == Marble.mark_for_rem) {
markedForDel++;
}
}
}
}
if (markedForDel > 0) {
int bon = (int) (4 + Math.pow(markedForDel - 4, 3)); // 6 kulek = 12 pkt, 7 kulek - 31 pkt
score += bon;
logger.info(score + "");
System.out.println("your score: " + score); // 1 pkt za kazda kulke
}
return score;
}
}
Here is my log configuration:
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
# File Logging
java.util.logging.FileHandler.pattern=./logs/Marbles_game.log
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.limit=2
java.util.logging.FileHandler.count=100
# Console Logging
java.util.logging.ConsoleHandler.level = OFF
Add java.util.logging.FileHandler.append=true to your properties file. This will append data to the log file until it reaches the limit.

Tic Tac Toe / Java

I've done my first aplication - Tic Tac Toe. I want to add a new function - display a winner (player X or O). How Can I do it?
public class Test extends JFrame {
int counter = 0;
public Test(){
setSize(800,800);
setTitle("Kółko i krzyżyk");
setVisible(true);
setLayout(new GridLayout(3,3));
for (int i = 1; i <= 9; i++){
JButton button = new JButton ("");
add (button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (counter % 2 ==0){
button.setText("X");
System.out.println("X");
} else{
button.setText("O");
System.out.println("O");
}
button.setEnabled(false);
counter++;
}
});
}
}
1.Player Class :
import java.util.Scanner;
public class Player {
private String name;
private MarkType mark;
private int row, col;
Scanner sc = new Scanner(System.in);
public Player(String name, MarkType mark) {
this.mark = mark;
this.name = name;
}
public String getName() {
return name;
}
public MarkType getMark() {
return mark;
}
public void nextMove() {
System.out.println(this.getName() + " enter position for " + this.getMark());
row = sc.nextInt();
col = sc.nextInt();
}
public int getRow() {
return row - 1;
}
public int getCol() {
return col - 1;
}
}
2.Board Class :
public class Board {
private MarkType board[][];
private int bsize;
public Board(int bsize) {
this.bsize = bsize;
board = new MarkType[bsize][bsize];
}
public int getBoardSize() {
return bsize;
}
public void updateBoard(int row, int col, MarkType mark) {
if (row > bsize || col > bsize) {
throw new ArrayIndexOutOfBoundsException();
} else if (board[row][col] == MarkType.$) {
board[row][col] = mark;
} else {
throw new InvalidPosition("Enter valid position");
}
}
public void initialize() {
for (int row = 0; row < bsize; row++)
for (int col = 0; col < bsize; col++)
board[row][col] = MarkType.$;
}
public boolean isWinner(int passedRow, int passedCol, MarkType mark) {
for (int col = 0; col < bsize; col++) {
if (board[passedRow][col] != mark)
break;
if (col == bsize - 1) {
return true;
}
}
for (int row = 0; row < bsize; row++) {
if (board[row][passedCol] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
if (passedRow == passedCol) {
for (int row = 0; row < bsize; row++) {
if (board[row][row] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
}
if (passedRow + passedCol == bsize - 1) {
for (int index = 0; index < bsize; index++) {
if (board[index][(bsize - 1) - index] != mark)
break;
if (index == bsize - 1) {
return true;
}
}
}
return false;
}
public void display() {
for (int row = 0; row < bsize; row++) {
for (int col = 0; col < bsize; col++) {
System.out.print(" " + board[row][col] + " ");
if (col != bsize - 1) {
System.out.print("|");
}
}
System.out.println();
if (row != bsize - 1) {
for (int col = 0; col < bsize; col++)
System.out.print("--- ");
}
System.out.println();
}
}
}
for complete answer follow the link below:
http://programmersthing.blogspot.in/2017/06/simple-game-in-java.html

Generating an unique Sudoku

I am making a Sudoku game in Java and I need some help.
I've got two classes for generating the Sudoku puzzle: SudokuSolver, SudokuGenerator`.
The SudokuSolver creates a full valid Sudoku puzzle for an empty table and the SudokuGenerator removes a random value from the table and then checks (using SudokuSolver) if the Sudoku puzzle is unique.
I found out that the Sudoku puzzle isn't unique, so I think my algorithm for checking the uniqueness of the Sudoku puzzle is bad.
For example, I have this Sudoku puzzle
497816532
132000000
000000000
910600080
086009000
000084963
021063059
743050020
600278304
And this solution:
497816532
132**745**698
568392471
914**637**285
386529147
275184963
821463759
743951826
659278314
I went to https://www.sudoku-solutions.com/ and I added the pattern of my Sudoku and they gave me another solution:
497816532
132**547**698
568392471
914**635**287
386729145
275184963
821463759
743951826
659278314
The funny think is that they're saying that This puzzle is valid and has a unique solution.
Some opinions?
SudokuSolver
public class SudokuSolver {
public static final int GRID_SIZE = 9;
public static final int SUBGRID_SIZE = 3;
private static int validRow = 0;
private static int validCol = 0;
private int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public boolean solveSudoku(int[][] values, int forbiddenNum) {
if(!findUnassignedLocation(values)) return true;
//suffle the nums array - for having a different valid sudoku
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(num == forbiddenNum) continue; //
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(solveSudoku(values, forbiddenNum)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
public boolean createValidSudoku(int[][] values) {
if(!findUnassignedLocation(values)) return true;
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(createValidSudoku(values)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
private void shuffleNums() {
Random random = new Random();
for(int i = nums.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int a = nums[index];
nums[index] = nums[i];
nums[i] = a;
}
}
private boolean findUnassignedLocation(int[][] values) {
for(int row = 0; row < GRID_SIZE; row++) {
for(int col = 0; col < GRID_SIZE; col++) {
if (values[row][col] == 0) {
validRow = row;
validCol = col;
return true;
}
}
}
return false;
}
private boolean usedInRow(int[][] values, int row, int num) {
for (int col = 0; col < GRID_SIZE; col++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInCol(int[][] values, int col, int num) {
for (int row = 0; row < GRID_SIZE; row++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInBox(int[][] values, int boxStartRow, int boxStartCol, int num) {
for(int row = 0; row < SUBGRID_SIZE; row++) {
for (int col = 0; col < SUBGRID_SIZE; col++) {
if (values[row + boxStartRow][col + boxStartCol] == num) return true;
}
}
return false;
}
private boolean isSafe(int[][] values,int row, int col, int num) {
return !usedInRow(values, row, num) &&
!usedInCol(values, col, num) &&
!usedInBox(values, row - row % 3, col - col % 3, num);
}
public void printGrid(int[][] values) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
}
SudokuGenerator
public class SudokuGenerator {
private int[][] generatorValues = new int[9][9];
public void generateSudoku() {
SudokuSolver sudokuSolver = new SudokuSolver();
//generate a random valid sudoku for an empty table
sudokuSolver.createValidSudoku(generatorValues);
int count = 0;
printNums(generatorValues);
while(count < 40){
Random random = new Random();
int row = 0;
int col = 0;
if(count < 15){
row = random.nextInt(3);
col = random.nextInt(9);
} else if (count >= 15 && count < 30) {
row = random.nextInt(3) + 3;
col = random.nextInt(9);
}else {
row = random.nextInt(3) + 6;
col = random.nextInt(9);
}
int num = generatorValues[row][col];
int tempValues[][] = Arrays.copyOf(generatorValues, generatorValues.length);
//System.out.println("Row:" + row + "Col: " + col + "Num: " + num);
//Set the cell to 0;
if(generatorValues[row][col] != 0){
generatorValues[row][col] = 0;
} else{
continue;
}
//If found a solution, set cell back to original num
if(sudokuSolver.solveSudoku(tempValues, num)) {
generatorValues[row][col] = num;
continue;
}
count++;
}
System.out.println("------------------");
printNums(generatorValues);
}
private void printNums(int[][] values) {
for (int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
public int[][] getGeneratorValues () {
return generatorValues;
}
}

Manipulating adjacent matrix

I have a network graph with nodes and edges and i managed to construct an adjacent matrix of my graph.
sample adjacent matrix with edge weight
Nodes -> {A, B, C, D}
Edges -> {[A->B = 2] , [A->D = 5] , [C->A = 1] , [C->B = 4] , [D->B = ] , [D->C = 2]}
my adjacent network is like this
0 2 0 2
0 0 0 0
4 4 0 0
0 6 6 0
so i want to change the adjacent matrix to be like this with labels of the nodes and average of each column by considering non zero cells
A B C D
A 0 2 0 2
B 0 0 0 0
C 4 4 0 0
D 0 6 6 0
X 4 4 6 2 <- Mean of non zero column
here is my the code i used to create adjacent matrix,
Node.java
public class Node
{
public char label;
public Node(char l)
{
this.label=l;
}
}
Graph.java
public class Graph
{
public ArrayList nodes=new ArrayList();
public double[][] adjacentMatrix;
int size;
public void addNode(Node n)
{
nodes.add(n);
}
public void addEdge(Node start,Node end,int weight)
{
if(adjacentMatrix==null)
{
size=nodes.size();
adjacentMatrix=new double[size][size];
}
int startIndex=nodes.indexOf(start);
int endIndex=nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex]=weight;
}
public static void printAdjacentMatrix(double matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Defining nodes
Node nA=new Node('A');
Node nB=new Node('B');
Node nC=new Node('C');
Node nD=new Node('D');
//Creating adjacent matrix
Graph g=new Graph();
g.addNode(nA);
g.addNode(nB);
g.addNode(nC);
g.addNode(nD);
g.addEdge(nA, nB, 2);
g.addEdge(nA, nD, 2);
g.addEdge(nC, nA, 4);
g.addEdge(nC, nB, 4);
g.addEdge(nD, nB, 6);
g.addEdge(nD, nC, 6);
g.printAdjacentMatrix(g.adjacentMatrix);
}
}
so i ask for help to display the second matrix with average and labels...Thank you in advance
Not a very nice solution but that will do.
public class Graph {
public ArrayList nodes = new ArrayList();
public int[][] adjacentMatrix;
int size;
public void addNode(Node n) {
nodes.add(n);
}
public void addEdge(Node start, Node end, int weight) {
if (adjacentMatrix == null) {
size = nodes.size();
adjacentMatrix = new int[size][size];
}
int startIndex = nodes.indexOf(start);
int endIndex = nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex] = weight;
}
public static void printAdjacentMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
public static void convertMatrix(int matrix[][]) {
int row = matrix.length + 2;
int column = matrix[0].length + 1;
String newMatrix[][] = new String[row][column];
initializeFirstRow(newMatrix);
initializeFirstColumn(newMatrix);
copyMatrix(matrix, newMatrix);
addMean(matrix, newMatrix);
printAdjacentMatrix(newMatrix);
}
private static void initializeFirstColumn(String[][] newMatrix) {
newMatrix[1][0] = "A";
newMatrix[2][0] = "B";
newMatrix[3][0] = "C";
newMatrix[4][0] = "D";
newMatrix[5][0] = "X";
}
private static void printAdjacentMatrix(String[][] newMatrix) {
for (int row = 0; row < newMatrix.length; row++) {
for (int column = 0; column < newMatrix[row].length; column++) {
System.out.print(newMatrix[row][column] + " ");
}
System.out.println();
}
}
private static void addMean(int[][] matrix, String[][] newMatrix) {
int mean = 0;
int sum = 0;
int divident = 0;
for (int j = 0; j < matrix[0].length; j++) {
sum = 0;
divident = 0;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][j] != 0) {
sum += matrix[i][j];
divident++;
}
}
if (sum != 0) {
mean = sum / divident;
}
newMatrix[5][j + 1] = "" + mean;
}
}
private static void copyMatrix(int[][] matrix, String[][] newMatrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
newMatrix[i + 1][j + 1] = "" + matrix[i][j];
}
}
}
private static void initializeFirstRow(String[][] newMatrix) {
newMatrix[0][0] = " ";
newMatrix[0][1] = "A";
newMatrix[0][2] = "B";
newMatrix[0][3] = "C";
newMatrix[0][4] = "D";
}
}
Also add following line in Main.java
g.convertMatrix(g.adjacentMatrix);

Categories

Resources