How to resolve the algorithm Hamming numbers step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Hamming numbers step by step in the Scala programming language
Table of Contents
Problem Statement
Hamming numbers are numbers of the form Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Generate the sequence of Hamming numbers, in increasing order. In particular:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Hamming numbers step by step in the Scala programming language
Source code in the scala programming language
class Hamming extends Iterator[BigInt] {
import scala.collection.mutable.Queue
val qs = Seq.fill(3)(new Queue[BigInt])
def enqueue(n: BigInt) = qs zip Seq(2, 3, 5) foreach { case (q, m) => q enqueue n * m }
def next = {
val n = qs map (_.head) min;
qs foreach { q => if (q.head == n) q.dequeue }
enqueue(n)
n
}
def hasNext = true
qs foreach (_ enqueue 1)
}
class Hamming extends Iterator[BigInt] {
import scala.collection.mutable.Queue
val q2 = new Queue[BigInt]
val q3 = new Queue[BigInt]
val q5 = new Queue[BigInt]
def enqueue(n: BigInt) = {
q2 enqueue n * 2
q3 enqueue n * 3
q5 enqueue n * 5
}
def next = {
val n = q2.head min q3.head min q5.head
if (q2.head == n) q2.dequeue
if (q3.head == n) q3.dequeue
if (q5.head == n) q5.dequeue
enqueue(n)
n
}
def hasNext = true
List(q2, q3, q5) foreach (_ enqueue 1)
}
val hamming : Stream[BigInt] = {
def merge(inx : Stream[BigInt], iny : Stream[BigInt]) : Stream[BigInt] = {
if (inx.head < iny.head) inx.head #:: merge(inx.tail, iny) else
if (iny.head < inx.head) iny.head #:: merge(inx, iny.tail) else
merge(inx, iny.tail)
}
1 #:: merge(hamming map (_ * 2), merge(hamming map (_ * 3), hamming map (_ * 5)))
}
def hamming(): Stream[BigInt] = {
def merge(a: Stream[BigInt], b: Stream[BigInt]): Stream[BigInt] = {
if (a.isEmpty) b else {
val av = a.head; val bv = b.head
if (av < bv) av #:: merge(a.tail, b)
else bv #:: merge(a, b.tail) } }
def smult(m:Int, s: Stream[BigInt]): Stream[BigInt] =
(m * s.head) #:: smult(m, s.tail) // equiv to map (m *) s; faster
def u(s: Stream[BigInt], n: Int): Stream[BigInt] = {
lazy val r: Stream[BigInt] = merge(s, smult(n, 1 #:: r))
r }
1 #:: List(5, 3, 2).foldLeft(Stream.empty[BigInt]) { u } }
You may also check:How to resolve the algorithm Damm algorithm step by step in the Modula-3 programming language
You may also check:How to resolve the algorithm Simulate input/Keyboard step by step in the LabVIEW programming language
You may also check:How to resolve the algorithm CRC-32 step by step in the Tcl programming language
You may also check:How to resolve the algorithm Variable declaration reset step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Digital root step by step in the AWK programming language