Recursive function in Kotlin - kotlin

I'm trying to solve the problem "is Subsequence"
https://leetcode.com/problems/is-subsequence/
in kotlin. I decided to use recursion. The is the solution:
const val first = "abc"
const val second = "ahbgdc"
fun isSubsequence(first: String, second :String): Boolean {
if(first.isEmpty())
return true
if(second.isEmpty())
return false
return subCheck((first.length).minus(1),(second.length).minus(1))
}
fun subCheck(s: Int, t: Int): Boolean {
println("$s $t")
if(s == -1) return true
if(t == -1) return false
if(first[s] == second[t]) subCheck(s.minus(1),t.minus(1))
return subCheck(s,t.minus(1))
}
fun main() {
println(isSubsequence(first, second))
}
I've been struggling to find where the problem is since it always returns false with this input and when I tried to debug it I found that the value of s and t reach -1 and -1. however instead of returning true, the values of s and t change to 0 and -1.
this is the the output of the println statement:
1 4
1 3
1 2
0 1
0 0
-1 -1
0 -1
1 1
1 0
1 -1
2 4
2 3
2 2
2 1
2 0
2 -1
false

Related

Get index of each root on level wise in tree data structure

Hey I am working on tree data structure. I want to know can we get index of each node in level wise. I below diagram represent how I want the value + index. Level A or B represent node value and index value represent index value
Node
| | |
Level A -> 1 2 3
index value-> 0 1 2
| | | | | |
| | | | | |
Leve B-> 4 5 6 7 8 9
index value-> 0 1 2 3 4 5
....// more level
How can we achieved index in each level wise. I am adding my logic how I am adding value in each level wise. Could you someone suggest how can I achieve this?
var baseNode: LevelIndex = LevelIndex()
var defaultId = "1234"
fun main() {
val list = getUnSortedDataListForLevel()
val tempHashMap: MutableMap<String, LevelIndex> = mutableMapOf()
list.forEach { levelClass ->
levelClass.levelA?.let { levelA ->
val levelOneTempHashMapNode = tempHashMap["level_a${levelA}"]
if (levelOneTempHashMapNode != null) {
if (defaultId == levelClass.id && levelOneTempHashMapNode is LevelOne) {
levelOneTempHashMapNode.defaultValue = true
}
return#let
}
val tempNode = LevelOne().apply {
value = levelA
if (defaultId == levelClass.id) {
defaultValue = true
}
}
baseNode.children.add(tempNode)
tempHashMap["level_a${levelA}"] = tempNode
}
levelClass.levelB?.let { levelB ->
val levelTwoTempHashMapNode = tempHashMap["level_a${levelClass.levelA}_level_b${levelB}"]
if (levelTwoTempHashMapNode != null) {
if (defaultId == levelClass.id && levelOneTempHashMapNode is LevelTwo) {
levelTwoTempHashMapNode.defaultValue = true
}
return#let
}
val tempNode = LevelTwo().apply {
value = levelB
if (defaultId == levelClass.id) {
defaultValue = true
}
}
val parent =
tempHashMap["level_a${levelClass.levelA}"] ?: baseNode
parent.children.add(tempNode)
tempHashMap["level_a${levelClass.levelA}_level_b${levelB}"] =
tempNode
}
levelClass.levelC?.let { levelC ->
val tempNode = LevelThree().apply {
value = levelC
if (defaultId == levelClass.id) {
defaultValue = true
}
}
val parent =
tempHashMap["level_a${levelClass.levelA}_level_b${levelClass.levelB}"]
?: baseNode
parent.children.add(tempNode)
}
}
}
open class LevelIndex(
var value: String? = null,
var children: MutableList<LevelIndex> = arrayListOf()
)
class LevelOne : LevelIndex() {
var defaultValue: Boolean? = false
}
class LevelTwo : LevelIndex() {
var defaultValue: Boolean? = false
}
class LevelThree : LevelIndex() {
var defaultValue: Boolean = false
}
UPDATE
I want index value by root level because, I have one id, I want to match that combination with that id, if that value is present then I am storing that value b true, and need to find that index value.
Node
| | |
Level A -> 1 2 3
index value-> 0 1 2
default value-> false true false
| | | | | |
| | | | | |
Leve B-> 4 5 6 7 8 9
index value-> 0 1 2 3 4 5
default value->false false true false false false
....// more level
So, Level A I'll get index 1.
For Level B I'll get index 2
I'd create a list to put the nodes at each level in order. You can recursively collect them from your tree.
val nodesByLevel = List(3) { mutableListOf<LevelIndex>() }
fun collectNodes(parent: LevelIndex) {
for (child in parent.children) {
val listIndex = when (child) {
is LevelOne -> 0
is LevelTwo -> 1
is LevelThree -> 2
// I made LevelIndex a sealed class. Otherwise you would need an else branch here.
}
nodesByLevel[listIndex] += child
collectNodes(child)
}
}
collectNodes(baseNode)
Now nodesByLevel contains three lists containing all the nodes in each layer in order.
If you just need the String values, you could change that mutableList to use a String type and use += child.value ?: "" instead, although I would make value non-nullable (so you don't need ?: ""), because what use is a node with no value?
Edit
I would move defaultValue up into the parent class so you don't have to cast the nodes to be able to read it. And I'm going to treat is as non-nullable.
sealed class LevelIndex(
var value: String = "",
val children: MutableList<LevelIndex> = arrayListOf()
var isDefault: Boolean = false
)
Then if you want to do something with the items based on their indices:
for ((layerNumber, layerList) in nodesByLevel.withIndex()) {
for((nodeIndexInLayer, node) in layerList) {
val selectedIndexForThisLayer = TODO() //with layerNumber
node.isDefault = nodeIndexInLayer == selectedIndexForThisLayer
}
}

problems with index of array

I'm writing a function that allows you to remove certain numbers from an int arraylist.
My code
for (i in 1 until 4) {
divider = setDivider(i)
for(index in 0 until numbers.size){
if(index <= numbers.size){
if (numbers[index] % divider == 0 && !isDone) {
numbers.removeAt(index)
}
}else{
isDone = true
}
}
if(isDone)
break
}
the function to set the divider
fun setDivider(divider: Int): Int {
when (divider) {
1 -> return 2
2 -> return 3
3 -> return 5
4 -> return 7
}
return 8
}
I do not know why the ide is giving me the error Index 9 out of bounds for length 9.
Author explained in the comments that the goal is to remove all numbers that are divisible by 2, 3, 5 and 7.
It can be achieved much easier by utilizing ready to use functions from stdlib:
val dividers = listOf(2, 3, 5, 7)
numbers.removeAll { num ->
dividers.any { num % it == 0 }
}
It removes elements that satisfy the provided condition (is divisible) for any of provided dividers.
Also, it is often cleaner to not modify a collection in-place, but to create an entirely new collection:
val numbers2 = numbers.filterNot { num ->
dividers.any { num % it == 0 }
}

Determine whether number contains different digits

For a given number n, determine whether it contains different digits.
For example, 54 and 323 consist of different digits and 111 and 0 are the same.
you could try this
fun areDigitsDistinct(n:Int) = "$n".toCharArray().distinct().count() > 1
Try this:
fun hasDifferent(number: Int): Boolean {
val stringNumber = number.toString()
if (stringNumber.length == 1) return false
for (char in stringNumber) {
if (char != stringNumber[0]) return true
}
return false
}
Doesn't require convertion to String, doesn't require processing of all digits:
fun sameDigits(number: Int): Boolean {
val veryLastDigit = number % 10
var x = number / 10
while (x > 0) {
val lastDigit = x % 10
if (lastDigit != veryLastDigit) return false
x /= 10
}
return true
}
If you need to make it work with negative numbers too, change part before while-loop to this:
val _number = number.absoluteValue
val veryLastDigit = _number % 10
var x = _number / 10

How to write Kotlin code to store all odd numbers starting at 7 till 101 and print sum of them?

How to write Kotlin code to store all odd numbers starting at 7 till 101 and print the sum of them?
My code goes like this:
var sum:Int = 0
var num:Int? = null
for(num in 7..101 )
if(num % 2 != 0)
print("$num ")
var result = sum + num
num++
println("$result")
Simply filter the range 7..101 and sum the items:
val total = (7..101).filter { it % 2 == 1 }.sum()
println(total)
Or use sumBy():
val total = (7..101).sumBy { if (it % 2 == 1) it else 0}
println(total)
Or first create a list of all the odd numbers and then get the sum:
val list = (7..101).filter { it % 2 == 1 }
val total = list.sum()
println(total)
If you need to store them, just create a MutableList and add the odd numbers during the forEach execution
var oddNumbersTotal = 0
(7..101).forEach { n ->
if (n % 2 != 0) {
oddNumbersTotal += n
}
}
println(oddNumbersTotal)
You can also try this:
val array = IntArray(48){2*it+1}
print(array.sum())

how can i use return# with if expression in kotlin?

What should I use instead of the whats_there parameter so the value of x will be 0?
val x =
if (true) {
for (i in 1..5)
if (i == 4)
return#whats_there 0
1
}
else 2
val x = if (ok) run {
for (i in 1..5) {
if (i == someValue)
return#run 10
}
5
} else 2
or
val x = if (ok) {
if (someValue in 1..5) 10 else 5
} else 2
Using a return like that is hard to read and prone to error.  This example is probably too simplified to show your real problem, but it looks like you could use any(), e.g.:
val x =
if (true) {
if ((1..5).any{ it == 4 })
0
else
1
} else
2
That probably expresses your intent better than a loop would.
You might find it even clearer to re-order the cases, so you can use a when:
val x = when {
!true -> 2
(1..5).any{ it == 4 } -> 0
else -> 1
}
in order to solve my problem i used #IR42 first solution, but i had to use it a bit differently:
val x = run {
if (ok){
for (i in 1..5)
if (i == someValue)
return#run 10
5
}
else 2
}