3n + 1 failed for unknown reason - java

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.

Related

Java program not outputting correct values

I'm trying to create a simple program that determines if a number can be written as n^x and what n and x are. Ex: 81 = 3^4. My program correctly identifies numbers that can be written as n^x but the values for n and x are way off. (this is just supposed to be an exercise). The logic in my coding is kind of confusing so here's basically what it is. First it finds a number that can divide into a (the chosen number), then it figures out if the a can be divided by the number until it reaches 1. Then it figures out how many times it takes to reach 1. I can't find any problems with the logic. Here's my code.
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
int a = scan1.nextInt();
scan1.close();
int i = 2;
boolean y = false;
int x = 0;
for (; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
int n = i;
for (; n <= a; n *= i) {
if (a % n != 0) {
y = false;
break;
}
x++;
y = true;
}
}
}
if (y == true) {
System.out.println(a + " = " + i + " ^ " + x);
}
else {
System.out.println("Your number cannot be represented as n^x");
}
}
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
int a = scan1.nextInt();
scan1.close();
int i = 2;
boolean y = false;
int x = 0;
for(; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
int n = i;
for (; n <= a; n *= i) {
if (a % n != 0) {
y = false;
}
y = true;
x = n;
break;
}
}
}
i--;
if (y == true) {
System.out.println(a + " = " + i + " ^ " + x);
}
else {
System.out.println("Your number cannot be represented as n^x");
}
}
Use a do-while for the outer loop and you won't need i--; at the end.

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

Printing integer from 2D array using nested FOR Loops

I'm having a bit of a problem with a piece of Java code, part of an AI project. The programm is supposed to take a 11x13 2d array representing a maze. The printed maze we are given uses characters for each cell, but for ease of use I've converted it to integers using a mnemonic code.
My problem is when I try to print the 2d integer array to the screen, to check eveything is OK, I get zeros at every cell, even though I have a check function in place which parses the array cell-by-cell checking for incorrect values.
The project is currently composed of 2 files. The main file - function (AISemesterProject.java) and a file that will implement the UCS algorithm in the future (UCS.java)
AISemesterProject.java
package aisemesterproject;
public class AISemesterProject
{
public static void main(String[] args)
{
UCS a = new UCS();
a.checkArrayInt();
a.printInt();
}
}
UCS.java
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(!(array_int[i][i] == 0 || array_int[i][j] == 1 || array_int[i][j] == 2 || array_int[i][j] == 8 || array_int[i][j] == 9))
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}
Output
As you can see the output is not what I expected and I have tried 4 different methods for the print (1 active, 3 commented) but the result is always the same.
Anyone have an idea what am I missing or doing wrong?
Thanks for your time.
It looks like you have a scope issue...
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
you already created the array as a class level variable
Your constructor is setting the local variable array_int. This local variable overshadows the field with the same name, and thus it never sees the array you're assigning to it.
You should make sure that you're assigning to the field, which can most easily be done by removing the int[][] word from your constructor.
Thank you everyone. I moved the declatarion from the constructor to the variable at the beggining and it worked.
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
// Array initialization outside the constructor scope
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(array_int[i][j] == 0) //Check for 0 = x
{
checker = false;
}
else if(array_int[i][j] == 1) //Check for 1 = e
{
checker = false;
}
else if(array_int[i][j] == 2) //Check for 2 = d
{
checker = false;
}
else if(array_int[i][j] == 8) //Check for 8 = s
{
checker = false;
}
else if(array_int[i][j] == 9) //Check for 9 = g
{
checker = false;
}
else //All other integers, which are false
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}

String index out of range (Repeating Sequence of digits)

I seem to be having a problem with my code which is to look for the repeating sequence of digits. I have converted(?) double to string because I get the error unreachable statement. (which I guess helps to looking for the reason why I get the error I have now?).
Whenever I run it, it goes fine until I finish entering N and D.
It'll say "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3"
Here is my code below:
import java.util.*;
public class RepeatingSequence{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
int numerator = in.nextInt();
int denominator = in.nextInt();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
for ( int i = 2; number.charAt(j) != number.charAt(i); i++ ){
index[z] = number.charAt(z);
index[j] = number.charAt(j);
index[i] = number.charAt(i);
output = output + index[i];
if ( index[i] != index[z] ){
System.out.print(index[z] + ".(" + index[j] + output + ")");
}
}
}
}
just add i < number.length() to the condition
( int i = 2; i < number.length() && number.charAt(j) != number.charAt(i); i++ )
For your exception, I think you should write safer code - something on the lines of:
int len = number.length();
for ( int i = 2; (i < len) && (j < len) &&
number.charAt(j) != number.charAt(i); i++ ){
...
}
I am not attempting to solve the problem that you are trying to solve but just the problem you are facing. Sorry for that.
I changed your code a little bit try it out and see what you think:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
double numerator = in.nextDouble();
double denominator = in.nextDouble();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
int max = -1;
int currentNumber = -1;
int temp = -1;
int tempMax = -1;
System.out.println("" + quotient);
boolean check = true;
for(int i = (number.indexOf(".") + 1); i < index.length; i++)
{
if(max == -1)
{
currentNumber = i;
temp = i;
max = 1;
tempMax = 1;
}
else
{
if(index[i] == index[i-1])
{
tempMax++;
}
else
{
if(tempMax > max)
{
check = false;
max = tempMax;
currentNumber = temp;
}
tempMax = 1;
temp = i;
}
}
}
if(check)
{
max = tempMax;
}
System.out.println(index[currentNumber] + " repeats " + max + " times.");
}
Example of input/output:
Enter N,D: 1
3
0.3333333333333333
3 repeats 16 times.

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}

Categories