Checking if an array contains two numbers [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
i have just started with Java and facing a problem right now, which i cannot solve after 2hrs of checking code.
When i input :
7 ( as length)
6 3 4 8 3 2 6 (as array)
8 3 (as numbers to check)
it Writes false, but clearly they are included in the exact order.
Please help me trying to understand what the problem is
here is the Code:
import java.util.Scanner;
public class checker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int[] numbers = new int[length];
boolean broken = false;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int j = 1; j < length; j++) {
if (numbers[j] == n && numbers[j-1] == m || numbers[j] == m && numbers[j+1] == n || numbers[j] == m && numbers[j-1] == n || numbers[j] == n && numbers[j+1] == m) {
broken = false;
} else {
broken = true;
}
}
if (broken) {
System.out.println("false");
} else {
System.out.println("true");
}
}
}

As you mentioned in a comment, you want to check on {n,m} and {m,n} so why do you have more conditions?
The following is enough:
for (int j = 0; j < length-1; j++) {
if (numbers[j] == n && numbers[j+1] == m || numbers[j] == m && numbers[j+1] == n) {
broken = false;
break;
} else {
broken = true;
}
}
The loop goes from 0 (=first array element) to the last -1 because the if compares with j+1. Once you have found a match you have to break out of the loop otherwise you risk to set broken to false again.

You could also achieve this without using a boolean, check tweaked code below.
import java.util.Scanner;
public class checker {
public static void main(String[] args) {
int howManyValuesPresent = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Length of array");
int length = scanner.nextInt();
int[] numbers = new int[length];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int m = scanner.nextInt();
for(int number: numbers){
if(number == n || number == m){
howManyValuesPresent++;
}
}
if (howManyValuesPresent>0) {
System.out.println("true, Your selected numbers appear: " + howManyValuesPresent + " times in array");
} else {
System.out.println("false, Your selected numbers appear: " + howManyValuesPresent + " times in array");
}
}
}

Related

Traveling salesman code not working (Java)

Traveling salesman code in java below (gives wrong result)
http://www.sanfoundry.com/java-program-solve-travelling-salesman-problem-unweighted-graph/
package com.hinguapps.graph;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TSP {
private int numberOfNodes;
private Stack < Integer > stack;
public TSP() {
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;
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];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag) {
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
}
public static void main(String...arg) {
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 cities are visited as follows: ");
TSP tspNearestNeighbour = new TSP();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
scanner.close();
}
}
Matrix should be :
0 10 5 40
2 0 5 1
6 13 0 12
1 8 9 0
Expected result: 1 3 2 4 1
Code result : 1 3 4 2 1
This implementation is wrong. This is a hard problem, because you need to either touch every path, or at the very least CONSIDER every path. This implementation basically boils down to "Each step, move to the closest node that I haven't visited". Since the stack is not keeping memory of where you have been, it does not backtrack to consider that a better path may have existed down one of the longer roads.
To fix this, the algorithm needs to keep the path in memory somehow, and not start printing the solution until the best solution has actually been found. (Can use recursion, a stack that holds the whole path, or some other method.)

Trying to find a pattern from a vector in an array

I'm learning Java and I have this exercise where I need to find a pattern from a vector in a matrix and then copy the number of the rows where the pattern is found to another vector.
I'm trying to copy each row of the matrix to another vector and then compare it with the pattern, but it only saves the first row where the pattern is found
package exercise;
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
public class Exercise {
static final int M = 7;
static final int N = 7;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Scanner fEnt = null;
Scanner fEnt1 = null;
PrintStream fSal = null;
double[] pattern = new double[M];
double[][] m = new double[N][N];
double[] aux = new double[N];
int[] res = new int[N];
int i, ax, j, vLon, k, z, w = 0;
boolean found, repeated;
System.out.print("Enter matrix filename: ");
String nomEnt = scanner.next();
System.out.print("Enter pattern filename: ");
String nomEnt1 = scanner.next();
System.out.print("Enter new filename: ");
String nomSal = scanner.next();
try {
fEnt = new Scanner(new File(nomEnt));
fEnt.useLocale(Locale.US);
fEnt1 = new Scanner(new File(nomEnt1));
fEnt1.useLocale(Locale.US);
fSal = new PrintStream(new File(nomSal));
i = 0;
ax = 0;
while (fEnt1.hasNext() && i < M) {
pattern[i] = fEnt1.nextDouble();
i++;
}
vLon = i;
j = 0;
i = 0;
while (fEnt.hasNext() && i < N) {
while (fEnt.hasNext() && j < N) {
m[i][j] = fEnt.nextDouble();
j++;
}
i++;
}
k = 0;
for (i = 0; i < N; i++) {
repeated = false;
for (j = 0; j < N; j++) {
aux[j] = m[i][j];
}
z = 0;
found = true;
while (z <= N - vLon) {
j = 0;
while (j < vLon && found) {
if (aux[z + j] != pattern[j]) {
found = false;
}
j++;
}
if (found) {
repeated = true;
}
z++;
}
if (repeated) {
res[k] = i;
k++;
}
w = k;
}
if (w == 0) {
System.out.println("The pattern wasn't found in the matrix");
} else {
for (i = 0; i < w; i++) {
fSal.print(String.valueOf(res[i]) + "\t");
}
fSal.println();
System.out.println("The vector has been saved.");
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
} finally {
if (fEnt != null) {
fEnt.close();
}
if (fSal != null) {
fSal.close();
}
}
}
}
For example, if it reads the matrix
5 2 1 2 3 4
5 3 5 1 2 3
1 2 5 2 4 6
6 7 3 5 1 2
1 2 3 6 8 4
4 5 3 2 4 6
Then if the pattern is 1 2 3, it should save the following vector 1 2 5
This is a question of basic debugging. Therefore, TL;DR use your IDE's debugger.
Long version:
If you have an IDE, then use its debugging features. Eclipse and IntelliJ both have great debugging support and mountains of online tutorials on how to do it.
Things I found wrong while debugging your code (not everything):
Your matrix is only reading into the first line. 2nd, 3rd, etc. rows are all 0's. Also, you are setting N and M to 7 but they should be 6.
-- hint -- step through it and watch what happens right after you increment i, on your next entry into the loop on j. Line ~58
You are doing something wrong with your 'found' flag, causing your program to quit checking after it initially fails. Line ~70
-- hint -- double-check your logic here - I don't think 'found' means what you think it means in your code

Having issues with printing a nested loop

I am trying to print a nested loop that will print two islands and scale depending on what the input is. The goal is to make Exclamation points(!) to make the left island, a line diagonally of asterisks(*), question marks to make the right island and tildas(~) to make the ocean. Any comments on my code would be helpful.
Example of what I am trying to do.
Input a size (must be larger than 1):
5
0 !!~~*
1 !!~*~
2 ~~*~~
3 ~*~??
4 *~~??
Here is my code:
import java.util.Scanner;
public class Two_Islands {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
//Create Size variable
System.out.println("Input a size: ");
int n = 0; n = kbinput.nextInt();
for (int r = 0; r < n; r++) {
System.out.print(r);
for (int c = 0; c < n; c++) {
if (r+c == n-1) {
System.out.print("*");
} else if (r+c == n-2) {
System.out.print("!");
} else if (r+c == n+2) {
System.out.print("?");
} else {
System.out.print("~");
}
}
System.out.println();
}
kbinput.close();
}
}
Here is my current output.
Input a size:
5
0~~~!*
1~~!*~
2~!*~~
3!*~~?
4*~~?~
try the following:
else if(r+1 < n/2 && c+1 < n/2)
{
System.out.print("!");
}
else if(r+1 > n-n/2 && c+1 > n-n/2)
{
System.out.print("?");
}

Find the Last Digit In An Array

I need to find the last digit in a array and see if it is equal to zero. Here is the code I'm using;
import java.util.Scanner;
public class NrOccurrence
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100: ");
int[] numbers = new int[100], times = new int[100];
boolean zero = false;
while (zero == false)
{
for (int a = 0; a <= numbers.length; a++)
{
numbers[a] = scan.nextInt();
times[a]++;
if (numbers.equals(0))
{
zero = true;
}
}
}
for (int b = 0; b <= numbers.length; b++)
{
System.out.println(numbers[b] + " occurs " + times[b] + " times");
}
scan.close();
}
}
Create a method like this:
private boolean isLastItemZero(int[] numbers)
{
boolean isLastItemZero = false;
if ((numbers != null) && (numbers.length > 0))
{
isLastItemZero = numbers[numbers.length - 1] == 0;
}
return isLastItemZero;
}
And call it once you're done reading in all of the numbers from the user.
First of all for (int a = 0; a <= numbers.length; a++) will give youIndexOutOfBoundsException .Java uses 0 bases indexing which means that an array of size n has indices up to and including n-1. Change it tofor (int a = 0; a < numbers.length; a++) . Same thing here for (int b = 0; b <= numbers.length; b++)
Second i am not sure what you are trying to check here :
if (numbers.equals(0))
{
zero = true;
}
but you could simply do :
if(numbers[i] == 0);
Now if you wanna check if the last element in the array is 0you can simply do:
if(numbers[numbers.length - 1] == 0)
//do something
By definition, if the remainder of a number divided by 10 is 0, then the last digit must be 0. So you just need;
if(numbers[i] % 10 == 0) { zero = true; }
Hope this helps.

How Do I Determine If The 5 Numbers I Typed Into An Array Are Sequential using Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write a really simple poker game. I'm just using the non-face cards, 2-9, without suites or anything of the like. I'm trying to figure out how to write a method that determines if five cards are a full house, which is a pair and a 3 of a kind. I have the user input 5 integers that represent card values and store them in a single array. I tried writing something like this:
public static boolean containsFullHouse(int[] hand)
{
for (int i = 0; i < hand.length; i++){
int count = 0;
for (int j = 0; j < hand.length; j++){
if (hand[i] == hand[j]){
count++;}
if (count == 3){
return true;}
}
}
for(int i = 0; i < hand.length; i++){
for(int j = i + 1; j < hand.length; j++){
if(hand[i] == hand[j]){
return true;}
}
}
}
return false;
}
You need to count the occurrences of each number, and create what is called a cardinality map. Then the cardinalities must be (2,3) or (3,2). If not using guava or Apache Commons Collections (which contain convenience methods to do this), this can be done in the following way:
public static boolean isFullHouse(final int[] input) {
if (input.length != 5) { throw new IllegalArgumentException("need 5 integers"); }
Map<Integer, Integer> cardinalityMap = new HashMap<>();
for (int i : input) {
if (cardinalityMap.containsKey(i)) {
cardinalityMap.put(i, cardinalityMap.get(i) + 1);
}
else {
cardinalityMap.put(i, 1);
}
}
if (cardinalityMap.size() != 2) { return false; }
Collection<Integer> occurences = cardinalityMap.values();
int first = occurences.iterator().next();
return first == 2 || first == 3;
}
I would use CollectionUtils.getCardinalityMap from Apache Commons to do this
public static void main(String[] args) {
Integer[] fullHouse = new Integer[]{7, 7, 7, 4, 4};
Integer[] notFullHouse = new Integer[]{2, 2, 2, 2, 3};
Integer[] notFullHouse2 = new Integer[]{1, 4, 2, 2, 3};
System.out.println(isFullHouse(fullHouse));
System.out.println(isFullHouse(notFullHouse));
System.out.println(isFullHouse(notFullHouse2));
}
private static boolean isFullHouse(Integer[] cards){
Map<Integer,Integer> cardinalityMap = CollectionUtils.getCardinalityMap(Arrays.asList(cards));
if(cardinalityMap.size() == 2) {
if (cardinalityMap.values().containsAll(Arrays.asList(2, 3))) {
return true;
}
return false;
}
return false;
}
Problems:
You're checking index i twice, although correct (since you check for count == 3), it's unnecessary.
You're also returning before you check the other 2.
The second loop will return true since it will find the numbers from the previous loop.
If you sort them, you can simply check whether the two pairs of cards on both sides are the same and check whether the middle card is the same as either one. So something like this:
Arrays.sort(hand);
return (hand[0] == hand[1] && hand[3] == hand[4] &&
(hand[2] == hand[1] || hand[2] == hand[3]));
Alternatively, if you want to fix your function:
public static boolean containsFullHouse(int[] hand)
{
// a variable that keeps track of one of the 3-of-a-kind indices (used in 2-of-a-kind check)
int pos = -1;
for (int i = 0; i < hand.length && pos == -1; i++){
// start count at one instead
int count = 1;
// start j from next position rather than 0
for (int j = i+1; j < hand.length && pos == -1; j++){
if (hand[i] == hand[j]) {
count++;
}
if (count == 3) {
pos = i;
}
}
}
// if we didn't find 3-of-a-kind, return false
if (pos == -1)
return false;
// look for 2-of-a-kind
for(int i = 0; i < hand.length; i++){
// exclude elements that match one of the 3-of-a-kind
if (hand[i] != hand[pos]){
for(int j = i + 1; j < hand.length; j++){
if(hand[i] == hand[j]){
return true;
}
}
}
}
return false;
}
A full house consists of 2 different integers, so keep a counter for both. It also needs to keep track of the 2 different values. If you combine this you get something like this:
public static boolean containsFullHouse(int[] hand)
{
int value1 = -1, count1 = 0;
int value2 = -1, count2 = 0;
for (int i = 0; i < hand.length; i++) {
if(hand[i] == value1) {
// Found another value1 card
count1++;
} else if(hand[i] == value2) {
// Found another value2 card
count2++;
} else if(value1 == -1) {
// Found a new card, store as value1
value1 = hand[i];
count1++;
} else if(value2 == -1) {
// Found a new card, store as value2
value2 = hand[i];
count2++;
} else {
// Found a third card, so it cannot be a full house!
return false;
}
}
if(value2 == -1) {
// Found 'five of a kind'?!
return false;
}
// Check if it is a full house
return (count1 == 3 && count2 == 2) || (count1 == 2 && count2 == 3;)
}

Categories