Reputation: 649
I have two numbers that contain every one from 1 to 6 digits
.
I would like to compare them using JavaScript and to put a percentage according their matching.
The comparison should be done from left to right.
Example:
if 6D matching then 100% ==> Example: (value_1: 987456, value_2: 987456)
if 5D matching then 90% ==> Example: (value_1: 987450, value_2: 987456)
if 4D matching then 80% ==> Example: (value_1: 987400, value_2: 987456)
if 3D matching then 60% ==> Example: (value_1: 987000, value_2: 987456)
if 2D matching then 40% ==> Example: (value_1: 980000, value_2: 987456)
else 0% ==> Example: (value_1: 010101, value_2: 987456)
I hope that I was clear. Can you suggest me a solution how can I do it in a function ? Thank you
Upvotes: 1
Views: 4357
Reputation: 986
Convert number to string (string1, string2)
split one of the string greater length (string1 > string2) ? string1.split('')
loop every element of string2
initialize a counter to 0
check if element of string2 exists in string1 if (string1.indexOf(string2[i]) > -1) {count += 1}
finally for percentage (count/string1.length) * 100
`
var a = String(839123)
var b = String(829156)
var count = 0;
for (let i = 0 ; i < b.length; i++) {
if (a.indexOf(b[i]) > -1) {
count += 1;
}
}
alert(count); //Match Count`
Upvotes: 1
Reputation: 465
Firstly transform the number to a string and iterate over them. for example:
let number1 = 12345 + ""
let number2 = 12346 + ""
let percentageMaps = ["0%", "0%", "40%", "60%", "80%", "90%", "100%"]
function getPercentage(number1, number2) {
counter = 0;
for (var i = 0; i < number1.length; i++) {
if (number1.charAt(i) == number2.charAt(i)) {
counter++;
}
}
return percentageMaps[counter]
}
console.log(getPercentage(number1, number2))
Upvotes: 3
Reputation: 3132
You can simply take the difference of numbers and if the difference is 0 then take empty string else the length/order of difference.
keep the percentages in an array on the index of the same order it should be.
let per = [100, 90, 80, 60, 40]
calcPer = (num1, num2) => per[(Math.abs(num1 - num2) || '').toString().length] || 0;
console.log(calcPer(987456, 987456))
console.log(calcPer(987456, 987450))
console.log(calcPer(987456, 987400))
console.log(calcPer(987456, 987000))
console.log(calcPer(987456, 900000))
Upvotes: 5
Reputation: 56
You should do something like:
let value_1 = 123456
let value_2 = 123000
let percentage = 100
while (percentage > 0 && value_1 !== value_2) {
value_1 = Math.floor(value_1/10)
value_2 = Math.floor(value_2/10)
if (percentage > 80) percentage -= 10
else if (percentage > 40) percentage -= 20
else percentage = 0
}
console.log(percentage)
Hope this helps
Upvotes: 1