Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.montran.ewallet.core
- class HashMap<T>(
- private val maxSize: Int,
- ) {
- private var data = MutableList<T?>(maxSize) { null }
- private fun hash(key: String): Int
- = key.mapIndexed { index, char ->
- char.code * nthPrime(index)
- }
- .sum() % maxSize
- private fun nthPrime(n: Int): Int {
- var number = 2
- var count = 0
- while (count != n) {
- if (number.isPrime()) count++
- number++
- }
- return number - 1
- }
- private fun Int.isPrime(): Boolean {
- var div = 2
- while (div * div <= this / 2) {
- if (this % div == 0) {
- return false
- }
- div += 1
- }
- return true
- }
- fun put(key: String, value: T) {
- data[hash(key)] = value
- }
- fun at(key: String): T
- = data[hash(key)] ?: throw NullPointerException()
- }
- fun main() {
- val map = HashMap<Int>(200)
- map.put("abc", 12)
- map.put("acb", 123)
- println(map.at("abc"))
- println(map.at("acb"))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement