N times problem while iterating through loop in Duplicate element program - java

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

Related

Code submission on Spoj is giving runtime error (NZEC)

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.

How can I move this into a other class

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.

Combinations redundant in java programme

I want to print every possible combinations by using given letters without change letter orders so i wrote this code but it will print every line again and again what is the problem
public class Solutions {
public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
c = "l u k".split(" ");
Solutions solutions = new Solutions();
solutions.combi(0);
System.out.println("Number of combi = " + count);
System.out.print(max);
}
static String[] c;
static int count = 0;
static int max = 0;
public void combi(int start) {
int j;
if (start != 0) {
String str = "";
for (int i = 0; i < start; i++) {
// System.out.print(c[i]);
str += c[i];
}
// System.out.println();
count++;
}
for (j = start; j < c.length; j++) {
combi(start + 1);
}
}
}
public void combi(int start) {
int j;
if (start != 0) {
for (int i = 0; i < start; i++) {
System.out.print(c[i]);
}
System.out.println();
count++;
} else {
for (j = start+1; j <= c.length; j++) {
combi(j);
}
}
}

illegal start of expression in java while declaring private variables in public class

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class TSPNearestNeighbour {
{
private final Stack<Integer> stack;
private int numberOfNodes;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
public void tsp(int adjacencyMatrix[][])
{
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i,cost=0;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
cost=cost+adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print( dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
System.out.println("total cost" +cost);
}
public static void main(String args[])
{
int number_of_nodes;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}
> illegal start of expression in the line:
> **private final Stack<Integer> stack;**
You have 2 open braces
public class TSPNearestNeighbour { {
remove one and may be you get your code compiled

Java Implementation, Priority Queue

I have a hard time to figure out one error after assigning
int evaluationNode = getMinDistances();
settled.add(evaluationNode);
checkNeighbours(evaluationNode);
The error show type mismatch: connot convert from Node to int. I am appreciated if anyone can help me this. Below is a complete code.
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.util.Comparator;
public class DijkstraPriorityQueue
{
private int distances[];
private Set<Integer> settled;
private PriorityQueue<Node> priorityQueue;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraPriorityQueue(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
priorityQueue = new PriorityQueue<Node>(number_of_nodes,new Node());
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
priorityQueue.add(new Node(source, 0));
distances[source] = 0;
while (!priorityQueue.isEmpty())
{
evaluationNode = getMinDistances();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getMinDistances()
{
int node = priorityQueue.remove();
return node;
}
private void checkNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
priorityQueue.add(new Node(destinationNode,distances[destinationNode]));
}
}
}
}
public static void main(String[] args)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
source = scan.nextInt();
DijkstraPriorityQueue dijkstrasPriorityQueue = new DijkstraPriorityQueue(number_of_vertices);
dijkstrasPriorityQueue.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasPriorityQueue.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is " + dijkstrasPriorityQueue.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
class Node implements Comparator<Node>
{
public int node;
public int cost;
public Node()
{
}
public Node(int node, int cost)
{
this.node = node;
this.cost = cost;
}
#Override
public int compare(Node node1, Node node2)
{
if (node1.cost < node2.cost)
return -1;
if (node1.cost > node2.cost)
return 1;
return 0;
}
}
In the getMinDistances method you are calling
int node = priorityQueue.remove();
But the priority queue contains Node objects, and not int values.
Maybe you wanted something like
private int getMinDistances()
{
Node node = priorityQueue.remove();
return node.getDistance();
}
but this is something that can not be answered by the debugging cloud (aka stackoverflow).
In order to use the PriorityQueue, you have to implement MinPQ extending the PriorityQueue and you'll also need a Comparator between nodes that returns the Node with a minimum distance in the MinPQ.
Take a look here for more details.

Categories

Resources