Advertisement
marcgruita

Untitled

Oct 19th, 2022
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.13 KB | None | 0 0
  1. package com.montran.ewallet.core
  2.  
  3. class HashMap<T>(
  4.     private val maxSize: Int,
  5. ) {
  6.    
  7.     private var data = MutableList<T?>(maxSize) { null }
  8.    
  9.     private fun hash(key: String): Int
  10.         = key.mapIndexed { index, char ->
  11.             char.code * nthPrime(index)
  12.         }
  13.         .sum() % maxSize
  14.    
  15.     private fun nthPrime(n: Int): Int {
  16.         var number = 2
  17.         var count = 0
  18.        
  19.         while (count != n) {
  20.             if (number.isPrime()) count++
  21.             number++
  22.         }
  23.         return number - 1
  24.     }
  25.    
  26.     private fun Int.isPrime(): Boolean {
  27.         var div = 2
  28.         while (div * div <= this / 2) {
  29.             if (this % div == 0) {
  30.                 return false
  31.             }
  32.             div += 1
  33.         }
  34.         return true
  35.     }
  36.    
  37.     fun put(key: String, value: T) {
  38.         data[hash(key)] = value
  39.     }
  40.    
  41.     fun at(key: String): T
  42.         = data[hash(key)] ?: throw NullPointerException()
  43. }
  44.  
  45.  
  46. fun main() {
  47.     val map = HashMap<Int>(200)
  48.    
  49.     map.put("abc", 12)
  50.     map.put("acb", 123)
  51.     println(map.at("abc"))
  52.     println(map.at("acb"))
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement