Advertisement
MrModest

IpSort

Aug 31st, 2019
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.65 KB | None | 0 0
  1. data class Ip(val node1: Int, val node2: Int, val node3: Int, val node4: Int) : Comparable<Ip> {
  2.     constructor(ipStr: String) {
  3.         val nodesStr = ipStr.split('.')
  4.  
  5.         if (nodesStr.count() != 4)
  6.             throw InvalidOperationException("Incorrect ip string format")
  7.            
  8.         val nodes = nodesStr.map { it.toIntOrNull() }.filter { it != null }
  9.        
  10.         if (nodes.count() != 4)
  11.             throw InvalidOperationException("Some nodes have incorrect format")
  12.            
  13.         if (!nodes.all { it >= 0 && it <= 255 })
  14.             throw InvalidOperationException("Some nodes great than 255 or less than 0")
  15.            
  16.         node1 = nodes[0]
  17.         node2 = nodes[1]
  18.         node3 = nodes[2]
  19.         node4 = nodes[3]
  20.     }
  21.    
  22.     override operator fun compareTo(other: Ip): Int {
  23.         var compare = this.node1 - other.node1
  24.         if (compare != 0) return compare.sign()
  25.            
  26.         compare = this.node2 - other.node2
  27.         if (compare != 0) return compare.sign()
  28.                
  29.         compare = this.node3 - other.node3
  30.         if (compare != 0) return compare.sign()
  31.                
  32.         compare = this.node3 - other.node3
  33.         return compare.sign()
  34.     }
  35.    
  36.     override fun toString(): String {
  37.         return "${node1}.${node2}.${node3}.${node4}"
  38.     }
  39. }
  40.  
  41. fun main(args: Array<String>) {
  42.     if (args.count() < 2) {
  43.         println("Not enought arguments")
  44.         return
  45.     }
  46.    
  47.     try {
  48.         args.map { Ip(it) }.sortedBy { it }.forEach {
  49.             println(it)
  50.         }
  51.     }
  52.     catch(e: InvalidOperationException) {
  53.         println(e.message)
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement