I have the following algorithm where I pass in an array, I count how many of each number is in the array. Then i need to return a result based on the number of times each number appears in the array. The results don't change so I created a look up table which can be found in my scoreResults
object below:
const scoreResults = {
1: {
1:100
3:1000
},
2: {
3: 200
},
3: {
3:300
},
4: {
3:400
},
5: {
3:500
1:50
},
6: {
3:600
},
}
// example dice [2,3,6,6,6]
function score(dice) {
[...]
return getResult(mapping); // mapping = {2:1, 3:1, 6:3}
}
function getResult(object){
for (const key in object){
[CODE I CANNOT FIGURE OUT]
}
}
For the part I cannot figure out I would like to do the following:
I would now like to check each key in my mapping
object. For example let's take key value pair 6:3
in my mapping
object. If key 6
is in my scoreResults
object (which it is) check the value
of key 6 in my mapping object (which is 3) if it's 3 then check if there is a key 3 here , within the 6 key: 6: {3:600},
return 600 (the value) if not, return nothing.
Another example: For the key value pair 2:1
in my mapping
object I want to see if key 2
is in my scoreResults
object (which it is) check what the value
of key 2
in my mapping object is which is 1
, there is no 1
in value of key 2
in my scoreResults
so return nothing.
Basically I am trying to resolve this algorithm: https://www.codewars.com/kata/5270d0d18625160ada0000e4/train/javascript
Let me know if you need additional clarification
Here is your solution. You can create array from keys of an object with Object.keys. Just like i did in here also,you can use a parameter instead of mapping object which i pre-defined.
const scoreResults = {
1: {
1:100,
3:1000
},
2: {
3: 200
},
3: {
3:300
},
4: {
3:400
},
5: {
3:500,
1:50
},
6: {
3:600
},
}
let mapping = {2:1, 3:1, 6:3}
function getResult(){
let result;
const keys = Object.keys(mapping);
keys.map(key => {
if(scoreResults[key][key]) {
result = scoreResults[key][key];
}
})
return result;
}
To make it work for any scoreResults and number of dices you could do something like this:
function getResult(mapping) {
let res = 0
for (let key of Object.keys(mapping)) {
if (!scoreResults[key])
continue
let count = mapping[key]
let test = count
while (count > 0 && test > 0) {
if (scoreResults[key][test]) {
let amount = Math.floor(count / test)
res += amount * scoreResults[key][test]
count -= amount * test
test = count
} else {
test--
}
}
}
return res
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.