Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data class Ip(val node1: Int, val node2: Int, val node3: Int, val node4: Int) : Comparable<Ip> {
- constructor(ipStr: String) {
- val nodesStr = ipStr.split('.')
- if (nodesStr.count() != 4)
- throw InvalidOperationException("Incorrect ip string format")
- val nodes = nodesStr.map { it.toIntOrNull() }.filter { it != null }
- if (nodes.count() != 4)
- throw InvalidOperationException("Some nodes have incorrect format")
- if (!nodes.all { it >= 0 && it <= 255 })
- throw InvalidOperationException("Some nodes great than 255 or less than 0")
- node1 = nodes[0]
- node2 = nodes[1]
- node3 = nodes[2]
- node4 = nodes[3]
- }
- override operator fun compareTo(other: Ip): Int {
- var compare = this.node1 - other.node1
- if (compare != 0) return compare.sign()
- compare = this.node2 - other.node2
- if (compare != 0) return compare.sign()
- compare = this.node3 - other.node3
- if (compare != 0) return compare.sign()
- compare = this.node3 - other.node3
- return compare.sign()
- }
- override fun toString(): String {
- return "${node1}.${node2}.${node3}.${node4}"
- }
- }
- fun main(args: Array<String>) {
- if (args.count() < 2) {
- println("Not enought arguments")
- return
- }
- try {
- args.map { Ip(it) }.sortedBy { it }.forEach {
- println(it)
- }
- }
- catch(e: InvalidOperationException) {
- println(e.message)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement