public class AirplaneLab
{
private int [][] first;
private int [][] economy;
private boolean [] seat;
private boolean okay;
private boolean okayokay;
public AirplaneLab()
{
}
public AirplaneLab(int [][] first1, int [][] economy1)
{
}
public boolean viewFirstClass(boolean set[], int [][] first, int [][] economy)
{
if (okay = true)
{
boolean seating1[] = new boolean[20];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if(seat[((j + 1) + (i * 4)) - 1])
{
System.out.print("x ");
seating1[i * j] = true;
}
else
{
System.out.print("o ");
seating1[i * j] = flase;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating1[];
}
else
{
return false;
}
}
public boolean viewEconomyClass(boolean set[], int [][] first, int [][] economy)
{
if (okayokay = true)
{
boolean seating2[] = new boolean[30];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
if(seat[((j + 1) + (i * 3)) - 1])
{
System.out.print("x ");
seating2[i * j] = true;
}
else
{
System.out.print("o ");
seating2[i * j] = false;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating2[];
}
else
{
return false;
}
}
public void decision()
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1 for “booking in first class”");
System.out.println("2 for “booing in economy class”");
System.out.println("3 to view seating chart for first class ");
System.out.println("4 to view seating chart for economy class");
System.out.println("0 to exit");
System.out.print("? ");
while(true)
{
int mOpt = input.nextInt();
if ((mOpt == 1) || (mOpt == 3))
{
if (mOpt == 1)
{
okay = true;
System.out.println("Based on the following setting arrangement, please pick a window middle or end seat");
viewFirstClass(boolean set[], int [][] first, int [][] economy);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (seating1[i * j] == true)
{
if ((i * j) ________________)
}
}
}
}
}
}
}
}
In the code above, where the blank is:
The last if statement before all of the closed brackets:
I was wondering how you would use module there.
Let's say I wanted to do (i * j) module of 4; how would I do that? Can you fill in the blank? Thank you for your help!
If you are looking for some thing (modulo) like
if ((i * j) mod 4 )
in java ,the syntax would be
if ((i * j) % 4 )
Related
My code doesn't work and i don't know either why or how to make it work. This is my code.
public static void ex5(){
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
int m = 1;
for (int i = 2; i < givenNr; i++){
while (m <= i/2 ){
if(i % m != 0) {
System.out.print(i + " ");
}
m++;
}
}
}
public static void ex5() {
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
for (int i = 2; i < givenNr; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
all code
package ubung;
import java.util.Random;
//-------------------------------------------------------------- a)
public class Sudoku {
final int n = 3;
final int gridsize = n*n;
int[][] field = new int[gridsize][gridsize];
Random random = new Random();
public Sudoku() {
int[] firstRow = {1,2,3,4,5,6,7,8,9};
//h): int[] firstRow = randomRow();
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
field[i][j] = (i*n + i/n + j) % gridsize + 1;
//h): field[i][j] = firstRow[(i*n + i/n + j) % gridsize];
System.out.println(this);
}
//------------------------------------------------------------- g)
public Sudoku(int permutationCount) {
this();
randomPermutation(permutationCount);
}
//-------------------------------------------------------------- b)
/**Die Methode gibt ein Sudoku-Objekt als einen String zurueck
* #return der String eines Sudoku-Objektes
*/
public String toString() {
String str = line(25);
for(int i = 0; i < 9; i++){
str += "|";
for(int j = 0; j < 9; j++){
str += " " + get(i,j);
if(j == 2 || j == 5 || j == 8)
str += " |";
}
str += "\n";
if(i == 2 || i == 5 || i == 8){
str += line(25);
}
}
return str;
}
/**
* Getter for single entries
*/
private String get(int i, int j) {
if(i < 0 || i > gridsize + 1 || j < 0 || j > gridsize + 1) {
return " ";
}
int m = field[i][j];
if(m == 0)
return " ";
return ""+m;
}
private String line(int n){
String str = "";
for(int i = 0; i < n; i++)
str += "-";
return str+"\n";
}
//-------------------------------------------------------------- c)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions. ?????????????????????????
*/
private void permutateRows(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
for(int i = 0; i < gridsize; i++) {
int temp = field[i][a-1];
field[i][a-1] = field[i][b-1];
field[i][b-1] = temp;
}
}
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions. ????????????????????
*/
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
//-------------------------------------------------------------- d)
/**
* Two stacks are swapped. This produces 3! as much solutions.
*/
private void permutateStacks(int a, int b) {
if(b < a) {
permutateStacks(b,a);
return;
}
if(a == 1 && b == 2) {
permutateColumns(1,4);
permutateColumns(2,5);
permutateColumns(3,6);
}
else if(a == 1 && b == 3) {
permutateColumns(1,7);
permutateColumns(2,8);
permutateColumns(3,9);
}
else if(a == 2 && b == 3) {
permutateColumns(4,7);
permutateColumns(5,8);
permutateColumns(6,9);
}
}
/**
* Two bands are swapped. This produces 3! as much solutions.
*/
private void permutateBands(int a, int b) {
if(b < a) {
permutateBands(b,a);
return;
}
if(a == 1 && b == 2) {
permutateRows(1,4);
permutateRows(2,5);
permutateRows(3,6);
}
else if(a == 1 && b == 3) {
permutateRows(1,7);
permutateRows(2,8);
permutateRows(3,9);
}
else if(a == 2 && b == 3) {
permutateRows(4,7);
permutateRows(5,8);
permutateRows(6,9);
}
}
//-------------------------------------------------------------- e)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions.
*/
private void permutateRows() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateRows(a+block*3,b+block*3);
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions.
*/
private void permutateColumns() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateColumns(a+block*3,b+block*3);
}
private void permutateStacks() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateStacks(a,b);
}
private void permutateBands() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateBands(a,b);
}
//-------------------------------------------------------------- f)
/**
* The matrix is transposed. This produces double as much solutions.
*/
private void transpose() {
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < i; j++) {
int temp = field[j][i];
field[j][i] = field[i][j];
field[i][j] = temp;
}
}
//-------------------------------------------------------------- g)
private void randomPermutation(){
switch(random.nextInt(5)) {
case 0: permutateRows(); break;
case 1: permutateColumns(); break;
case 2: permutateStacks(); break;
case 3: permutateBands(); break;
case 4: transpose();
default:
}
}
private void randomPermutation(int n){
for(int i = 0; i < n; i++)
randomPermutation();
}
//-------------------------------------------------------------- h)
/**
* Returns random row of digits. Used to relabel digits in the initial matrix
* This yields 9! as much solutions.
*/
private int[] randomRow(){
boolean[] used = new boolean[gridsize];
int[] row = new int[gridsize];
for(int i = 0; i < gridsize; i++) {
int candidate = random.nextInt(gridsize);
if(!used[candidate]){
used[candidate] = true;
row[i] = candidate+1;
}
else {
i--;
}
}
return row;
}
//-------------------------------------------------------------- i)
private void hide(int n) {
if(n < 0)
n = 0;
if(n > 81)
n = 81;
for(int k = 0; k < n; k++) {
int i = random.nextInt(9); //在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值。
int j = random.nextInt(9);
if(field[i][j] != 0)
field[i][j] = 0;
else
k--;
}
}
/*****************************************/ //gegeben
public static void main(String[] args){
Sudoku s = new Sudoku(100000);
System.out.println(s);
s.hide(50);
System.out.println(s);
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
If we notate the indices of the 2D array as field[x][y], the provided solution code uses x as the column index and y as the row index. It is important to note that the provided method is not the only correct solution. It would be just as correct to implement x as the row index and y as the column index, so long as the methods were implemented correctly.
I cannot get my write to file code working the error message- writeFile cannot be resolved. I a trying to write the board positions to a text file so the game can be saved. If the user chooses to save the game then it should call a new subroutine that will write the pieces to the file.
/*
* Skeleton program code for the AQA COMP1 Summer 2016 examination
* This code to be used in conjunction with the Preliminary Material
* written by the AQA Programmer Team
* Developed in the NetBeans 7.3.1. programming environment
* Additional classes AQAConsole2016, AQAReadTextFile2016 and
* AQAWriteTextFile2016 may be used.
*
* A package name may be chosen and private and public modifiers added -
* permission to make these changes to the Skeleton Program does not need
* to be obtained from AQA or the AQA Programmer
*/
import java.util.Random;
public class Aaa {
AQAConsole2016 console = new AQAConsole2016();
Random random = new Random();
int boardSize;
public Aaa() {
char choice;
String playerName;
// int boardSize;
boardSize = 6;
playerName = "";
do {
displayMenu();
choice = getMenuChoice(playerName);
switch (choice) {
case 'p' : playGame(playerName, boardSize);
break;
case 'e' : playerName = getPlayersName();
break;
case 'c' : boardSize = changeBoardSize();
break;
}
} while (choice != 'q');
}
void setUpGameBoard(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (row == (boardSize + 1) / 2 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2 + 1) {
board[row][column] = 'C';
} else {
if (row == (boardSize + 1) / 2 + 1 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2) {
board[row][column] = 'H';
} else {
board[row][column] = ' ';
}
}
}
}
}
int changeBoardSize() {
int boardSize;
do {
console.print("Enter a board size (between 4 and 9): ");
boardSize = console.readInteger("");
} while (!(boardSize >= 4 && boardSize <= 9));
return boardSize;
}
int getHumanPlayerMove(String playerName) {
int coordinates;
console.print(playerName + " enter the coordinates of the square where you want to place your piece: ");
coordinates = console.readInteger("");
return coordinates;
}
int getComputerPlayerMove(int boardSize) {
return ((random.nextInt(boardSize) + 1) * 10 + (random.nextInt(boardSize) + 1));
}
boolean gameOver(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == ' ')
return false;
}
}
return true;
}
String getPlayersName() {
String playerName;
console.print("What is your name? ");
playerName = console.readLine();
return playerName;
}
boolean checkIfMoveIsValid(char[][] board, int move) {
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (((row<=boardSize) &&(row>0)) && ((column<=boardSize) && (column>0))){
if (board[row][column] == ' ') {
moveIsValid = true;
}
}
return moveIsValid;
}
int getPlayerScore(char[][] board, int boardSize, char piece) {
int score;
score = 0;
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == piece) {
score = score + 1;
}
}
}
return score;
}
boolean checkIfThereArePiecesToFlip(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipStillPossible;
boolean flipFound;
boolean opponentPieceFound;
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
flipStillPossible = true;
flipFound = false;
opponentPieceFound = false;
while (rowCount <= boardSize && rowCount >= 1 && columnCount >= 1 && columnCount <= boardSize && flipStillPossible && !flipFound ) {
if (board[rowCount][columnCount] == ' ') {
flipStillPossible = false;
} else {
if (board[rowCount][columnCount] != board[startRow][startColumn]) {
opponentPieceFound = true;
} else {
if (board[rowCount][columnCount] == board[startRow][startColumn] && !opponentPieceFound) {
flipStillPossible = false;
} else {
flipFound = true;
}
}
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
return flipFound;
}
void flipOpponentPiecesInOneDirection(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipFound;
flipFound = checkIfThereArePiecesToFlip(board, boardSize, startRow, startColumn, rowDirection, columnDirection);
if (flipFound) {
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
while (board[rowCount][columnCount] != ' ' && board[rowCount][columnCount] != board[startRow][startColumn]) {
if (board[rowCount][columnCount] == 'H') {
board[rowCount][columnCount] = 'C';
} else {
board[rowCount][columnCount] = 'H';
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
}
}
void makeMove(char[][] board, int boardSize, int move, boolean humanPlayersTurn) {
int row;
int column;
row = move % 10;
column = move / 10;
if (humanPlayersTurn) {
board[row][column] = 'H';
} else {
board[row][column] = 'C';
}
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, -1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, 1);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, -1);
}
void printLine(int boardSize) {
console.print(" ");
for (int count = 1; count <= boardSize * 2 - 1; count++) {
console.print("_");
}
console.println();
}
void displayGameBoard(char[][] board, int boardSize) {
console.println();
console.print(" ");
for (int column = 1; column <= boardSize; column++)
{
console.print(" ");
console.print(column);
}
console.println();
printLine(boardSize);
for (int row = 1; row <= boardSize; row++) {
console.print(row);
console.print(" ");
for (int column = 1; column <= boardSize; column++) {
console.print("|");
console.print(board[row][column]);
}
console.println("|");
printLine(boardSize);
console.println();
}
}
void displayMenu() {
console.println("(p)lay game");
console.println("(e)nter name");
console.println("(c)hange board size");
console.println("(q)uit");
console.println();
}
char getMenuChoice(String playerName) {
char choice;
console.print(playerName + " enter the letter of your chosen option: ");
choice = console.readChar();
return choice;
}
void playGame(String playerName, int boardSize) {
char[][] board = new char[boardSize + 1][boardSize + 1];
boolean humanPlayersTurn;
int move;
int humanPlayerScore;
int computerPlayerScore;
boolean moveIsValid;
setUpGameBoard(board, boardSize);
humanPlayersTurn = false;
int NoOfMoves=0;
do {
humanPlayersTurn = !humanPlayersTurn;
displayGameBoard(board, boardSize);
moveIsValid = false;
do {
if (humanPlayersTurn) {
move = getHumanPlayerMove(playerName);
} else {
move = getComputerPlayerMove(boardSize);
}
moveIsValid = checkIfMoveIsValid(board, move);
} while (!moveIsValid);
if (!humanPlayersTurn) {
NoOfMoves++;
console.println("The number of moves completed so far: " +NoOfMoves);
console.print("Press the Enter key and the computer will make its move");
console.readLine("");
}
makeMove(board, boardSize, move, humanPlayersTurn);
console.println();
String answer = console.readLine("Do you want to save the board? (y/n)");
if (answer.equalsIgnoreCase("y")){
writeBoard(board, boardSize);
console.println("Saved!");
}
} while (!gameOver(board, boardSize));
displayGameBoard(board, boardSize);
humanPlayerScore = getPlayerScore(board, boardSize, 'H');
computerPlayerScore = getPlayerScore(board, boardSize, 'C');
if (humanPlayerScore > computerPlayerScore) {
console.println("Well done, " + playerName + ", you have won the game!");
}
else {
if (humanPlayerScore == computerPlayerScore) {
console.println("that was a draw!");
} else {
console.println("The computer has won the game!");
}
console.println();
}
}
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
public static void main(String[] args) {
new Aaa();
}
}
This Section contains the errors:
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
The problematic section contains a variable named writeFile which can not be resolved. No where in the class Aaa that you have shared, neither this variable has been declared nor initialized with an instance of its type. So the method void writeBoard(char[][] board, int boardSize) gives compilation error.
From the usage of this variable it is clear that it belongs to a class which has following instance methods:
1) openFile(String filename)
2) writeToTextFile(String piece)
3) closeFile()
Please search the class which has the above methods and on finding create an instance of that as the first statement inside the method void writeBoard(char[][] board, int boardSize). Hope it helps.
I have been trying to get my tic tac toe program to work for a while now.
At the moment I'm stuck in the win condition.
The game can now end as a draw but no player (human || computer) can win it.
I need to determine the winning conditions (horizontal, vertical, across) in playerHasWon but have no idea how to implement them.
import java.util.Scanner;
import java.util.Random;
public class NewTicTacToe {
public static final int DRAW = 0;
public static final int COMPUTER = 1;
public static final int PLAYER = 2;
public static final char PLAYER_MARK = 'X';
public static final char COMPUTER_MARK = 'O';
public static int size;
public static String[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);
/**
* Creates base for the game.
*
* #param args the command line parameters. Not used.
*/
public static void main(String[] args) {
while (true) {
System.out.println("Select board size");
System.out.print("[int]: ");
try {
size = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("You can't do that.");
continue;
}
break;
}
int[] move = {};
board = new String[size][size];
setupBoard();
int i = 1;
loop:
while (true) {
if (i % 2 == 1) {
displayBoard();
move = getMove();
} else {
computerTurn();
}
switch (isGameFinished(move)) {
case PLAYER:
System.err.println("YOU WIN!");
break loop;
case COMPUTER:
System.err.println("Computer WINS!\nYOU LOSE!");
break loop;
case DRAW:
System.err.println("IT'S A DRAW");
break loop;
}
i++;
}
}
private static int isGameFinished(int[] move) {
if (isDraw()) {
return DRAW;
} else if (playerHasWon(board, move, COMPUTER_MARK)) {
return COMPUTER;
} else if (playerHasWon(board, move, PLAYER_MARK)) {
return PLAYER;
}
return -1;
}
/**
* Checks for win.
*
* #param board
* #return if the game is won.
*/
public static boolean playerHasWon(String[][] board, int[] move,
char playerMark) { //playermark x || o
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
if (board[i][j].equals(playerMark)) {
score++;
} else {
score = 0;
}
if (score == 5) {
return true;
}
}
}
return hasWon;
}
/**
* Checks for draws.
*
* #return if this game is a draw
*/
public static boolean isDraw() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == " ") {
return false;
}
}
}
return true;
}
/**
* Displays the board.
*
*
*/
public static void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%s]", board[i][j]);
}
System.out.println();
}
}
/**
* Displays the board.
*
*
*/
public static void setupBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = " ";
}
}
}
/*
* Takes in userinput and sends it to isValidPlay.
*
*
*/
public static int[] getMove() {
Scanner sc = new Scanner(System.in);
System.out.println("Your turn:");
while (true) {
try {
System.out.printf("ROW: [0-%d]: ", size - 1);
int x = Integer.parseInt(sc.nextLine());
System.out.printf("COL: [0-%d]: ", size - 1);
int y = Integer.parseInt(sc.nextLine());
if (isValidPlay(x, y)) {
board[x][y] = "" + PLAYER_MARK;
return new int[]{x, y};
}
} catch (Exception e) {
System.out.println("You can't do that.");
}
return null;
}
}
/*
* Randomizes computer's turn - where it inputs the mark 'O'.
*
*
*/
public static void computerTurn() {
Random rgen = new Random(); // Random number generator
while (true) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
if (isValidPlay(x, y)) {
board[x][y] = "" + COMPUTER_MARK;
break;
}
}
}
/**
* Checks if the move is possible.
*
* #param inX
* #param inY
* #return
*/
public static boolean isValidPlay(int inX, int inY) {
// Play is out of bounds and thus not valid.
if ((inX >= size) || (inY >= size)) {
return false;
}
// Checks if a play have already been made at the location,
// and the location is thus invalid.
return (board[inX][inY] == " ");
}
}
// End of file
You could use a different approach to check for victories. Maybe split in three parts? Horizontal, vertical, and diagonals?
I made some changes to your code to give an example:
public static boolean playerHasWon(String[][] board, int[] move,
String playerMark) { //playermark x || o
//Horizontal check
for (int i = 0; i < size; i++) {
if (board[i][0].equals(playerMark)) {
int j;
for (j = 1; j < size; j++) {
if (!board[i][j].equals(playerMark)) {
break;
}
}
if (j == size) {
return true;
}
}
}
//Vertical check
for (int i = 0; i < size; i++) {
if (board[0][i].equals(playerMark)) {
int j;
for (j = 1; j < size; j++) {
if (!board[j][i].equals(playerMark)) {
break;
}
}
if (j == size) {
return true;
}
}
}
//Diagonals
int i;
for (i = 0; i < size; i++) {
if (!board[i][i].equals(playerMark)) {
break;
}
}
if (i == size) {
return true;
}
for (i = 0; i < size; i++) {
if (!board[i][(size - 1) - i].equals(playerMark)) {
break;
}
}
if (i == size) {
return true;
}
return false;
}
Note that you have to change the playerMarks from char to String.
Also, I suggest displaying the board just before announcing who won. That way, if the computer wins, you can see its last move
A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}