How to check the similarity between two ints java - java

I am trying to create an app where the user has to memorize a random number (17 digits long) and then enter what she/he remembers.
After generating the number, how do I check how similar they are i.e. 10 of the digits match so it is 58% similar.

Lets say you compare this two strings:
String number1; // users number
String number2; // your number
Since you said both will be 17 digit long, no need to take in account different sizes (then you should go from the end):
int matches = 0;
for (int i = 0; i < number1.length(); i++) {
if (number1.substring(i, i + 1).equals(number2.substring(i, i + 1))) matches++;
}
Another approach would be with char arrays:
char[] charArray1 = number1.toCharArray();
char[] charArray2 = number2.toCharArray();
for (int i = 0; i < charArray1.length; i++) {
if (charArray1[i] == charArray2[i]) matches++;
}
Or by using Strings own array of chars (thanks #David Wallace):
for (int i = 0; i < charArray1.length; i++) {
if (number1.charAt(i) == number2.charAt(i)) matches++;
}
Now, you calculate procent:
double procent = matches / (number1.length() * 1d) * 100;
You must multiply with double value of 1, so it doesn't calculates with int, this will force it to deal with doubles.

you can use integer(or long) division and modulo to get the digits of an int.
See this java snippet:
int num1=1234;
int dig[]=new int[4];
dig[3]=num1 /1000;
dig[2]=(num1%1000)/100;
dig[1]=(num1%100) /10;
dig[0]=(num1%10) /1;
for(int i=0;i<4;i++){
System.out.println("dig"+i+" : "+dig[i]);
}
It will print:
dig0 : 4
dig1 : 3
dig2 : 2
dig3 : 1

Related

Retrieve numbers after comma (from double numbers)

Imagine that I have 4,81 (double), how can i get the figures after the comma?
I want to receive 8 as a Integer and 1 as another.
Thanks
Doubles are tricky to work with when you're interested in decimal properties such as the decimal digits of the fractional part.
I suggest you let String.valueOf do the transformation to decimal digits and work with the resulting string.
double d = 4.81;
String s = String.valueOf(d);
for (int i = s.indexOf(".") + 1; i < s.length(); i++) {
int digit = Character.getNumericValue(s.charAt(i));
System.out.println(digit);
}
Output:
8
1
You can always make this kind of loop:
double number = 4,81;
while (condition) {
number *= 10;
int nextNumber = Math.floor(number) % 10;
}

Optimal algorithm for happy numbers

Given number is n digits find 2n digits numbers
that, for example
given number is 3 then 6n numbers are from 100000 -999999
then find count of those numbers that for example
123213
1 + 2 + 3 = 2 + 1 + 3
6 = 6
I found and wrote a program for calculating little numbers, but I need the fastest algorithm to find those numbers. Ideas?
my program :
Scanner scan = new Scanner(System.in);
System.out.println("enter n ");
int say = scan.nextInt();
say *= 2;
int low = (int) Math.pow(10, say - 1);
int max = (int) Math.pow(10, say) - 1;
int counter = 0;
int first = 0;
int last = 0;
for (int i = low; i <= max; i++) {
int number = i;
first = 0;
last = 0;
for (int j = 0; j < say / 2; j++) {
int k = number % 10;
first += k;
number /= 10;
}
for (int j = 0; j < say / 2; j++) {
int k = number % 10;
last += k;
number /= 10;
}
if (first == last) {
// System.out.println(i);
counter++;
}
}
System.out.println(counter);
The numbers are called lucky tickets in Russian (a link to ru.wikipedia.org). Yet, I don't seem to find a good explanation in English besides these slides.
Basically, let us say we have 2n digits, and we want the sum of first n be equal to the sum of last n. We first count c(d,s): the number of sequences of d digits which have sum s. Here, 0 <= d <= n and 0 <= s <= 9n. This can be done by dynamic programming: c(0,0)=1, and for d > 0, c(d,s) = c(d-1,s-0) + c(d-1,s-1) + c(d-1,s-2) + ... + c(d-1,s-9) since we can take any sequence of d-1 digits and write another digit from 0 to 9.
Now, the total number of lucky tickets is the sum for different s of the numbers of lucky tickets where the sum of the first n digits is s and the sum of the last n digits is s. When s is fixed, this number is equal to c(n,s) * c(n,s): there are exactly c(n,s) ways to choose the first half, and equally many to choose the second one.
Thus the answer is sum[s=0..9n] c(n,s)^2.
There are other solutions as well involving advanced maths, but for a programmer's assignment, this would suffice. Once again, I can't find a proper source in English — sorry! Here are a few popular articles in Russian, for what it's worth.
Edit: If you in fact need to account for numbers 100000 to 999999, not 000000 to 999999, a patch would be to calculate sum[s=0..9n] (c'(n,s) * c(n,s)), where c'(n,s) is the same table but calculated with disabled addition of zero digit when adding the first digit.

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

How can I get max number that consists of some digits of an integer number

I have a number. This number has many digits. I want to write a function which returns the largest number that consists of some digits of that number. While getting that largest number, the sequence of the digits should not change.
int myFunction(int n, int cat){
...
return max;
}
If n = 38462637 and cat = 3 the function has to return 86637, i.e. if cat = 3 the function is expected to return 5-digit number, as 8 - 3 = 5. The original number has many variations of 5 digits numbers, but the largest possible number is 86637. In this case, the most important requirement is that the digits should not change their place.
Be greedy - select the largest digit that can be leftmost in the answer(if there are several positions where this digit appears, choose its leftmost occurance). A digit may be leftmost if it is not 0 and we have at least n - cat - 1 digits to the right of it.
After that use the same algorithm to create the largest number on the right of the position of this digit that has exactly n - cat - 1 digits. Continue iterating until you have your number composed. Only note that the digits you select after the first iteration may be zero(as they will no longer be leftmost in the resulting number)
EDIT: best solution that uses the algorithm described above - use range minimum query to compute the highest value that is possible for each consecutive digit position. In theory this can be done in constant time per query and linear extra memory using linear precomputation, but the algorithm is so complex and hard to implement that it will only give you improvement for really big values of n. I personally suggest using a segment tree approach that will result in O(n*log(n)) time complexity.
This is probably a bit overcomplicated, but it seems to work:
public static int myFunction(int n, int cat) {
String numString = String.valueOf(n);
int finalLength = numString.length() - cat;
int[] positions = new int[finalLength];
StringBuilder answer = new StringBuilder();
for (int i = 0; i < finalLength; i++) {
for (int j = (i == 0 ? i : positions[i - 1] + 1); j <= numString.length() - finalLength + i; j++) {
if (positions[i] == 0 || numString.charAt(j) > numString.charAt(positions[i]) ) {
positions[i] = j;
}
}
answer.append(numString.charAt(positions[i]));
}
return Integer.parseInt(answer.toString());
}
[EDIT]: A cleaner version without all the String nonsense:
public static int myFunction(int n, int cat) {
List<Integer> digits = new ArrayList<Integer>();
int number = n;
while (number > 0) {
digits.add(number % 10);
number /= 10;
}
int finalLength = digits.size() - cat;
int lastIndex = digits.size();
int answer = 0;
for (int i = 0; i < finalLength; i++) {
int highestDigit = -1;
for (int j = lastIndex - 1; j >= finalLength - i - 1; j--) {
if (digits.get(j) > highestDigit) {
highestDigit = digits.get(j);
lastIndex = j;
}
}
answer = answer * 10 + highestDigit;
}
return answer;
}
If you have access to the code, store the number as a string with a seperator (space, comma, etc) in it, then use the string separator function to put each number (string character) into it's own array location. Parse the string array and make an integer array. Then run a quick sort on the array. When that is done, take the first X number of integers and that is your number.

Iterate through each digit in a number

I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}

Categories