Eclipse says <terminated>, not sure why - java

I'm not sure, when I run this in eclipse it says . What's happening is, the input Y is a year that's less than 10000, and I have to find the next year after that one that has all different digits. For example, 2010 would print 2013 because 2013 is the next year after 2010 with all different digits.
package from1987To2013;
public class from1987To2013 {
public static void main(String[] args) {
//Y is year input
int Y = 2011;
//number of digits in Y
int length = String.valueOf(Y).length();
//Turns the Y into an int array arrayY
String temp = Integer.toString(Y);
int[] arrayY = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
arrayY[i] = temp.charAt(i) - '0';
}
//first for loop
for (int i = 0; i < 10000; i++) {
//find every value from Y to 10000
int a = Y + i;
//changes if its true or not
boolean bool = true;
//this loop goes through once if y = 2, twice if y = 33, thrice if y = 456, four times if y == 4666, etc
int d = 0;
for (int b = 0; b < length; b++)
//d is the b - 1 which will be compared with the position at b
d = b-1;
int b = 0;
//checks if they're all equal
if (arrayY[d] != (arrayY[b])) {
} else {
bool = false;
break;
}
if (bool = true){
System.out.print(a);
}
}
}
}

As well as changing the code as per #ZouZou's comment, I'm not quite sure why, but i had to change this line:
System.out.print(a);
to
System.out.println(a);
in order to get any output from eclipse.
p.s. your logic doesn't work, but at least this gives you output so you can debug it now.

Related

how to determine if a number is a smart number in java?

I have this question I am trying to solve. I have tried coding for the past 4 hours.
An integer is defined to be a Smart number if it is an element in the infinite sequence
1, 2, 4, 7, 11, 16 …
Note that 2-1=1, 4-2=2, 7-4=3, 11-7=4, 16-11=5 so for k>1, the kth element of the sequence is equal to the k-1th element + k-1. For example, for k=6, 16 is the kth element and is equal to 11 (the k-1th element) + 5 ( k-1).
Write function named isSmart that returns 1 if its argument is a Smart number, otherwise it returns 0. So isSmart(11) returns 1, isSmart(22) returns 1 and isSmart(8) returns 0
I have tried the following code to
import java.util.Arrays;
public class IsSmart {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = isSmart(11);
System.out.println(x);
}
public static int isSmart(int n) {
int[] y = new int[n];
int j = 0;
for (int i = 1; i <= n; i++) {
y[j] = i;
j++;
}
System.out.println(Arrays.toString(y));
for (int i = 0; i <= y.length; i++) {
int diff = 0;
y[j] = y[i+1] - y[i] ;
y[i] = diff;
}
System.out.println(Arrays.toString(y));
for (int i = 0; i < y.length; i++) {
if(n == y[i])
return 1;
}
return 0;
}
}
When I test it with 11 it is giving me 0 but it shouldn't. Any idea how to correct my mistakes?
It can be done in a simpler way as follows
import java.util.Arrays;
public class IsSmart {
public static void main(String[] args) {
int x = isSmart(11);
System.out.println("Ans: "+x);
}
public static int isSmart(int n) {
//------------ CHECK THIS LOGIC ------------//
int[] y = new int[n];
int diff = 1;
for (int i = 1; i < n; i++) {
y[0] =1;
y[i] = diff + y[i-1];
diff++;
}
//------------ CHECK THIS LOGIC ------------//
System.out.println(Arrays.toString(y));
for (int i = 0; i < y.length; i++) {
if(n == y[i])
return 1;
}
return 0;
}
}
One of the problems is the way that your populating your array.
The array can be populated as such
for(int i = 0; i < n; i++) {
y[i] = (i == 0) ? 1 : y[i - 1] + i;
}
The overall application of the function isSmart can be simplified to:
public static int isSmart(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = (i == 0) ? 1 : array[i - 1] + i;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == n) return 1;
}
return 0;
}
Note that you don't need to build an array:
public static int isSmart(int n) {
int smart = 1;
for (int i = 1; smart < n; i++) {
smart = smart + i;
}
return smart == n ? 1 : 0;
}
Here is a naive way to think of it to get you started - you need to fill out the while() loop. The important thing to notice is that:
The next value of the sequence will be the number of items in the sequence + the last item in the sequence.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
System.out.println(isSmart(11));
}
public static int isSmart(int n) {
ArrayList<Integer> sequence = new ArrayList<Integer>();
// Start with 1 in the ArrayList
sequence.add(1);
// You need to keep track of the index, as well as
// the next value you're going to add to your list
int index = 1; // or number of elements in the sequence
int nextVal = 1;
while (nextVal < n) {
// Three things need to happen in here:
// 1) set nextVal equal to the sum of the current index + the value at the *previous* index
// 2) add nextVal to the ArrayList
// 3) incriment index by 1
}
// Now you can check to see if your ArrayList contains n (is Smart)
if (sequence.contains(n)) { return 1; }
return 0;
}
}
First think of a mathematical solution.
Smart numbers form a sequence:
a0 = 1
an+1 = n + an
This gives a function for smart numbers:
f(x) = ax² + bx + c
f(x + 1) = f(x) + x = ...
So the problem is to find for a given y a matching x.
You can do this by a binary search.
int isSmart(int n) {
int xlow = 1;
int xhigh = n; // Exclusive. For n == 0 return 1.
while (xlow < xhigh) {
int x = (xlow + xhigh)/2;
int y = f(x);
if (y == n) {
return 1;
}
if (y < n) {
xlow = x + 1;
} else {
xhigh = x;
}
}
return 0;
}
Yet smarter would be to use the solution for x and look whether it is an integer:
ax² + bx + c' = 0 where c' = c - n
x = ...
I was playing around with this and I noticed something. The smart numbers are
1 2 4 7 11 16 22 29 ...
If you subtract one you get
0 1 3 6 10 15 21 28 ...
0 1 2 3 4 5 6 7 ...
The above sequence happens to be the sum of the first n numbers starting with 0 which is n*(n+1)/2. So add 1 to that and you get a smart number.
Since n and n+1 are next door to each other you can derive them by reversing the process.
Take 29, subtract 1 = 28, * 2 = 56. The sqrt(56) rounded up is 8. So the 8th smart number (counting from 0) is 29.
Using that information you can detect a smart number without a loop by simply reversing the process.
public static int isSmart(int v) {
int vv = (v-1)*2;
int sq = (int)Math.sqrt(vv);
int chk = (sq*(sq+1))/2 + 1;
return (chk == v) ? 1 : 0;
}
Using a version which supports longs have verified this against the iterative process from 1 to 10,000,000,000.

Debugging hackerrank week of code 25: Between two sets

I have a problem on hackerrank as below.
My answer is after this problem description, it shows ok after running the code, but then when I submit the code, this code only passes 3 per 6 test cases. I still not figure out where is my mistake. Any helps would be very appreciated. Thanks.
Consider two sets of positive integers, A={a0, a1, ..., a(n-1)} and B={b0, b1, ..., b(m-1)} . We say that a positive
integer, x, is between sets A and B if the following conditions are
satisfied:
All elements in A are factors of x. And x is a factor of all elements in B.
Given A and B, find and print the number of integers (i.e., possible 's)
that are between the two sets.
Input Format
The first line contains two space-separated integers describing the
respective values of n (the number of elements in set A) and m (the
number of elements in set B). The second line contains distinct
space-separated integers describing a0, a1, ..., a(n-1). The third line contains
distinct space-separated integers describing b0, b1, ..., b(m-1).
Constraints
1<= n, m <= 10
1<= a(i) <= 100
1<= b(i) <= 100
Output Format
Print the number of integers that are considered to be between A and B.
Sample Input
2 3
2 4
16 32 96
Sample Output
3
Explanation
The integers that are between A={2, 4} and B={16, 32, 96} are 4, 8, and 16.
My code:
public class Solution {
public static boolean checkX_function(int Ax, int [] b){
for(int i=0; i<b.length; i++){
if(b[i]%Ax!=0){
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // n: length of array A
int m = in.nextInt(); // m: length of array B
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int[] b = new int[m];
for(int b_i=0; b_i < m; b_i++){
b[b_i] = in.nextInt();
}
boolean checkX = false;
int count=0;
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
int Ax = 0;
Ax = a[i]*a[j];
//check if Ax is satisfied for all elements in B
checkX = checkX_function(Ax, b);
if (checkX == true){
count++;
}
}
}
System.out.println(count);
}
}
Please have a look
int main(){
int n;
int m;
int currentNum,count=0 ;
cin >> n >> m;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
vector<int> b(m);
for(int b_i = 0;b_i < m;b_i++){
cin >> b[b_i];
}
currentNum = a[n-1];
do{
bool check1 = true;
for(int i=0;i<n;i++){
if(currentNum%a[i]!=0){
check1 = false;
}
}
if(check1){
bool check = true;
for(int i=0;i<m;i++){
if(b[i]%currentNum!=0){
check = false;
}
}
if(check){
// cout<<currentNum<<"\n";
count++;
}
}
currentNum ++;
}while(currentNum <=b[0]);
cout<<count;
return 0;
}
Hi have written the below code and it's passed all the test cases.
function getTotalX(a, b) {
// Write your code here
let counter = 0;
for (let currentNum = 0; currentNum <= 100; currentNum++) {
let check1 = true;
for (let j = 0; j < a.length; j++) {
if (currentNum % a[j] != 0) {
check1 = false;
}
}
if (check1) {
let checkx = checkFactor(currentNum, b);
if (checkx) {
counter++;
}
}
}
return counter;
}
function checkFactor(ax, b) {
for (let i = 0; i < b.length; i++) {
if (b[i] % ax != 0) {
return false;
}
}
return true;
}
def getTotalX(a, b):
def factor(x,y):
return x%y==0
list1=[]
for i in range(max(a),min(b)+1):
if all(factor(i,x) for x in a) and all(factor(x,i) for x in b):
list1.append(i)
return len(list1)

Pascal's triangle code failing after certain row

import java.util.*;
public class PascalFinal
{
public static void main()
{
Scanner f = new Scanner(System.in);
System.out.print("How many rows of Pascal's triangle do you want to print: ");
int row = f.nextInt();
Pascal(row);
showPascal(Pascal(row));
}
public static void showPascal(int[][] Pascal)
{
for(int a = 0; a < Pascal.length; a++)
{
for(int b = 0; b < Pascal[a].length; b++)
{
System.out.print(Pascal[a][b] + " ");
}
System.out.println();
}
}
public static int[][] Pascal(int x)
{
int[][] Pascal = new int[x][];
int rowLength = 1;
for(int a = 0; a < x; a++)
{
Pascal[a] = new int[rowLength];
rowLength++;
}
for(int a = 0; a < Pascal.length; a++)
{
for(int b = 0; b < Pascal[a].length; b++)
{
int Piscal = a-b;
Pascal[a][b] = Factorial(a)/Factorial(b)/Factorial(Piscal);
}
}
return Pascal;
}
public static int Factorial(int n)
{
if (n < 0)
{
int x = -1;
return x;
}
if (n == 0)
{
int x = 1;
return x;
}
else
{
return (n * Factorial(n - 1));
}
}
When I run that code, it works perfectly fine for the first 13 lines, however it then starts putting in weird values for the rest of the rows. My first though was that it could be due to the values getting too big from the factorial method and the int datatype not being able to hold it but I am not sure. No clue why this is getting messed up. Please help.
Edit: I tried using the long datatype instead of int, but the same issue occurs once I get past 20 rows.
If the Pascal's triangle that you have to draw is the one designed here
you do not need to evaluate any factorial.
Each row can be evaluated using the previous row with simple sums...
You can do it using an array. As a suggestion, start with the arrary: [0, 1, 0]
and remember that the next row can be evaluated doing a sum of the adjacent numbers of the previous row.
You need to loop over [0, 1, 0] and create [0,1,1,0] and then [0,1,2,1,0]
As you can see, the first is 0 and remains always 0, the next is the sum of the first two, and so on...

How to access an integer that is inside braces?

Data file:
J A V A
1 H 11 H 21 H
1 V 2 V 3 V
2 H 12 H 22 H
3 V 4 V 5 V
7 H 6 V 17 H
Code (part of a larger program):
File dataFile = new File("data.txt");
Scanner in;
in = new Scanner (dataFile);
String letter1 = in.next(); //Reads first letter of the word and stores it as a string
String letter2 = in.next(); //Reads second letter of the word and stores it as a string
String letter3 = in.next(); //Reads third letter of the word and stores it as a string
String letter4 = in.next(); //Reads fourth letter of the word and stores it as a string
// Not all of these ints are used in the code shown here
int firstLetterValue1;
int secondLetterValue1;
int thirdLetterValue1;
int fourthLetterValue1;
int firstLetterValue2;
int secondLetterValue2;
int thirdLetterValue2;
int fourthLetterValue2;
int firstLetterValue3;
int secondLetterValue3;
int thirdLetterValue3;
int fourthLetterValue3;
int multiplier1 = 1;
int multiplier2 = 1;
int multiplier3 = 1;
int totalWordValue1 = 0;
int totalWordValue2 = 0;
int totalWordValue3 = 0;
// These test to see whether the first, second, third, or fourth letter of the word
// Are equal to a specified letter and if they are,
// then a value is stored into a different integer
if (letter1.equalsIgnoreCase("A") || letter1.equalsIgnoreCase("E"))
{
firstLetterValue1 = 1;
firstLetterValue2 = 1;
firstLetterValue3 = 1;
}
else if (letter1.equalsIgnoreCase("D") || letter1.equalsIgnoreCase("R"))
{
firstLetterValue1 = 2;
firstLetterValue2 = 2;
firstLetterValue3 = 2;
}
else if (letter1.equalsIgnoreCase("B") || letter1.equalsIgnoreCase("M"))
{
firstLetterValue1 = 3;
firstLetterValue2 = 3;
firstLetterValue3 = 3;
}
else if (letter1.equalsIgnoreCase("V") || letter1.equalsIgnoreCase("Y"))
{
firstLetterValue1 = 4;
firstLetterValue2 = 4;
firstLetterValue3 = 4;
}
// For example, in the word "J A V A", the first letter, which is "J", will store
// the value "8" into the integers inside the brackets (firstLetterValue1, firstLetterValue2, etc.)
else if (letter1.equalsIgnoreCase("J") || letter1.equalsIgnoreCase("X"))
{
firstLetterValue1 = 8;
firstLetterValue2 = 8;
firstLetterValue3 = 8;
}
for (int num = 0; num <= 4; num++)
{
int location1 = in.nextInt();
String direction1 = in.next();
// This is where I am getting my problem: "The local variable firstLetterValue1 has not been initialized"
if ((location1 == 1) && (direction1.equalsIgnoreCase("H")))
{
firstLetterValue1 *= 1;
secondLetterValue1 *= 1;
thirdLetterValue1 *= 2;
fourthLetterValue1 *= 1;
multiplier1 = 1;
totalWordValue1 = (firstLetterValue1 + secondLetterValue1 + thirdLetterValue1 + fourthLetterValue1) * multiplier1;
}
}
I tried to outline my problem with the comments. So, I am getting an error at the part with if ((location1 == 1) && (direction1.equalsIgnoreCase("H"))). I know that the program wants me to declare the integer by int firstLetterValue1 = 0;, but the problem I am getting is that the whole part before it with the if statements will just be skipped. I want the firstLetterValue1, firstLetterValue2, etc. integers to keep their value.
If this is still unclear let me know
You just have to assign default value to local variables that would make it compilable
int i = -1;
if( /* some condition */) {
i = 10;
}
System.out.println(i);
If none of the conditions in the if / else if is true, the variables won't be initialised. Two options:
initialise them with a default value when you declare them
add an else statement to ensure that the variables will always be initialised

algorithm for adding the diagonals on a square or rectangular matrix, starting rightwise

I want to add the diagonals in a square or rectangular matrix to emulate the process of adding the partial results in a multiplying algorithm.
Like this:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
I need to run this, step by step, to satisfy the requirements of an online judge program. I have already figured out how to get the partial results of the multiplications (the humbers 2412, 7236, 4824, 7236) and I have placed them on a square matrix.
I realized I can get the addition result of this matrix by considering square or rectangular like:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
and get the result of the addition by adding each diagonal (starting with the upper right one) and taking into account the carry of the addition and using an auxiliary array that has the same number of digits as number_of_digits_in_operand_a + number_of_digits_in_operand_b (operand a being 2412 and operand b being 3231, in this case).
For example, the array result, on its rightmost position should be:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
Well, I'm stuck writing the double nested loop that's supposed to add these diagonals starting with the upper right one. Help. Please.
I ended up using this (don't ask why it converts a BigInteger to an ArrayList and viceversa, it's a bizarre homework requirement).
public static BigInteger simpleMultiply(BigInteger x, BigInteger y) throws IOException {
char [] longerNum;
char [] shorterNum;
ArrayList<Integer> multResult= new ArrayList<Integer>(2000);
if(x.compareTo(y)>=0){ // x is a longer/equal num
longerNum = x.toString().toCharArray();
shorterNum = y.toString().toCharArray();
}
else { //y is a longer num
longerNum = y.toString().toCharArray();
shorterNum = x.toString().toCharArray();
}
//shorter num equals the number of rows in partial result
// longer num + 1 equals the number of columns in partial result
int [][] partialResult = new int [shorterNum.length][longerNum.length+1];
int pastCarry=0;
int result=0;
int carry=0;
for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--){
pastCarry=0;
for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
{
int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
int lInt = Integer.parseInt(""+longerNum[lIndex]+"");
int product = sInt*lInt;
if (lIndex==0){
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult
partialResult[sIndex][lIndex] = carry;
}
else {
result = (pastCarry+product) % 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult
}
}
}
for (int i=0; i<partialResult.length;i++)
for (int j=0; j<partialResult[0].length;j++)
{
System.out.print(partialResult[i][j] + " ");
if (j==partialResult[0].length-1){System.out.println();}
}
int auxColumn=0;
int diagonalAcum=0;
//add diagonals
int copyDigit=0;
int carryDigit=0;
int lastCarry=0;
rowCycle:
for (int column=partialResult[0].length-1; column>=0; column--){
diagonalAcum=0; //carryDigit=0;
diagonalAcum+=carryDigit;
auxColumn=column;
for (int row=0; row<partialResult.length; row++){
if (auxColumn+1 ==partialResult[0].length){
diagonalAcum+=partialResult[row][auxColumn++];
copyDigit=diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
continue rowCycle;
}
diagonalAcum+=partialResult[row][auxColumn++];
} //end row cycle
copyDigit= diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
if(column==0){
lastCarry = carryDigit;
}
}
carryDigit=0; //reset
int diagonal2Acum=0;
// diagonal2Acum +=lastCarry;
int auxRow;
int diagCarry=0;
int rowLimit=partialResult.length-1;
int colLimit=partialResult[0].length-1;
int initialRow=1;
int colIndex=0;
for (int row=initialRow;row<=rowLimit;row++){
diagonal2Acum=0;
diagonal2Acum +=lastCarry;
lastCarry=0;
auxRow = row;
colIndex=0;
// partialResult[auxRow][]
while ((auxRow<=rowLimit) && (colIndex<=colLimit)){
diagonal2Acum+= partialResult[auxRow++][colIndex++];
}
if ((colIndex==0)&&(row==rowLimit)) {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
multResult.add(carryDigit);
}
else {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
}
} // end row for
StringBuilder appended = new StringBuilder();
for (int i=multResult.size()-1;i>=0;i--){
appended.append(multResult.get(i));
}
System.out.println("result is " + appended.toString());
BigInteger the_result1 = new BigInteger(appended.toString());
return the_result1;
}
Assume your partialResult dimensions are width and height you can add by the following two loops (see it here in action):
int digit = width + height - 1;
int carry = 0;
for (int d1 = width - 1; d1 >= 0; d1--) {
for (int r = 0; r < height && d1 + r < width; r++)
carry += partialResult[r][d1 + r];
result[--digit] = carry % 10;
carry /= 10;
}
for (int d2 = 1; d2 < height; d2++) {
for (int c = 0; c < width && d2 + c < height; c++)
carry += partialResult[d2 + c][c];
result[--digit] = carry % 10;
carry /= 10;
}
Note: Carry may be non-empty at the end meaning another digit before the first one in result.

Categories

Resources