Nat Strangerweather
07/14/2022, 1:12 PMfun getWordValue() {
val workingArray = repository.arr.distinct()
val list = mutableListOf(0)
word.value!!.forEach { c ->
workingArray.forEach {
if (it.name.contains(c)) {
when (c) {
word.value!![0] -> list.add(it.value)
word.value!![1] -> list.add(it.value)
word.value!![2] -> list.add(it.value)
else -> list.add((it.value * 2))
}
}
}
}
wordValue.value = list.sum()
saveWordValue(wordValue.value!!)
}
I'd be grateful for some help, thanks!Sam
07/14/2022, 1:16 PMrepository
, word
and wordValue
are.Joffrey
07/14/2022, 1:16 PMSam
07/14/2022, 1:17 PMNat Strangerweather
07/14/2022, 1:18 PMdistinct
in my workingArray
is that some of the scrabble letters are repeated several times. Each letter has a name and a value.Sam
07/14/2022, 1:32 PMword.value!!.forEach { c ->
to
word.value!!.forEachIndexed { i, c ->
Where i
will give you the position of the character in the word.Giorgos Makris
07/14/2022, 1:48 PMJoffrey
07/14/2022, 1:51 PMGiven a character and its index in the word, can you find its value?Actually this would be easy if instead of converting the letters array by just using
distinct()
you used a Map<Char, Int>
from letter to value:
val lettersToValues = repository.arr.associate { it.name to it.value }
Nat Strangerweather
07/14/2022, 2:19 PMNolan
07/15/2022, 1:58 PMwhen
statement will always hit the first condition in the scenario you described because it's comparing the values. So if your word is "EXCEPT", the first "E" and the fourth "E" will match word.value!![0]
because that evaluates to "E".Nat Strangerweather
07/15/2022, 8:23 PMwhen
statement in order to make my code less awkward, and using the suggestions that were made above. But it's good to know why this did not work in the first place. 😊 Here is what the code looks like now:
fun getWordValue() {
val list = mutableListOf(0)
val lettersToValues = repository.arr.associate { it.name to it.value }
word.value!!.forEachIndexed() { i, c: Char ->
if (i in 0..2) {
list.add(lettersToValues.getValue(c.toString()))
} else {
list.add(lettersToValues.getValue(c.toString()) * 2)
}
}
wordValue.value = list.sum()
saveWordValue(wordValue.value!!)
}
Joffrey
07/15/2022, 9:21 PMGiorgos Makris
07/15/2022, 10:30 PMNat Strangerweather
08/02/2022, 1:28 PMfun getWordValue() {
val lettersToValues = repository.arr.associate { it.name to it.value }
word.value!!.forEachIndexed { i, c: Char ->
if (i in 0..2) {
lettersToValues.getValue(c.toString())
} else {
lettersToValues.getValue(c.toString()) * 2
}
wordValue.value = c.toString().sumOf { i }
}
}
Sam
08/02/2022, 1:32 PMlettersToValues.getValue(…)
but you don’t seem to do anything with the result. In an earlier version of your code you were adding it to a list, I think.c.toString().sumOf { i }
also looks odd, and probably doesn’t do what you want it to.Nat Strangerweather
08/02/2022, 1:33 PMSam
08/02/2022, 1:33 PMNat Strangerweather
08/02/2022, 1:33 PMJoffrey
08/02/2022, 6:14 PMfold
which is a functional way of doing it.