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
Related
import java.util.*;
import java.io.*;
public class CarFueling {
static int compute_refills(int dist,int tank,int stops[],int n){
int current_refills=0;
int num_refills=0;
int last_refill=0;
while(current_refills<=n) {
last_refill = current_refills;
while ((current_refills <= n) && (stops[current_refills + 1] - stops[last_refill]) <= tank) {
current_refills = current_refills + 1;
}
if (current_refills == last_refill)
return -1;
if (current_refills <= n)
num_refills = num_refills + 1;
}
return num_refills;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dist = scanner.nextInt();
int tank = scanner.nextInt();
int n = scanner.nextInt();
int stops[] = new int[n*n*n];// to solve array index out of bound exception increase the size of the array
for (int i = 0; i < n; i++) {
stops[i] = scanner.nextInt();
}
System.out.println(compute_refills(dist,tank,stops,n));
}
}
I think there is some issue in my while loop condition.
Input:
950
400
4
200 375 550 750
my output:
1
correct output:
2
If you look at the
(current_refills <= n) && (stops[current_refills + 1] ... )
part, two things:
current_refills <= n is true for both n-1 (the last element of a n-element array, as the first one has index 0), and n (which is already outside the array)
then stops[current_refills + 1] accesses an element "later", which is 1 or 2 elements above the max for these two cases
But actually this can work, just you could add 0 for the beginning of the trip and dist as the end:
int n = scanner.nextInt();
int stops[] = new int[n+2];
stops[0] = 0; // well, it is 0 already
stops[n+1] = dist;
for (int i = 1; i <= n; i++) {
stops[i] = scanner.nextInt();
}
Then compute_refills() may work correctly (though I haven't checked).
below is the format of the matrix. and no diagonal combinations of letters is allowed ,only vertical and horizontal combinations are allowed.
Can anyone suggest how to calculate the number of combinations required for a particular level.
example: if i say level is 1 then , only 1 letter combination is allowed i.e. A,B,C,D,E,F,G,H,I i.e. 10 combinations
if i say level is 2 then possible combinations are AA,BB,AB,AD,BC,BE,... and so on so total 36 combinations for level 2.
Like that if input is any level number given, then how do i calculate the possible number of combinations ?
A B C
D E F
G H I
J
I tried using this formula :
(n!/(r!(n-r)!)
but it doesnt calculate properly from level 2 onwards.
note : on both sides of J no letter is present.
Please suggest.
#Thientvse
This is the code that i coded... it gives correct output...can you please tell me whether my code is correct and whether it will satisfy all test cases for this scenario
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
public static int combinationCounts(int input1){
ArrayList<String> mainalternatestring = new ArrayList<String>();
ArrayList<String> mainverticalstring = new ArrayList<String>();
String sb = "ABC#DEF#GHI# J ";
String a=null,b=null,c=null,nw=null;
int mainindex = 0,counter,totalcount=10,index=0,mainindex_duplicate=0,count=1;
if(input1 > 1 && input1 <= 4){
while(mainindex != 11){
int level = 0;
counter = 0;
count=1;
char[] strtoworkon = new char[sb.length()];
index=0;
if(mainindex != 0)
mainindex = mainindex+1;
for(int j = mainindex; count!= (sb.length()-mainindex) ; j++){
if(level == input1)
break;
if(sb.charAt(j) == '#'){
level++;
if (counter == 0){
mainindex_duplicate = j;
counter = 1;
}
}
if(level <= input1){
strtoworkon[index] = sb.charAt(j);
index++;
}
count++;
}
mainindex = mainindex_duplicate;
// for sideways combinations
for(int m = 0; m <= strtoworkon.length; m++){
c = null;
if(strtoworkon[m] == ' ')
break;
if(!String.valueOf(strtoworkon).substring(m, m+(input1)).contains("#")){
c = String.valueOf(strtoworkon).substring(m, m+(input1));
if(!c.matches(".*[A-Z].*"))
break;
if(!mainalternatestring.contains(c))
mainalternatestring.add(c);
}
}
//for vertical combinations
nw = "#" + (String.valueOf(strtoworkon));
int counter1=0;
while(counter1 != 3){
c="";
for(int n = 0; n<= strtoworkon.length; n++){
if(nw.charAt(n) == '#'){
Character test = nw.charAt(n+counter1);
a = Character.toString(strtoworkon[n+counter1]).trim();
if(a.contains("#"))
break;
c = a+c;
c.trim();
}
}
if(!mainverticalstring.contains(c) && c.length() == input1)
mainverticalstring.add(c);
counter1++;
}
if(mainindex == 11)
break;
}
totalcount = totalcount + (2*mainalternatestring.size()) + (2*mainverticalstring.size());
}
return totalcount;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int output = 0;
int ip1 = Integer.parseInt(in.nextLine().trim());
output = combinationCounts(ip1);
System.out.println(String.valueOf(output));
}
}
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.)
I was challenged with the following question from a coding site :
==================================================================================
Given K prime numbers and T queries of form Ai, Bi, for each query print the number of integers between Ai and Bi (both inclusive) that are divisible by atleast one of the K given primes.
Input
First line: K and T.
Second line: K primes.
Next T lines, each contain Ai, Bi.
Output
Print T lines, denoting the answer to each of the T queries.
Constraints
1 ≤ K ≤ 10
1 ≤ T ≤ 100
1 ≤ A ≤ B ≤ 109
Each prime ≤ 107
Sample Input (Plaintext Link)
2 1
2 3
1 10
Sample Output (Plaintext Link)
7
Explanation
2,3,4,6,8,9,10 are the 7 numbers.
=======================================================================
When I run the following code (in system compiler) it works well, but when I submitted it to the site, all test cases throw nzec runtime error. Unfortunately the site does not share test cases but they can be created using the question.
Can any one please explain why there is a nzec error? I have used java so code is throwing an exception that needs to be caught:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
String[] line1 = scan.nextLine().split(" ");
int fPrime,first,last,count=0,cur;boolean duplicate=false;
int K = Integer.parseInt(line1[0]);
int T = Integer.parseInt(line1[1]);
int[][] num=new int[2][T];
// int arr[];
String[] line2 = scan.nextLine().split(" ");
if(T<=100 )
{
for(int k=0;k<T;k++)
{
if(scan.hasNextLine())
{
String[] line3 = scan.nextLine().split(" ");
num[0][k] = Integer.parseInt(line3[0]);
num[1][k] = Integer.parseInt(line3[1]);
// System.out.print("num0 = " + num[0][k]);
// System.out.println("num1 = " + num[1][k]);
}
else
{
System.out.println("Lines of Ai and Bi are missing. Make sure T lines exist");
}
}
}
else
{
System.out.print("Error! T>100");
}
if(T<=100)
{
for(int l = 0; l < T; l++)
{
first = num[0][l];
last = num[1][l];
int arr[] = new int[last];
cur=0;
// System.out.println("first = " +first);
// System.out.println("last = " +last);
for(int i = first; i<=last; i++ )
{
for(int j = 0; j < K; j++)
{
fPrime = Integer.parseInt(line2[j]);
// System.out.println("fPrime = " +fPrime);
if(( fPrime<=1000000) && (first<=1000000000 && last<=1000000000)){
if(i%fPrime==0)
{
// System.out.println("Gotcha num " + i);
for(int a = 0; a < arr.length; a++)
{
if (arr[a] == i)
{
duplicate=true;
// System.out.print("arr"+a+" = " + i);
}
}
if(duplicate==true)
{
duplicate=false;
}
else
{
arr[cur++]=i;
count++;
}
}
}
else
{
System.out.println("Make Sure 1 ? A ? B ? 10^9 Each prime ? 10^7" );
}
}
}
System.out.println(count);
}
}
else System.out.println("T can not be greater than 100");
}
}
I am doing the programming challenges of which I am doing the 3n + 1 challenge. I ahve completed code for it and it works fine for me completely BUT on the website it keeps saying that I have the wrong answer.I have no idea why if anyone can give me a reason for this it would be a great help. Code is below.
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
int array[] = new int[8];
int finalCounter = 0;
int currentCounter = 0;
Scanner scanner = null;
try {
scanner = new Scanner(
new BufferedReader(new FileReader("text.txt")));
int counter = 0;
while (scanner.hasNext()) {
array[counter] = scanner.nextInt();
counter++;
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
for (int loop = 0; loop < array.length; loop += 2) {
int i = array[loop];
int j = array[loop + 1];
finalCounter = 0;
for (int k = i; k < j; k++) {
int x = k;
currentCounter = 0;
while (x != 1) {
if (x % 2 == 0) {
x = x / 2;
currentCounter++;
} else if (x % 2 == 1) {
x = x * 3 + 1;
currentCounter++;
}
if (currentCounter > finalCounter) {
finalCounter = currentCounter;
}
}
}
System.out.println(i + " " + j + " " + (finalCounter + 1));
}
}
}
Instead of reading from file.txt, you should read the input from System.in. Since the problem statement does not says the number of test cases, you should process each case at the moment of reading the case. Your array is just 8 elements long, and I'm pretty sure there is going to be more test cases.