Created
February 7, 2020 19:36
-
-
Save Exey/d63ee3a2595128d85938b139de238c52 to your computer and use it in GitHub Desktop.
Most Frequent Number Task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Utils for bit operations | |
enum Bit { | |
case zero, one | |
func asInt() -> Int { self == .one ? 1 : 0} | |
} | |
// to bytes(UInt8) | |
func bitsToBytes(bits: [Bit]) -> [UInt8] { | |
let numBits = bits.count | |
let numBytes = (numBits + 7)/8 | |
var bytes = [UInt8](repeating: 0, count: numBytes) | |
for (index, bit) in bits.enumerated() { | |
if bit == .one { | |
bytes[index / 8] += UInt8(1 << (7 - index % 8)) | |
} | |
} | |
return bytes | |
} | |
// to bits | |
extension BinaryInteger { | |
var bits: Array<Bit> { | |
var arr = [Bit](repeatElement(.zero, count: self.bitWidth)) | |
var n = self | |
for i in 1...self.bitWidth { | |
if n & 1 == 1 { | |
arr[self.bitWidth-i] = .one | |
} | |
n >>= 1 | |
} | |
return arr | |
} | |
} | |
// Test data, generate numOfElements (most frequent integer is N) | |
let N = -1020 // Most frequent number | |
let numOfElements = 1001 // use odd numbers | |
var ints = [Int]() | |
for i in 1...numOfElements { | |
i % 2 == 0 ? ints.append(Int.random(in: Int.min...Int.max)) : ints.append(N) | |
} | |
print("\(N) count \(ints.filter { $0 == N }.count)/\(numOfElements)") | |
// Solution for most frequent(50%+) number | |
var bit64Counter = [Int](repeatElement(0, count: 64)) // for 64-bit int | |
for i in ints { | |
let bits = i.bits | |
bit64Counter = zip(bit64Counter, bits).map { $0.0 + $0.1.asInt() } | |
} | |
let bitsOfMostNum:[Bit] = bit64Counter.map { $0 > (Int(numOfElements/2)) ? .one : .zero } | |
let bytesOfMostNum:[UInt8] = bitsToBytes(bits: bitsOfMostNum) | |
let mostNum = UnsafeRawPointer(bytesOfMostNum).assumingMemoryBound(to: Int.self).pointee.bigEndian | |
print("Most frequent number \(mostNum)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment