import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class Maze
{
private int[][] maze;
private boolean exitFound;
public Maze()
{
exitFound = false;
maze = new int[0][0];
}
public Maze(int size, String line)
{
exitFound=false;
maze = new int[size][size];
int spot=0;
for(int r= 0; r<maze.length; r++)
{
for(int c =0; c<maze[r].length; c++)
{
maze[r][c]=(line.charAt(spot*2)-48);
spot++;
}
}
}
public void checkForExitPath(int r, int c)
{
if (r >= 0 && r <maze.length &&c >= 0 && c < maze[0].length && maze[r][c] == 1)
{
checkForExitPath(r + 1, c);
checkForExitPath(r - 1, c);
checkForExitPath(r, c + 1);
checkForExitPath(r, c - 1);
maze[r][c] = 7;
if (r == maze.length-1 && c == maze[0].length-1){
this.exitFound =true;
}
}
}
public String toString()
{
String hol = "";
for(int i = 0; i<maze.length; i++){
for(int j = 0; j<maze[0].length; j++){
hol += " ";
if(maze[i][j] == 7){
hol += "1";
}
else
{
hol += maze[i][j];
}
}
hol += "\n";
}
if(this.exitFound)
{
hol+= "exit found";
}
else {
hol += "exit not found";
}
return hol;
}
}
That is my maze class the method checkForExitPath is not working or at least I think because everytime I run the maze solver with this runner class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MazeRunner
{
public static void main( ) throws IOException
{
Scanner file = new Scanner(new File("maze.dat"));
while(file.hasNext())
{
int size = file.nextInt();
file.nextLine();
Maze test = new Maze(size, file.nextLine());
test.checkForExitPath(0,0);
out.println(test);
}
}
}
The only output I get is that an exit is not found, but I can find an exit.
I am doing this recursively.
Your whole method does not really work recursively. If the upper left corner has a 1 which I interpret from your code as walkable way, it is changed to 7 and your method ends without recursion.
I think the four recursive method calls should be part of the first if block and no else block is necessary.
Related
import java.util.*;
public class TestClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String[] val = new String[n];
scan.nextLine();
for (int i = 0; i < n; i++) {
val[i] = scan.nextLine();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (val[i].equals(val[j])) {
System.out.println(val[i]);
}
}
}
}
}
This is a simple code for finding duplicate array value but I need an else part where it should print "No duplicate found" but the problem is as I am iterating it through a loop it's printing N times the output.
INPUT
cat
dog
frog
owl
OUTPUT
No duplicate found
you can have a check variable for example
boolean duplicatefound = false;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (val[i].equals(val[j]))
{
System.out.println(val[i]);
duplicatefound = true;
}
}
}
if(duplicatefound)
{
System.out.println("duplicate found");
}else
{
System.out.println("No Duplicated found");
}
Can we use something like this
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class TestClass
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String[] val = new String[n];
scan.nextLine();
for (int i = 0; i < n; i++)
{
val[i] = scan.nextLine();
}
boolean dups = false;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (val[i].equals(val[j]))
{
System.out.println(val[i]);
} else
{
dups = true;
}
}
}
if (dups)
{
System.out.println("no duplicate found");
}
if (findDups(val))
{
System.out.println("no duplicate found");
}
if (findDups(Arrays.asList(val)))
{
System.out.println("no duplicate found");
}
}
// different approach to avoid nested loops
public static boolean findDups(String[] arr)
{
Set<String> set = new HashSet<>();
for (String i : arr)
{
if (set.contains(i))
{
return false;
} else
{
set.add(i);
}
}
return true;
}
// Java 8 streams
public static boolean findDups(List<String> list)
{
return list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).isEmpty();
}
}
I am struggling with Runtime Error (NZEC) on Spoj for problem,
http://www.spoj.com/problems/NHAY/
I tried so many cases from my side and everytime it is giving correct output in eclipse but could not able to find out the reason of Runtime error while submitting this on Spoj, Can anyone please help me to resolve this error.
Here is my code,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
class KMP {
public int[] lps(String needle, int needleLength)
{
int lps[] = new int[needleLength];
int j=0,i=1;
lps[0]=0;
while(i<needle.length())
{
if(needle.charAt(j) == needle.charAt(i))
{
lps[i] = j+1;
i++;
j++;
}
else
{
if(j != 0)
{
j = lps[j-1];
}
lps[i] = 0;
i++;
}
}
return lps;
}
public List<Integer> KMPalgo(String hayStack, String needle, int needleLengh)
{
int lps[] = lps(needle, needleLengh);
int i=0;
int j=0;
List<Integer> position = new ArrayList<Integer>();
while(i<hayStack.length())
{
if(hayStack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
if(j !=0)
{
j = lps[j-1];
}
else
i++;
}
if(needle.length() == j)
{
position.add(i-j);
if(j !=0)
j = lps[j-1];
}
}
return position;
}
public static void main(String[] args) throws NumberFormatException, IOException {
KMP o = new KMP();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String needlLength = bf.readLine().trim();
if(needlLength == null || needlLength.equals(""))
break;
int lNeedle = Integer.parseInt(needlLength);
String needle = bf.readLine().trim();
String haystack = bf.readLine().trim();
List<Integer> result= o.KMPalgo(haystack, needle, lNeedle);
System.out.println();
for(Integer itr : result)
System.out.println(itr);
}
}
}
The cause of the runtime error is:
String needlLength = bf.readLine().trim();
if(needlLength == null || needlLength.equals(""))
break;
You are calling trim() before checking needlLength for null.
But it seems you have at least one other error. You should replace
if(j != 0)
{
j = lps[j-1];
}
lps[i] = 0;
i++;
with
if(j != 0)
{
j = lps[j-1];
}
else
{
lps[i] = 0;
i++;
}
because now you are doing at most one jump when computing a prefix function, and that is not correct.
I am working on a Four in a row game.
But I have run into a problem with it. I have been able to make the game work. But I would like to know if I can move my public void fillBoard() and public void presentBoard() into another class. This is because I would like to make the code more organised.
package com.company;
public class Main {
public static void main(String[] args)
{
GameMechanics game = new GameMechanics();
game.play();
}
}
package com.company;
import java.util.Scanner;
public class GameMechanics
{
/*
This is my local variables
*/
public Scanner scanner = new Scanner(System.in);
public char token;
public int column;
public int player = 2;
public int turn = 2;
public int count = 0;
public boolean gameRunning = true;
public void play()
{
this.createBoard();
//While gameRunning is true, the methods inside the { } will run, and that's the 4InARow game
while (gameRunning)
{
this.presentBoard();
this.changeTurn();
this.dropToken();
this.gameWon();
}
presentBoard();
}
public void gameWon()
{
this.winConHorizontal();
this.winConVertical();
}
private char[][] board = new char[6][7];
//Creating my board and assign "space" to all the fields in the array.
public void createBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
//Presents the board, it prints the board with |"space"| so it looks more like a gameboard.
public void presentBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (j == 0) {
System.out.print("|");
}
System.out.print(board[i][j] + "|");
}
System.out.println();
}
}
public void changeTurn() {
if (this.turn == this.player) {
this.turn = 1;
this.token = 'X';
} else {
this.turn++;
this.token = 'O';
}
}
public void dropToken() {
System.out.println("player " + turn + ": press 1-7 to drop the token");
column = scanner.nextInt() - 1;
//If pressed any intValue outside the board, it will tell you to try again.
if (column >= 7 || column <= -1)
{
System.out.println("place the token inside the bord");
changeTurn();
} else {
//Drops the token and replace it with playerChar.
for (int i = 5; i > -1; i--) {
if (board[i][column] == ' ')
{
board[i][column] = token;
break;
}
}
}
}
public boolean winConHorizontal() {
while (gameRunning) {
for (int i = 0; 6 > i; i ++) {
for (int j = 0; 7 > j; j ++) {
if (board[i][j] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
public boolean winConVertical() {
while (gameRunning) {
for (int i = 0; 7 > i; i ++) {
for (int j = 0; 6 > j; j ++) {
if (board[j][i] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
}
An easy way to do this is as follows:
extract your char[][] board into its own class, e.g. Board
Said class could expose the function char getField(int index)
Extract the ,,presenting" part of your code into another class, e.g. BoardPresenter. Said class should have a function presentBoard(Board board) which internally uses getField(int index) of the Board class.
By doing this you abstract away your internal board storage mechanism while also reducing the number of responsibilities the GameMechanics class has (See https://en.wikipedia.org/wiki/Single_responsibility_principle)
yes, you can make another class and extend it with the current class GameMechanics and inside another class you can define the functions.
Note : This is a very simple approachable way.
Otherwise better if you manage your classes and interfaces similar to mvc model, for which you can search youtube for mvc structure java.
I am trying to execute merge sort step by step handled by an button click event. I am unable to perform this. What i want is when i click on a button called next, it executes a single step and so on.
Core is my main class. which includes all the gui buttons etc.
here is my code.
`
package sorter;
import sorter.Core;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import sorter.Core$step;
import javax.swing.JOptionPane;
// Referenced classes of package sorter:
// Core
public class MergeSort_Step
implements Runnable, ActionListener
{
private static List<Integer> lists;
private int counter =0;
private int length_list;
public static boolean STEP_BY_STEP=false;
Thread sortingThread=null;
public MergeSort_Step()
{
//JOptionPane.showMessageDialog(Core.form, "Changes will apply on next sort");
Core.btnNext.addActionListener(new Core$step(this));
}
private void clickperformed_1(ActionEvent evt) {
STEP_BY_STEP = true;
//sortingThread = new Thread (this);
//sortingThread.resume();
//run();
}
static void access$click(MergeSort_Step x0, ActionEvent x1) {
x0.clickperformed_1(x1);
}
public void run()
{
//*****************list
length_list = Core.length;
lists = new ArrayList<Integer>(length_list);
for (int i = 0; i < length_list; i++) {
lists.add(0);
}
//System.out.println("Results from file in list: " +lists.size());
mergesort_list (0,length_list-1);
JOptionPane.showMessageDialog(null, "Comparisions : "+ counter, "Notification!", 1);
Core.toggleSorting();
}
//***************list
public void mergesort_list(int low, int high)
{
sortingThread = new Thread (this);
if(low < high)
{
int middle = low + (high - low) / 2;
mergesort_list(low, middle);
mergesort_list(middle + 1, high);
if (Core.STEP_BY_STEP == true || STEP_BY_STEP == true)
{
merge_list(low, middle, high);
//sortingThread.
STEP_BY_STEP = false;
Core.STEP_BY_STEP = false;
}
}
}
//***************list
private void merge_list(int low, int middle, int high)
{
int i;
for(i = low; i <= high; i++)
{
lists.set(i, Core.num.get(i)); //= (List<Integer>) Core.num.get(i);
System.out.println("Current Array Status: " +lists.toString());
Core.numStatus[i] = Core.DONE;
}
i = low;
int j = middle + 1;
int k = low;
{
while(i <= middle && j <= high)
{
if( lists.get(i) <= lists.get(j))
{
Core.num.set(k, lists.get(i));
Core.numStatus[i] = Core.DONE;
Core.updateScreen();
i++;
} else
{
Core.num.set(k, lists.get(j));
Core.numStatus[i] = Core.DONE;
Core.updateScreen();
j++;
}
k++;
Core.numStatus[i] = Core.EVENT;
Core.updateScreen();
//Core.STEP_status = false;
counter++;
}
while(i <= middle)
{
Core.num.set(k, lists.get(i));
Core.numStatus[i] = Core.EVENT;
Core.updateScreen();
k++;
i++;
Core.updateScreen();
//Core.STEP_status = false;
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}`
I am very new to event handling and java gui implementation as well. any help will be appreciated.
This is a ACM-ICPC practicing problem: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=975. And the basic idea is to find the shortest weight of a minimum spanning tree. And I tried to solve it with Kruskal algorithm. I tested it myself and it seems to be working fine. However, when I submit it onto the uva online judge, the result is "wrong answer". Could any body see where is not correct? Thanks!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
//import java.util.Comparator;
import java.util.List;
//import java.math.*;
public class Main {
public static void main(String[] args) throws Exception, IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
int numOfCases = Integer.parseInt(cin.readLine());
while (numOfCases > 0) {
cin.readLine();
int numOfPoints = Integer.parseInt(cin.readLine());
List<Points> listOfPoints = new ArrayList<Points>();
List<Edge> listOfEdges = new ArrayList<Edge>();
double inkUsed = 0;
for (int i = 0; i < numOfPoints; i++) {
String[] tokens = cin.readLine().split(" ");
Points point = new Points(Double.parseDouble(tokens[0]),Double.parseDouble(tokens[1]));
listOfPoints.add(point);
}
for (int i = 0; i < listOfPoints.size(); i++) {
for (int j = i+1; j < listOfPoints.size(); j++) {
Edge edge = new Edge(listOfPoints.get(i), listOfPoints.get(j));
listOfEdges.add(edge);
}
}
Collections.sort(listOfEdges);
for (Edge e: listOfEdges) {
Points pointA = null;
Points pointB = null;
// Find pointA and pointB in the list "listOfPoints"
for (int i = 0; i < listOfPoints.size(); i++) {
if (listOfPoints.get(i).x == e.A.x && listOfPoints.get(i).y == e.A.y) {
pointA = listOfPoints.get(i);
}
if (listOfPoints.get(i).x == e.B.x && listOfPoints.get(i).y == e.B.y) {
pointB = listOfPoints.get(i);
}
}
Points rootOfA = findSet(pointA);
Points rootOfB = findSet(pointB);
if (rootOfA.x != rootOfB.x || rootOfA.y != rootOfB.y){ //add this edge
//System.out.println( "[" + "(" + pointA.x +"," + pointA.y+"); (" + pointB.x +"," + pointB.y+")"+ "]");
inkUsed += e.weight;
rootOfA.parent = rootOfB;
}
}
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(inkUsed));
numOfCases--;
}
}
public static Points findSet(Points A) {
Points rootOfA = A;
while (rootOfA.parent != null) {
rootOfA = rootOfA.parent;
}
return rootOfA;
}
}
class Points {
public double x;
public double y;
public Points parent = null;
Points (double x, double y) {
this.x = x;
this.y = y;
}
}
class Edge implements Comparable<Edge> {
Points A;
Points B;
double weight;
Edge (Points var1, Points var2) {
A = var1;
B = var2;
weight = Math.sqrt(Math.pow((A.x-B.x), 2) + Math.pow((A.y-B.y), 2));
}
public String toString() {
return Double.toString(weight);
}
public int compareTo(Edge anotherEdge) {
if (this.weight < anotherEdge.weight) {
return -1;
} else if (this.weight == anotherEdge.weight) {
return 0;
} else {
return 1;
}
}
}