Last active
August 29, 2015 14:22
-
-
Save duanebester/2878104c197ed90470e8 to your computer and use it in GitHub Desktop.
Merge Enumerations In Scala Worksheet
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
import java.util.Enumeration | |
class Merge(a:Enumeration[Integer], b:Enumeration[Integer]) extends Enumeration[Integer] | |
{ | |
/** | |
* Checks to see if either Enumeration has any elements | |
* @return true if either input Enumeration has an element | |
* false if both Enumerations have no elements | |
*/ | |
override def hasMoreElements: Boolean = { | |
(tempA, tempB) match { | |
case (None, None) => false | |
case (_, _) => true | |
} | |
} | |
/** | |
* Looks through the Enumerations for an ordered next element | |
* @return The next element in the Enumerations according to size | |
* @throws NoSuchElementException if called while no elements exist | |
*/ | |
override def nextElement(): Integer = { | |
if (this.hasMoreElements) | |
{ | |
val next:Integer = { | |
(tempA, tempB) match { | |
case (Some(aCurrent), Some(bCurrent)) => { | |
if(aCurrent < bCurrent) | |
{ | |
tempA = getNextA | |
aCurrent | |
} | |
else | |
{ | |
tempB = getNextB | |
bCurrent | |
} | |
} | |
case (Some(aCurrent), None) => { | |
tempA = getNextA | |
aCurrent | |
} | |
case (None, Some(bCurrent)) => { | |
tempB = getNextB | |
bCurrent | |
} | |
case (None, None) => { | |
throw new NoSuchElementException | |
} | |
} | |
} | |
next | |
} | |
else | |
{ | |
throw new NoSuchElementException | |
} | |
} | |
def getNextA:Option[Integer] = if(a.hasMoreElements) Some(a.nextElement()) else None | |
def getNextB:Option[Integer] = if(b.hasMoreElements) Some(b.nextElement()) else None | |
var tempA:Option[Integer] = getNextA | |
var tempB:Option[Integer] = getNextB | |
} | |
import java.util.ArrayList | |
val a = new ArrayList[Integer] | |
val b = new ArrayList[Integer] | |
a.add(1) | |
a.add(3) | |
a.add(5) | |
a.add(7) | |
b.add(1) | |
b.add(2) | |
b.add(4) | |
b.add(6) | |
b.add(9) | |
import java.util.Collections | |
val enA:Enumeration[Integer] = Collections.enumeration(a) | |
val enB:Enumeration[Integer] = Collections.enumeration(b) | |
val merge = new Merge(enA, enB) | |
// Outputs in sorted order | |
while(merge.hasMoreElements) | |
{ | |
println(merge.nextElement()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment