The Task is
"You've got a adjacency matrix (nxn). And simple graph. Print YES, if the graph is undirected and NO otherwise."
My teacher says that the programm is incorrect. Why?
import java.util.Scanner;
public class Graph {
private static Scanner scan;
public static void main(String[] args){
scan = new Scanner(System.in);
final int n = scan.nextInt();
Graph graph = new Graph();
int[][] matrix = graph.createMatrix(n);
boolean truth = graph.checkoriented(matrix);
System.out.println((truth)? "Yes": "No");
scan.close();
}
private boolean checkoriented(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(matrix[i][j] == 1){ //look if element on i pow, j column is "1";
boolean way = (matrix[j][i] == 1)? true: false; //if element on j pow i locumn is 1 also
if(!way) return false; // if element on j pow i locumn is 0 graph is oriented
}
}
}
return true;
}
private int[][] createMatrix(int n) {
int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
matrix[i][j] = scan.nextInt();
}
}
return matrix;
}
}
I don't know if it is actually a problem, but if your output should be YES or NO you'd better print these instead of Yes and No here System.out.println((truth)? "Yes": "No");.
P. S. If your graph has a way from the vertex to the same one (I mean matrix[i][i] = 1), your algorithm might consider the graph to be undirected, while it is not.
Based on the discussion and A. Yurchenko's inputs, I'm updating my answer for completeness (only).
private boolean checkoriented(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(i == j && matrix[i][j] !=0) {
return false;
}
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
I have been working on this java code for the doomsday-fuel problem which deals with the absorbing markov chains. It has passed every test except for test four. Is there any particular type of input I may have missed while testing my code? I have only about 12 hours left. I have tested four one dimensional arrays and am curious as to if this test failure is somehow a precision error or something else.
Context:
Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultimately reach, not all of which are useful as fuel.
Commander Lambda has tasked you to help the scientists increase fuel creation efficiency by predicting the end state of a given ore sample. You have carefully studied the different structures that the ore can take and which transitions it undergoes. It appears that, while random, the probability of each structure transforming is fixed. That is, each time the ore is in 1 state, it has the same probabilities of entering the next state (which might be the same state). You have recorded the observed transitions in a matrix. The others in the lab have hypothesized more exotic forms that the ore can become, but you haven't seen all of them.
Write a function solution(m) that takes an array of array of nonnegative ints representing how many times that state has gone to the next state and return an array of ints for each terminal state giving the exact probabilities of each terminal state, represented as the numerator for each state, then the denominator for all of them at the end and in simplest form. The matrix is at most 10 by 10. It is guaranteed that no matter which state the ore is in, there is a path from that state to a terminal state. That is, the processing will always eventually end in a stable state. The ore starts in state 0. The denominator will fit within a signed 32-bit integer during the calculation, as long as the fraction is simplified regularly.
public static int[] returnFractionPair(double x) {
double tolerance = 1.0E-14;//Handles the extent of precision used
double numerator=1;//Kept as one because initially the decimal may be greater than zero
double numeratorStorage=0;
double denominator=0;
double denominatorStorage=1;//prevents division by zero
double decimal = x;
double comparison = 0;
do {
double flooredDecimal = (double)(int)decimal;//Floors decimal
double aux = numerator;//Sets auxilary to be the numerator
numerator =(flooredDecimal*numerator)+numeratorStorage;
numeratorStorage = aux;
aux = denominator;
denominator = (flooredDecimal*denominator)+denominatorStorage;
denominatorStorage = aux;
decimal = 1/(decimal-flooredDecimal);
comparison = x-(numerator/denominator);
} while( returnAbs(comparison) > (x*tolerance) );//Tests if the difference between the initial decimal and this new numerator/denominator is greater than that of x multiplied by the level of tolerance it has
int[] res = new int[]{(int)numerator, (int)denominator};
return res;
}
public static double returnAbs(double value){
if(value < 0){
value *= -1;
}
return value;
}
public static int getLCD(int[][] fractions){
int num = 0;
int den = 1;
int lcd = 1;
for(int i = 0; i < fractions.length; i++){
lcd *= fractions[i][den];
}
for(int i = 2; i < lcd; i++){
boolean foundLeastCommon = true;
for(int j = 0; j < fractions.length; j++){
if( (double)( i%fractions[j][den] ) != 0){
foundLeastCommon = false;
}
}
if(foundLeastCommon == true){
lcd = i;
return lcd;
}
}
return lcd;
}
public static double[] returnRowSums(int[][] matrix){
//Assume all values in matrix are positive
double[] sumsOfEachRow = new double[matrix.length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
sumsOfEachRow[i] += matrix[i][j];
}
}
return sumsOfEachRow;
}
public static double returnMatrixCellSum(double[] row, double[] column){//Assume row size == column size.
if(row.length != column.length){
return 0;
}
double sum = 0;
for(int i = 0; i < row.length; i++){
sum += (column[i] * row[i]);
}
return sum;
}
public static int[] returnRearrangedIndices(double[] sumsOfEachRow){
int[] indicesOfRearrangedMatrix = new int[sumsOfEachRow.length];
int indicesIndex = 0;
for(int i = 0; i < sumsOfEachRow.length; i++){
if(sumsOfEachRow[i] <= 1){
indicesOfRearrangedMatrix[indicesIndex] = i;
indicesIndex++;
}//TerminalStates first
}
for(int i = 0; i < sumsOfEachRow.length; i++){
if(sumsOfEachRow[i] > 1){
indicesOfRearrangedMatrix[indicesIndex] = i;
indicesIndex++;
}
}
return indicesOfRearrangedMatrix;
}
public static double[][] subtractMatrix(double[][] matrix1, double[][] matrix2){//assumes matrices are of same dimensions
double[][] matrix3 = new double[matrix1.length][matrix1.length];
for(int i = 0; i < matrix1.length;i++){
for(int j = 0; j < matrix1[i].length; j++){
matrix3[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return matrix3;
}
public static double[][] rotateMatrix(double[][] matrix){
double[][] rotatedMatrix = new double[matrix[0].length][matrix.length];
for(int i = 0; i < rotatedMatrix.length;i++){
for(int j = 0; j < rotatedMatrix[0].length; j++){
rotatedMatrix[i][j] = matrix[j][i];
}
}
return rotatedMatrix;
}
public static double[][] getRemainingValues(double[][] matrix, int rowIgnored, int columnIgnored){
double[][] newMatrix = new double[matrix.length-1][matrix.length-1];
int iC = 0;
int iR = 0;
for(int k = 0; k < matrix.length; k++){
if(k != rowIgnored){
iR = 0;
for(int j = 0; j < matrix[k].length;j++){
if(j != columnIgnored){
newMatrix[iC][iR] = matrix[k][j];
iR++;
}
}
iC++;
}
}
return newMatrix;
}
public static double getDeterminant(double[][] matrix){
//uses top rows only
double determinant = 0;
if(matrix.length == 1 && matrix[0].length == 1){
return matrix[0][0];
}
boolean negative = false;
double[][] newMatrix = new double[matrix.length-1][matrix.length-1];
for(int i = 0; i < matrix.length; i++){
newMatrix = getRemainingValues(matrix, 0, i);
if(negative == false){
determinant += matrix[0][i]*getDeterminant(newMatrix);
negative = true;
}else{
determinant -= matrix[0][i]*getDeterminant(newMatrix);
negative = false;
}
//System.out.println(determinant);
}
return determinant;
}
public static double[][] getMinorMatrix(double[][] matrix){
double[][] newMatrix = new double[matrix.length][matrix.length];
double[][] remainderMatrix;
if(matrix.length-1 != 0){
remainderMatrix = new double[matrix.length-1][matrix.length-1];
}else{
remainderMatrix = new double[matrix.length][matrix.length];
}
for(int i = 0; i < newMatrix.length;i++){
for(int j = 0; j < newMatrix.length;j++){
remainderMatrix = getRemainingValues(matrix, i, j);
newMatrix[i][j] = getDeterminant(remainderMatrix) + 0.0;//Prevent -0.0 float values
}
}
return newMatrix;
}
public static double[][] divideMatrixByScalar(double[][] matrix, double scalar){
double[][] newMatrix = new double[matrix.length][matrix[0].length];
newMatrix = matrix;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length;j++){
newMatrix[i][j] /= scalar;
}
}
return newMatrix;
}
public static double[][] invertMatrix(double[][] matrix){
double[][] minorMatrix = new double[matrix.length][matrix.length];
if(minorMatrix.length == 2){
minorMatrix = matrix;
double temp = minorMatrix[0][0];
minorMatrix[0][0] = minorMatrix[1][1];
minorMatrix[1][1] = temp;
minorMatrix[0][1] *= -1;
minorMatrix[0][1] += 0;
minorMatrix[1][0] *= -1;
minorMatrix[1][0] += 0;
for(int i = 0; i < minorMatrix.length; i++){
for(int j = 0; j < minorMatrix[i].length; j++){
System.out.print(minorMatrix[i][j] + " ");
}
System.out.print("\n");
}
}else{
minorMatrix = getMinorMatrix(matrix);
System.out.println("Getting minorMatrix");
for(int i = 0; i < minorMatrix.length; i++){
for(int j = 0; j < minorMatrix[i].length; j++){
System.out.print(minorMatrix[i][j] + " ");
}
System.out.print("\n");
}
boolean isNegative = false;
System.out.println("Getting adjoint of minorMatrix");//Not doing things correctly
for(int i = 0; i < minorMatrix.length;i++){
for(int j = 0; j < minorMatrix[i].length;j++){
if(isNegative == true){
minorMatrix[i][j] *= -1;
minorMatrix[i][j] += 0;
isNegative = false;
}else{
isNegative = true;
}
System.out.print(minorMatrix[i][j] + " ");
}
if(minorMatrix[i].length % 2 == 0){
if(isNegative == true){
isNegative = false;
}else{
isNegative = true;
}
}
System.out.print("\n");
}
minorMatrix = rotateMatrix(minorMatrix);//rotates the minorMatrix
}
double determinant = getDeterminant(matrix);
System.out.println(determinant);
if(determinant != 0){
minorMatrix = divideMatrixByScalar(minorMatrix, determinant);
System.out.println("Result");
for(int i = 0; i < minorMatrix.length; i++){
for(int j = 0; j < minorMatrix[i].length; j++){
System.out.print(minorMatrix[i][j] + " ");
}
System.out.print("\n");
}
return minorMatrix;//Inverse is good
}else{
return matrix;
}
}
public static double[][] returnUnabsorbedToUnabsorbed(double[][] matrix, int terminalStates){//Assumes matrix layers go from absorbed to unabsorbed
double[][] unabsorbedToUnabsorbed = new double[matrix.length-terminalStates][matrix.length-terminalStates];
int uIndex = 0;
int uuIndex = 0;
for(int i = terminalStates; i < matrix.length;i++){
uuIndex = 0;
for(int j = terminalStates; j < matrix.length;j++){
unabsorbedToUnabsorbed[uIndex][uuIndex] = matrix[i][j];
uuIndex++;
}
uIndex++;
}
return unabsorbedToUnabsorbed;
}
public static double[][] returnUnabsorbedToAbsorbed(double[][] matrix, int terminalStates){//Assumes matrix layers go from absorbed to unabsorbed
double[][] unabsorbedToAbsorbed = new double[matrix.length-terminalStates][terminalStates];
int uIndex = 0;
int uuIndex = 0;
for(int i = terminalStates; i < matrix.length;i++){
uuIndex = 0;
for(int j = 0; j < terminalStates;j++){
unabsorbedToAbsorbed[uIndex][uuIndex] = matrix[i][j];
uuIndex++;
}
uIndex++;
}
return unabsorbedToAbsorbed;
}
public static double[][] getFundamental(double[][] matrix){
double[][] modifiedMatrix = new double[matrix.length][matrix[0].length];
modifiedMatrix = matrix;
double[][] identity = new double[matrix.length][matrix.length];
for(int i = 0; i < identity.length; i++){
for(int j = 0;j < identity[i].length;j++){
if(i == j){
identity[i][j] = 1;
}else{
identity[i][j] = 0;
}
}
}
modifiedMatrix = subtractMatrix(identity, modifiedMatrix);//Modified matrix is returning properly
/*System.out.println("Getting matrix to be inverted");
for(int i = 0; i < modifiedMatrix.length; i++){
for(int j = 0; j < modifiedMatrix[i].length; j++){
System.out.print(modifiedMatrix[i][j] + " ");
}
System.out.print("\n");
}*/
modifiedMatrix = invertMatrix(modifiedMatrix);//Problem here(?)
return modifiedMatrix;
}
public static double[][] multiplyMatrix(double[][] matrix1, double[][] matrix2){//Assume all rows are equal.
double[][] result = new double[matrix1.length][matrix2[0].length];
double[][] rotatedM2 = new double[matrix2[0].length][matrix2.length];
rotatedM2 = rotateMatrix(matrix2);
for(int i = 0; i < result.length;i++){
for(int j = 0; j < result[i].length; j++){
result[i][j] = returnMatrixCellSum(matrix1[i], rotatedM2[j]);
//RotateMatrix does not increase matrix sums by how it should be
}
}
return result;
}
public static int[] algorithm(int[][] matrix, int startingPoint){
if(matrix.length == 0){
return new int[]{0, 1};
}
if(matrix.length == 1){
int[] ans = new int[matrix.length+1];
for(int i = 0; i < ans.length;i++){
ans[i] = 1;
}
for(int i = 0; i < ans.length; i++){
System.out.println(ans[i]);
}
return ans;
}
double[] sumsOfEachRow = new double[matrix.length];
sumsOfEachRow = returnRowSums(matrix);
double[][] probMatrix = new double[matrix.length][matrix.length];
int terminalStates = 0;//Number of terminal states
for(int i = 0; i < probMatrix.length; i++){
for(int j = 0; j < probMatrix[i].length; j++){
if(sumsOfEachRow[i] != 0){
probMatrix[i][j] = (double)matrix[i][j];
probMatrix[i][j] /= sumsOfEachRow[i];
}else{
probMatrix[i][j] = 0;
}
}
}
boolean startingIsTerminal = false;
for(int i = 0; i < probMatrix.length;i++){
boolean foundOne = false;
for(int j = 0; j < probMatrix[i].length;j++){
if(probMatrix[i][j] == 1 && i == j){
terminalStates++;
foundOne = true;
if(i == startingPoint){
startingIsTerminal = true;
}
}
}
if(foundOne == false){
if(sumsOfEachRow[i] == 0){
terminalStates++;
}
}
}
if( (sumsOfEachRow[startingPoint] == 0) || startingIsTerminal == true){
int[] ans = new int[terminalStates+1];
for(int i = 0; i < terminalStates;i++){
if(i != startingPoint){
ans[i] = 0;
}else{
ans[i] = 1;
}
}
ans[terminalStates] = 1;
for(int i = 0; i < ans.length; i++){
System.out.println(ans[i]);
}
return ans;
}
int[] indicesOfRearrangedMatrix = new int[probMatrix.length];
indicesOfRearrangedMatrix = returnRearrangedIndices(sumsOfEachRow);
double[][] rearranged = new double[probMatrix.length][probMatrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
rearranged[i][j] = probMatrix[indicesOfRearrangedMatrix[i]][indicesOfRearrangedMatrix[j]];
System.out.print(rearranged[i][j] + " ");
}
System.out.print("\n");
}//Get rearranged matrix divided
System.out.println("Matrix rearranged");
double[][] unabsorbedToUnabsorbed = new double[probMatrix.length-terminalStates][probMatrix.length-terminalStates];
unabsorbedToUnabsorbed = returnUnabsorbedToUnabsorbed(rearranged, terminalStates);//Get Unabsorbed Matrix
for(int i = 0; i < unabsorbedToUnabsorbed.length; i++){
for(int j = 0; j < unabsorbedToUnabsorbed[i].length; j++){
System.out.print(unabsorbedToUnabsorbed[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("unabsorbedToUnabsorbed");
double[][] unabsorbedToAbsorbed = new double[probMatrix.length-terminalStates][terminalStates];
unabsorbedToAbsorbed = returnUnabsorbedToAbsorbed(rearranged, terminalStates);
for(int i = 0; i < unabsorbedToAbsorbed.length; i++){
for(int j = 0; j < unabsorbedToAbsorbed[i].length; j++){
System.out.print(unabsorbedToAbsorbed[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("unabsorbedToAbsorbed");
double[][] fundamental = new double[unabsorbedToUnabsorbed.length][unabsorbedToUnabsorbed.length];
fundamental = getFundamental(unabsorbedToUnabsorbed);//Gets fundamental
double[][] probResult = multiplyMatrix(fundamental, unabsorbedToAbsorbed);
System.out.println("ProbResult got");
for(int i = 0; i < probResult.length; i++){
for(int j = 0; j < probResult[i].length; j++){
System.out.print(probResult[i][j] + " ");
}
System.out.print("\n");
}
int[][] fractionPairs = new int[terminalStates][2];
for(int i = 0; i < probResult[startingPoint].length; i++){
fractionPairs[i] = returnFractionPair(probResult[startingPoint][i]);
}
int lcd = getLCD(fractionPairs);
int[] ans = new int[terminalStates+1];
int num = 0;
int den = 1;
for(int i = 0; i < fractionPairs.length;++i){
int newNumerator = (lcd/fractionPairs[i][den]) * fractionPairs[i][num];
ans[i] = newNumerator;
}
ans[ans.length-1] = lcd;
for(int i = 0; i < ans.length; i++){
System.out.println(ans[i]);
}
return ans;
}
public static int[] solution(int[][] m) {
return algorithm(m, 0);
}
}
So I've been looking into creating a simple tic-tac-toe game where the human player plays against an ai run by the minimax algorithm. I have spent the last few days trying to figure these two bugs out but I cant for the life of me seem to. for one, the ai seems sort of predictable and not very good. Secondly, the only way it seems to work is if the ai goes first, if I have the human player go first, the ai just continues to fill the next available spot. Any help would be super appreciated.
Here's my code:
import java.util.Scanner;
public class Game
{
static String player = "X";
static String opponent = "O";
int row;
int col;
public Game(int x, int y)
{
row = x;
col = y;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String [][] board = new String [3][3];
fillBoard(board);
while(true) //Infinite loop only for testing, will change back
{
getBestMove(board);
printBoard(board);
playerTurn(board, input);
printBoard(board);
//System.out.println("Best move: " + bestMove.row + " " + bestMove.col);
}
//input.close();
}
static int checkState(String [][] board)
{
for (int row = 0; row<3; row++) //Rows
{
if (board[row][0] == board[row][1] &&
board[row][1] == board[row][2])
{
if (board[row][0]==player)
return -10;
else if (board[row][0]==opponent)
return +10;
}
}
for (int col = 0; col<3; col++) //Columns
{
if (board[0][col]==board[1][col] &&
board[1][col]==board[2][col])
{
if (board[0][col]==player)
return -10;
else if (board[0][col]==opponent)
return +10;
}
}
if (board[0][0]==board[1][1] && board[1][1]==board[2][2]) //Diagonal
{
if (board[0][0]==player)
return -10;
else if (board[0][0]==opponent)
return +10;
}
else if (board[0][2]==board[1][1] && board[1][1]==board[2][0]) //Diagonal
{
if (board[0][2]==player)
return -10;
else if (board[0][2]==opponent)
return +10;
}
return 0;
}
public static void getBestMove(String[][] board)
{
int bestValue = -1000;
Game bestMove = new Game(-1,-1);
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(board[i][j] == "-")
{
board[i][j] = player;
int currentValue = minimax(board, 0, false);
board[i][j] = "-";
if(currentValue > bestValue)
{
bestMove.row = i;
bestMove.col = j;
bestValue = currentValue;
}
}
}
}
board[bestMove.row][bestMove.col]= opponent;
}
public static int minimax(String [][] board, int depth, boolean isMaximizer)
{
if(checkState(board) != 0)
return checkState(board);
if(checkRemainingPlays(board) == false)
return 0;
if(isMaximizer)
{
int highest = -1000;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(board[i][j] == "-")
{
board[i][j] = player;
highest = Math.max(highest, minimax(board, depth + 1, !isMaximizer));
board[i][j] = "-";
}
}
}
return highest;
}
else
{
int lowest = 1000;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(board[i][j] == "-")
{
board[i][j] = opponent;
lowest = Math.min(lowest, minimax(board, depth + 1, !isMaximizer));
board[i][j] = "-";
}
}
}
return lowest;
}
}
public static void playerTurn(String [][] board , Scanner input)
{
input = new Scanner(System.in);
System.out.println("Player 1: ");
System.out.println("Please enter the index of desired spot (I) ");
int desiredIndexI = input.nextInt();
System.out.println("Please enter the index of desired spot (J) ");
int desiredIndexJ = input.nextInt();
while(board[desiredIndexI][desiredIndexJ] != "-")
{
System.out.println("Please enter the index of desired spot (I) ");
desiredIndexI = input.nextInt();
System.out.println("Please enter the index of desired spot (J) ");
desiredIndexJ = input.nextInt();
}
board[desiredIndexI][desiredIndexJ] = player;
}
public static boolean checkRemainingPlays(String [][] board)
{
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
if (board[i][j] == "-")
return true;
}
}
return false;
}
public static void printBoard(String [][] board)
{
for(int i = 0; i < board.length; i++)
{
if(i <= 2 && i > 0)
System.out.println("----------");
for(int j = 0; j < board[i].length; j++)
{
if(j < 2)
System.out.print(board[i][j] + " | ");
if(j == 2)
System.out.println(board[i][j]);
}
}
}
public static void fillBoard(String [][] board)
{
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
board[i][j] = "-";
}
}
}
}
At first, I'd like to start with the good news. Solving Tic Tac Toe with the minimax algorithm is a great training for beginners in Artificial Intelligence. The problem isn't to easy and it teaches well what AI planning is. Using Java for realizing the game plus the solver is also a good choice, because the language runs everywhere, supports object-oriented programming and is reasonable fast to execute.
Now I'd like to introduce the critical aspects. The first problem is, that AI related problems are quite different from normal computing tasks. If the sourcecode is about painting a AWT Java GUI to the screen, or about how to send a parameter to a class, I'm sure the question can be answered easily. In most cases, AI topics doesn't fail because of programming issues which means how to use a certain programming language but because of the underlying algorithm.
The discussion space in which AI problems are described and solved isn't within the programming domain but within the Gutenberg galaxy. Which means, around TicTacToe gameplaying with Artificial Intelligence and for the Minimax algorithm, there are at least 1000 papers, books and powerpoint presentations available. The task for the newbie isn't to write Java sourcecode, but to read and cite these sources. This helps other to understand the problem and provide detailed feedback.
I know, this moral instruction isn't answering the original question but the aim was to explain why I've pressed the button “migrate the question to https://ai.stackexchange.com/”. In this forum the question will get an answer quickly.
I am trying a simple sudoku program. i started by taking the values in a 3D
array and then copied them into a 1D array by using mr.serpardum's method.
i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output
says "its a sudoku" but i can't to find it...apparently i can't add any
image coz i dont have enough credits
public class SecondAssignment {
#SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}
//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}
You can update your code to following
//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}
You should have used break as soon as the match was found.
This code just checks if duplicate element is present in the array (of size 9) or not.
Hello I am trying to understand the code I have written and why does it print the output below
public void isSymmetricNow(int[][] matrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
}
}
}
System.out.print("matrix is symmetric \n");
}
prints me
matrix is not symmetric
matrix is not symmetric
matrix is symmetric
ASSUME THAT the given matrix is not symmetric here.
int matrix3[][] = {{1,4,7},{-4,6,6},{7,6,9}};
How can I modify this code to give me back saying if the matrix is symmetric or not only once.
Just a plain return statement will do. It will not execute again if the condition is false.
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
return;
}
}
}
System.out.print("matrix is symmetric \n");
}
Or
You could return a boolean saying it is a Symmetric or not.
public boolean isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
then call it using your function.
if(isSymmetric(matrix))
System.out.println("Symmetric");
else
System.out.println("Not Symmetric");
First of all, your loops will print "matrix is not symmetric \n" whenever they find i and j for which matrix[i][j] != matrix[j][i], which can happen more than once.
and System.out.print("matrix is symmetric \n"); is always called, so that explains the last line of output.
You probably want your method to have a boolean return value instead of printing this output. This way the loops will only iterate until you find out that the matrix is not symmetric.
public boolean isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
To do the same without a return value :
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
boolean isSymmetric = true;
for (int i = 0; i < matrix.length && isSymmetric; i++) {
for (int j = 0; j < matrix.length && isSymmetric; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
isSymmetric = false;
}
}
}
if (isSymmetric)
System.out.print("matrix is symmetric \n");
}
1) As Eran pointed out, i and j aren't equal more than once and hence will keep printing for as long as the loop iterates. I suggest using a break statement to exit out of the loop the very first time it finds that i != j.
2)The last print statement will be called irrespective of how the the loop behaves and whether the matrix is symmetric or not. I suggest printing that the matrix is symmetric by creating another if statement outside the loop to check symmetry.
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
return; //When it does not symetric, return.
}
}
}
System.out.print("matrix is symmetric \n");
}
basically I need to input two numbers and they will be the side size of two squares (drawn one inside of the other, being the inside square positioned in the middle of the biggest square).
I really have no idea how to do this, and the only thing that I was able to come up with was inputing a value and having one drawn square:
package teste;
import java.util.Scanner;
public class Main {
private static Scanner sc;
public static void main(String a[])
{
int size=0;
System.out.print("Enter size: ");
sc = new Scanner(System.in);
size = sc.nextInt();
for(int i=1; i <= size; i++){
for(int j=1; j <= size; j++){
if(i==1 || i==size || j==1 || j==size)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
I know it is not much, but my java skills are limited. Can you guys show a way to do it? I have no idea how to draw the square inside.
Thanks in advance.
The simplest way i see is just make a buffer where you will fill the characters you want to draw in console
// init buffer
char buffer[][] = new char[size][];
for (int i = 0; i < size; i ++) {
buffer[i] = new char[size];
}
// borders of first square
final int sq1Start = 0;
final int sq1End = size-1;
// draw outer square
for(int i = sq1Start; i <= sq1End; i ++){
for (int j = sq1Start; j <= sq1End; j ++) {
if (i == sq1Start || i == sq1End || j == sq1Start || j == sq1End) {
buffer[i][j] = '*';
}
}
}
// borders of second square
final int sq2Start = size / 4;
final int sq2End = size * 3 / 4;
// draw inner square
for (int i = sq2Start; i <= sq2End; i++) {
for (int j = sq2Start; j <= sq2End; j++) {
if (i == sq2Start || i == sq2End || j == sq2Start || j == sq2End) {
buffer[i][j] = '*';
}
}
}
for (int i = 0; i < size; i ++) {
for (int j = 0; j < size; j ++) {
System.out.print(buffer[i][j]);
}
System.out.println();
}
Hope it would be helpful