java - how to efficiently categorize user input - java

I'm trying to make a simple program that reads the user inputted integer and categorizes it based on the value until the counter reaches 70.
Code:
int counter = 0;
int value;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int i = 0;
Scanner scan = new Scanner(System.in);
while (counter != 70) {
value = scan.nextInt();
if (value >= 45 && value <= 55) {
a++;
counter++;
} else if (value >= 56 && value <= 66) {
b++;
counter++;
} else if (value >= 67 && value <= 77) {
c++;
counter++;
} else if (value >= 78 && value <= 88) {
d++;
counter++;
} else if (value >= 89 && value <= 99) {
e++;
counter++;
} else if (value >= 100 && value <= 110) {
i++;
counter++;
} else {
}
}
System.out.println(a + "-" + b + "-" + c + "-" + d + "-" + e + "-" + i);
Obviously, this code is inefficient and I know for a fact that there are less time consuming ways to replicate this. I feel pretty dumb right now so please tell me the most efficient way.

Also if doing a certain number of time, the I feel a for loop is clearer.
consider using an array of ints rather than a-i
int [] values = new int [6];
Scanner scan = new Scanner(System.in);
for (int counter = 0; counter < 70; counter++)
{
int value = scan.nextInt();
if (value >= 45 && value <= 55) {
values[0]++;
} else if (value >= 56 && value <= 66) {
values[1]++;
} else if (value >= 67 && value <= 77) {
values[2]++;
} else if (value >= 78 && value <= 88) {
values[3]++;
} else if (value >= 89 && value <= 99) {
values[4]++;
} else if (value >= 100 && value <= 110) {
values[5]++;
} else {
counter--; // out of bounds - try again
}
}

Try this.
int counter = 0;
int[] a = new int[6];
Scanner scan = new Scanner(System.in);
while (counter < 70) {
int value = scan.nextInt();
if (value >= 45 && value <= 110) {
a[(value - 45) / 11]++;
counter++;
}
}
System.out.print(a[0]);
for (int i = 1; i < a.length; ++i)
System.out.print("-" + a[i]);
System.out.println();

I've been thinking how to make this program with loops so this is what I came up with:
int min = 45;
int max = 55;
int counter = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
while (min <= 100) {
for (int value : list) {
if (value >= min && value <= max) {
counter++;
}
}
System.out.print(counter + "-");
min += 11;
max += 11;
counter = 0;
I really have no idea if this allocates memory faster or not but to me, it looks tidier although it may not be efficient.

One way to improve readability is to change variables names:
a becomes from45to55
b becomes from56to66
You can also move repeated operations into one method:
public static void increment(int value, int counter) {
value++;
counter++;
}
And use try with resources block to close Scanner. Full code:
public static void main(String[] args) {
int counter = 0;
int value;
int from45to55 = 0;
int from56to66 = 0;
int from67to77 = 0;
int from78to88 = 0;
int from89to99 = 0;
int from100to110 = 0;
try (Scanner scan = new Scanner(System.in)) {
while (counter != 70) {
value = scan.nextInt();
if (value >= 45 && value <= 55) {
increment(from45to55, counter);
} else if (value >= 56 && value <= 66) {
increment(from56to66, counter);
} else if (value >= 67 && value <= 77) {
increment(from67to77, counter);
} else if (value >= 78 && value <= 88) {
increment(from78to88, counter);
} else if (value >= 89 && value <= 99) {
increment(from89to99, counter);
} else if (value >= 100 && value <= 110) {
increment(from100to110, counter);
} else {
}
}
}
}
public static void increment(int value, int counter) {
value++;
counter++;
}

Related

Why do I see this weird symbol in place of characters in the char array in java?

output
I'm getting these weird symbols while trying to display this char array. Same problem in online compiler too. what to do?
It happened once to me in C++ too. Either it shows nothing or this. It's making me crazy.
package com.avishkar;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
System.out.println(Arrays.toString(con));
System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
System.out.println(ans);
}
}
I modified your code to print out the hexadecimal value of the characters, rather than the characters themselves.
The output looks like this:
0 0 0 0
61 61 65 65 0
61 0 61 0 65 0 65 0 0
Your "unprintable" characters are hexadecimal zero, which is unprintable.
Here's the modified code.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
for (char c : con) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(con));
for (char c : vow) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
for (char c : ans.toCharArray()) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(ans);
}
}

How can I use values stored in an array to another method to do a calculation?

static void diceRoll(int[] val) {
for (int i=0;i<6;i++) {
int roll1 = (int) ((Math.random() * 1000 % 6 + 1));
int roll2 = (int) ((Math.random() * 1000 % 6 + 1));
int roll3 = (int) ((Math.random() * 1000 % 6 + 1));
int roll4 = (int) ((Math.random() * 1000 % 6 + 1));
int total =0;
if ((roll1 < roll2) && (roll1 < roll3) && (roll1 < roll4)) {
total= roll2 + roll3 + roll4;
} else if ((roll2 < roll1) && (roll2 < roll3) && (roll2 < roll4)) {
total= roll1 + roll3 + roll4;
} else if ((roll3 < roll1) && (roll3 < roll2) && (roll3 < roll4)) {
total = roll1 + roll2 + roll4;
} else if ((roll4 < roll1) && (roll4 < roll2) && (roll4 < roll3)) {
total = roll1 + roll2 + roll3;
}
}
}
static void calculateBonus(int[] bonusVal){
int bonus=0;
int[] val= new int[6];
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
if (val[i] > 10 && val[i] != 11) {
bonusVal[j] = (val[i] - 10) / 2;
} else if (val[i] < 10) {
bonusVal[j] = ((val[i] / 2) - 5);
} else if (val[i] == 10 || val[i] == 11) {
bonusVal[j] = 0;
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
//Declaring variables
int level;
String choice = null;
//Getting the Level value
System.out.println("Enter the Level value :");
level = sc.nextInt();
while ((level<=0)||(level>20)){
System.out.println("Invalid input.Please enter a number between 1-20.");
System.out.println("Enter the Level value : ");
level = sc.nextInt();
}
do{
int[] val= new int[6];
int _str= val[0];
int con= val[1];
int dex= val[2];
int _int= val[3];
int wis= val[4];
int _cha= val[5];
int [] bonusVal=new int[6];
int bonus1= bonusVal[0];
int bonus2= bonusVal[1];
int bonus3= bonusVal[2];
int bonus4= bonusVal[3];
int bonus5= bonusVal[4];
int bonus6= bonusVal[5];
//Printing the Level
System.out.println("\n\n\n\n\nLevel : [ "+level+" ]");
//Displaying out put
System.out.println("_Str : ["+_str+" ]"+"["+bonus1+"]");
System.out.println("Dex : ["+dex+" ]"+"["+bonus2+"]");
System.out.println("Con : ["+con+" ]"+"["+bonus3+"]");
System.out.println("Int : ["+_int+" ]"+"["+bonus4+"]");
System.out.println("Wis : ["+wis+" ]"+"["+bonus5+"]");
System.out.println("_Cha : ["+_cha+" ]"+"["+bonus6+"]");
//Calculating the Hit points
double hp = (((Math.random()*1000 %6+1)+bonus3)*level);
//Print the Hit points
System.out.println("HP : ["+hp+"]");
//Give the chance to re-roll or continue
System.out.println("Type r if you want to re-roll or any other character if you want to continue :");
choice = sc.next();
}
while (choice.equals("r"));;
}
}
I think i had made mistakes in the second method .I want to figure out how can i use above stored values in the array to calcuate bonus and store the values for bonus in another array.This is the program i have so far.I still didnt got the output i neede.I need to get 6 values from dice roll method and store them in an array.and then i want to call the values to calculate bonus and store those bonus values in another array.
I think you want to do something like below. I haven't compiled the code, let me know if you face any issues in compiling.
static int[] calculateBonus(int[] val) {
int[] bonusVal = new int[val.length];
for(int j=0; j < val.length; j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonusVal;
}
You need to return an array from the first method to start with, right now it doesn't work with an array at all.
Change it to the below to return an array and have a new array variable
static int[] diceRoll() {
final int rolls = 6;
int[] result = new int[rolls];
//the for loop...
at the end of the for loop you store the value in the array and then at the end return the array so the end of the method will look like
result[i] = total;
}
return result;
}
The calculateBonus will use this returned array as input and it will also work internally with an array and not an int as you have now. I also added that it will return an array.
static int[] calculateBonus(int[] val){
int count = val.length;
int[] bonus = new int[count];
for(int j=0;j<count;j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonus;
}
A simple run
public static void main(String[] args) {
int[] values = diceRoll();
int[] bonus = calculateBonus(values);
for(int i=0; i<bonus.length; i++) {
System.out.println(bonus[i]);
}
}
Update
Below is a new version of the two methods that addresses the questions I asked in the comment and also clean up the code some.
Main difference is that I use a ArrayList in the diceRole method and that calculateBonus now uses double.
static int[] diceRoll() {
int[] result = new int[6];
for (int i=0;i<6;i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < 4; j++) {
list.add(new Integer((int) ((Math.random() * 1000 % 6 + 1))));
}
Collections.sort(list); //list is now in ascending order
int total =0;
for (int j = 1; j < list.size(); j++) {
total += list.get(j).intValue();
}
result[i] = total;
}
return result;
}
static double[] calculateBonus(int[] val) {
int count = val.length;
double[] bonus = new double[count];
for(int j=0;j<count;j++) {
double value = 0.0;
if (val[j] > 11) {
value = (val[j] - 10.0) / 2.0;
} else if (val[j] < 10.0) {
value = ((val[j] / 2.0) - 5.0);
}
bonus[j] = value;
}
return bonus;
}

Can't figure out the error Luhn check

Its supose to tell me if a card is valid or invalid using luhn check
4388576018402626 invalid
4388576018410707 valid
but it keeps telling me that everything is invalid :/
Any tips on what to do, or where to look, would be amazing. I have been stuck for a few hours.
It would also help if people tell me any tips on how to find why a code is not working as intended.
im using eclipse and java
public class Task11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long number) {
return (getSize(number) >= 13) && (getSize(number) <= 16)
&& (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37))
&& (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0) {
start = digits.length() - 1;
} else {
start = digits.length() - 2;
}
while (start != 0) {
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
public static int getDigit(int number) {
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number != 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d) {
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k) {
String size = Long.toString(number);
if (size.length() <= k) {
return number;
} else {
return Long.parseLong(size.substring(0, k));
}
}
}
You should modiffy your isValid() method to write down when it doesn't work, like this:
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
System.out.println("Err: Number "+number+" is too long");
return false;
} else if (! (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37)) ){
System.out.println("Err: Number "+number+" prefix doesn't match");
return false;
} else if( (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 != 0){
System.out.println("Err: Number "+number+" doesn't have sum of odd and evens % 10. ");
return false;
}
return true;
}
My guess for your problem is on the getPrefix() method, you should add some logs here too.
EDIT: so, got more time to help you (don't know if it's still necessary but anyway). Also, I corrected the method I wrote, there were some errors (like, the opposite of getSize(number) >= 13 is getSize(number) < 13)...
First it will be faster to test with a set of data instead of entering the values each time yourself (add the values you want to check):
public static void main(String[] args) {
long[] luhnCheckSet = {
0, // too short
1111111111111111111L, // too long (19)
222222222222222l // prefix doesn't match
4388576018402626l, // should work ?
};
//System.out.print("Enter a credit card number as a long integer: ");
//long number = input.nextLong();
for(long number : luhnCheckSet){
System.out.println("Checking number: "+number);
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
System.out.println("-");
}
}
I don't know the details of this, but I think you should work with String all along, and parse to long only if needed (if number is more than 19 characters, it might not parse it long).
Still, going with longs.
I detailed your getPrefix() with more logs AND put the d in parameter in long (it's good habit to be carefull what primitive types you compare):
public static boolean prefixMatched(long number, long d) {
int prefixSize = getSize(d);
long numberPrefix = getPrefix(number, prefixSize);
System.out.println("Testing prefix of size "+prefixSize+" from number: "+number+". Prefix is: "+numberPrefix+", should be:"+d+", are they equals ? "+(numberPrefix == d));
return numberPrefix == d;
}
Still don't know what's wrong with this code, but it looks like it comes from the last test:
I didn't do it but you should make one method from sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 and log both numbers and the sum (like i did in prefixMatched() ). Add logs in both method to be sure it gets the result you want/ works like it should.
Have you used a debugger ? if you can, do it, it can be faster than adding a lot of logs !
Good luck
EDIT:
Here are the working functions and below I provided a shorter, more efficient solution too:
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count- 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
in.close();
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
I also found a solution with less lines of logic. I know you're probably searching for an OO approach with functions, building from this could be of some help.
Similar question regarding error in Luhn algorithm logic:
Check Credit Card Validity using Luhn Algorithm
Link to shorter solution:
https://code.google.com/p/gnuc-credit-card-checker/source/browse/trunk/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
And here I tested the solution with real CC numbers:
public class CreditCardValidation{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
public static void main(String[] args){
//String num = "REPLACE WITH VALID NUMBER"; //Valid
String num = REPLACE WITH INVALID NUMBER; //Invalid
num = num.trim();
if(Check(num)){
System.out.println("Valid");
}
else
System.out.println("Invalid");
//Check();
}
}

How to get 10 per line -leap years

Please help with formatting my output.
I have been asked to "Write a program that displays all the leap years, ten per line, in the twenty-first century (from 2001 to 2100), separated by exactly one space".
Although I get the right results, it's not in the required format.
Thanks in advance
public class Leapyear {
public static void main(String[] args) {
//declare variabls;
int year;
int count=1;
int yearsperline = 10;
//loop
for(year=2001;2001<=2100;year++){
if((year%4==0 && year%100!=0) || (year%400==0))
System.out.print(year+",");
if ( year ==2100)
break;
while (count%10==0)
System.out.println();
}
}
}
You can write something like this:
//declare variables;
final int YEARS_PER_LINE = 10;
final int START_YEAR = 2001;
//loop
for(int year = START_YEAR; year <= 2100; year++){
System.out.print(year);
if((year - START_YEAR) % YEARS_PER_LINE == (YEARS_PER_LINE - 1)) {
System.out.println();
} else {
System.out.print(",");
}
}
Try this one:
public class LeapYear
{
public static void main(String[] args)
{
// declare variables
final int startYear = 2001;
final int endYear = 2100;
final int yearsPerLine = 10;
// loop
for (int year = startYear, count = 0; year <= endYear; year++)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
if (count % yearsPerLine != 0)
System.out.print(" ");
else if (count > 0 && count % yearsPerLine == 0)
System.out.println();
System.out.print(year);
++count;
}
}
}
}
int startFromYear = 2001;
int stopAtYear = 2100;
int count = 0;
for(int i = startFromYear; i <= stopAtYear; i++){
if((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0)){
System.out.print(i + " ");
count++;
if(count % 10 ==0)
System.out.println();
}
}
100% correct! and easy to understand.
public class LeapYears
{
public static void main(String[] args)
{
int count = 0;
for(int i = 2001; i <= 2100; i++)
{
if ((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0))
{
count++;
//if count is 10 then start a new line.
if(count % 10 == 0)
{
System.out.println(i);
}
//if count is smaller 10 then in the same line
else
{
System.out.print(i + " ");
}
}
}
}
}

java backtracking generating numbers

I've wrote a little program to generate numbers that have 2 conditions:
has all digits from 1 tot 9 so a number like 123456789
the number must be divisible by the last digit
for example 442 because 4 % 2 == 0 and 4 % 4 == 0
This is my backtrack algorithm:
static void backTrack(int value)
{
//Check if the number has all 9 digits, that it is dividable
if(isNine(value) && isDiv(value))
{
//System.out.println(value);
System.out.println("Found solution.");
System.out.println(aantal);
aantal++;
}
else
{
if(howMany(value) >= 9)
return;
for(int i = 1; i < 10; i++)
{
value = value * 10 + i;
if(value % i == 0 && howMany(value) <= 9)
{
//System.out.println(value);
backTrack(value);
}
value = value / 10;
}
}
}
//Gives length of integer for example 124 must give 3, 13 gives 2
static int howMany(int value)
{
int test = value % 10;
value = value / 10;
int teller = 0;
while(test != 0)
{
teller++;
test = value % 10;
value = value / 10;
}
return teller;
}
//Checks if the number is dividable by the last digit of the number and keeps recursive doing this for the whole number so 442 = YES 235 = NO
static boolean isDiv(int value)
{
int test = value % 10;
value = value / 10;
while(test != 0)
{
if(value % test == 0)
{
test = value % 10;
value = value / 10;
}
else
return false;
}
return true;
}
//Checks if the number has all digits from 1 to 9
static boolean isNine(int value)
{
boolean values[] = new boolean[10];
int test = value % 10;
int counter = 0;
for(int i = 1; i < values.length; i++)
values[i] = false;
while( test != 0)
{
if(values[test])
return false;
else
{
values[test] = true;
value = value /10;
test = value % 10;
}
}
for(int i = 1; i < values.length; i++)
{
if(values[i])
counter++;
}
if(counter == 9)
return true;
else
return false;
}
It never comes to a solution, I tested all subfunctions and those are working great.
Is there something wrong with my backtracking scheme? The System.out.println(aantal) is just a var to count how many solutions I've found.
I start with backtrack(0);
static void backTrack(int value)
{
//Check if the number has all 9 digits, that it is dividable
if(isNine(value)) // CHANGED this if test.
{
System.out.println("Found solution.");
System.out.println(value);
aantal++;
}
else
{
if(howMany(value) >= 9)
return;
for(int i = 1; i < 10; i++)
{
value = value * 10 + i;
if(value % i == 0 && howMany(value) <= 9)
{
//System.out.println(value);
backTrack(value);
}
value = value / 10;
}
}
}
//Gives length of integer for example 124 must give 3, 13 gives 2
static int howMany(int value)
{
int test = value % 10;
value = value / 10;
int teller = 0;
while(test != 0)
{
teller++;
test = value % 10;
value = value / 10;
}
return teller;
}
//Checks if the number has all digits from 1 to 9
static boolean isNine(int value)
{
boolean values[] = new boolean[10];
int test = value % 10;
int counter = 0;
for(int i = 1; i < values.length; i++)
values[i] = false;
while( test != 0)
{
if(values[test])
return false;
else
{
values[test] = true;
value = value /10;
test = value % 10;
}
}
for(int i = 1; i < values.length; i++)
{
if(values[i])
counter++;
}
if(counter == 9)
return true;
else
return false;
}
}

Categories