Tree as android library.

This commit is contained in:
2020-01-08 13:24:24 +01:00
parent ce0ff9b30f
commit 97b3502812
47 changed files with 1166 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
package com.github.adriankuta.datastructure.tree
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.github.adriankuta.datastructure.tree.test", appContext.packageName)
}
}

View File

@@ -0,0 +1,2 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.adriankuta.datastructure.tree" />

View File

@@ -0,0 +1,67 @@
package com.github.adriankuta.datastructure.tree
class TreeNode<T>(val value: T) {
private var parent: TreeNode<T>? = null
private val children = mutableListOf<TreeNode<T>>()
fun addChild(child: TreeNode<T>) {
child.parent = this
children += child
}
fun removeChild(child: TreeNode<T>): Boolean {
if (children.isEmpty()) {
return false
}
val nestedChildRemoved = children.map {
it.removeChild(child)
}.reduce { acc, b -> acc or b }
return children.remove(child) or nestedChildRemoved
}
fun getParent(): TreeNode<T>? = parent
fun getChildren(): List<TreeNode<T>> = children
fun size(): Int {
if (children.isEmpty())
return 0
return children.size +
children.sumBy { it.size() }
}
fun depth(): Int {
val childrenMaxDepth = children.map { it.depth() }.max() ?: 0
return childrenMaxDepth + 1
}
fun allItems(): List<T> {
return children.map { value }
}
override fun toString(): String {
val stringBuilder = StringBuilder()
print(stringBuilder, "", "")
return stringBuilder.toString()
}
private fun print(stringBuilder: StringBuilder, prefix: String, childrenPrefix: String) {
stringBuilder.append(prefix)
stringBuilder.append(value)
stringBuilder.append('\n')
val childIterator = children.iterator()
while (childIterator.hasNext()) {
val node = childIterator.next()
if(childIterator.hasNext()) {
node.print(stringBuilder, "$childrenPrefix├── ", "$childrenPrefix")
} else {
node.print(stringBuilder, "$childrenPrefix└── ", "$childrenPrefix ")
}
}
}
}

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">Tree Data Structure</string>
</resources>

View File

@@ -0,0 +1,17 @@
package com.github.adriankuta.datastructure.tree
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}