Skip to content

Commit ea74644

Browse files
alterevitegonSchiele
authored andcommitted
add binary search on kotlin
1 parent f47666f commit ea74644

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
typealias Graph<V> = MutableMap<V, List<V>>
2+
3+
fun <V> Graph<V>.breadthFirstSearch(key: V, isSearched: (V) -> Boolean): Boolean {
4+
val queue: Deque<V> = LinkedList()
5+
this[key]?.let { queue += it }
6+
val searched = HashSet<V>()
7+
while (queue.isNotEmpty()) {
8+
val value = queue.pop()
9+
if (!searched.contains(value))
10+
if (isSearched(value)) {
11+
println("value $value is here!")
12+
return true
13+
} else {
14+
this[value]?.let { queue += it }
15+
searched.add(value)
16+
}
17+
}
18+
return false
19+
}
20+
21+
data class Person(
22+
val name: String,
23+
val isSellerMango: Boolean = false
24+
) {
25+
override fun equals(other: Any?): Boolean =
26+
if (other is Person) other.name == name
27+
else false
28+
29+
30+
override fun hashCode(): Int {
31+
return name.length
32+
}
33+
}
34+
35+
fun main(args: Array<String>) {
36+
37+
val graph: Graph<Person> = HashMap()
38+
39+
(graph as java.util.HashMap<Person, List<Person>>).apply {
40+
put(Person("John"), listOf(Person("Sergey"), Person("Viktoria")))
41+
put(Person("Viktoria"), listOf(Person("Sergey"), Person("Phara")))
42+
put(Person("Phara"), listOf(Person("Sergey"), Person("Thrall"), Person("Xul"), Person("Juncart", true)))
43+
}
44+
45+
println(
46+
graph.breadthFirstSearch(Person("John"), Person::isSellerMango)
47+
)
48+
49+
50+
}

0 commit comments

Comments
 (0)