Problems with the N queen homework exercice in Java - java

I'm using my own implementation of the stack.
I should not use recursion.
My code:
public static void solve(int bsize)
{
stack queenLoc = new stack();
int y=0;
int count=0;
boolean done = false;
while(done == false && queenLoc.size() != bsize)
{
queenLoc.push(count);
if(!isSafe(bsize,queenLoc,count))
{
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
if(queenLoc.top != null)
{
queenLoc.push(queenLoc.pop()+1);
count++;
}
else
{
queenLoc.push(y+1);
count++;
}
}
else if(queenLoc.size() == bsize)
{
done = true;
}
else
{
count++;
queenLoc.push(count);
}
}
queenLoc.showAll();
if(queenLoc.size() == bsize)
printBoard(bsize, queenLoc);
}
public static boolean isSafe(int bsize, stack s,int count)
{
for(int i = 1; i<s.size(); i++)
{
if(s.getTop() == s.get(i) || s.getTop()+count == s.get(i)+s.size() || s.getTop()-count == s.get(i)-s.size())
return false;
}
return true;
}
I'm not sure what is really going on, i'm getting wrong position and the printBoard function is only printing the queens on the first row.
I actually tried a lot of possibilities, but i got a bit confused.
Can anyone just point me out to the right direction and tell me where's the problem in my code. I am using the stack to store the column and the "count" variable in the stack class to point me to which row.

package mynqueens;
public class MyNQueens {
public static int board[][] = new int[4][4];
public static int row,column;
public MyNQueens(){
}
public static void main(String[] args) {
check(0,0);
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
}
public static void check(int i, int j ){
while(i<3){
board[i][j] = 1;
i++;
}
while(i!=0){
board[i][j] = 1;
i--;
}
while(j<3){
board[i][j]=1;
j++;
}
while(j!=0){
board[i][j] = 1;
j--;
}
while(j<3 || i<3){
board[i][j] = 1;
i++;
j++;
}
while(j!=0 || i!=0){
board[i][j] = 1;
i--;
j--;
}
while(i<3 || j!=0){
board[i][j]=1;
i++;
j--;
}
while(i!=0 || j<3){
board[i][j]=1;
i--;
j++;
}
}
}

Before you start erasing elements in inner while section
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
number of elements in queenStack will exceed bsize.
You have while(done == false && queenLoc.size() != bsize) so when size of queenLoc will be equal to bsize you will print result.
What I am saying is that after bsize steps you are always printing results.
Advise: Your code should have invariant "queenLoc represents position where no two queens attack each other".

import java.util.Scanner;
/**
*
* #author Manimekalai
*/
public class Queen {
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String[] args)
{
//int N = Integer.parseInt(args[0]);
System.out.println("Enter N value");
Scanner s=new Scanner(System.in);
int N=s.nextInt();
enumerate(N);
}
}

Related

I am trying to find the prime numbers from 0 to a given number from the user

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;
}

listing prime numbers from user input in java

in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}
Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}
I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}
//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}

Module and how to use it in the situation below

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 )

PRIME1 - Prime Generator Java

I wrote the code in JAVA and it seems to work fine in Eclipse. But I get an error when I submite the code in SPOJ(runtime error (NZEC) ).
Could someone please help me with this.
Here what I tried so far:
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner n1 = new Scanner(System.in);
Scanner n3 = new Scanner(System.in);
int n2 = n1.nextInt();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String[] s2 = n3.nextLine().split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++){
for(int j=n4[i][0];j<=n4[i][1];j++){
if(isPrimeNumber(j)){
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
1st thing you need to do is use the scanner properly and get rid off the 2nd one..
you are using 2 scanners because only one is not working as expected, why?
because you forgot that the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Try this:
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
int n2 = input.nextInt();
input.nextLine();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String string2 = input.nextLine();
String[] s2 = string2.split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++) {
for (int j = n4[i][0]; j <= n4[i][1]; j++) {
if (isPrimeNumber(j)) {
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

Project Euler #3 Java

public class Problem3 {
public static void main (String args[]) {
System.out.print(primeMod(60085147514L));
}
public static double primeMod(long d) {
long max = 0;
int count = 0;
for (long i = 2; i < d; i++) {
if (d % i == 0) {
boolean isPrime = primeCounter(i);
if(isPrime == true) {
max = i;
System.out.println(max);
}
} else {
max = max;
}
}
return max;
}
public static boolean primeCounter(long x) {
int count = 0;
for (int s = 1; s <= x; s++) {
if (x % s == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
My program works for smaller numbers but it Throws an Arthmetic Exception for Divide by 0 when its not dividing by zero.please dont give me the answer,just wanna understand it and improve my skills
thank you
My guess would be that s is overflowing, leading eventually to a divide by zero. Make s a long instead.

Categories