How to deal with overlapping streams for reactive extensions? - system.reactive

Suppose I have a series of like this:
X - X - A - B - C - X - X
I am interested in two events:
1-) if A - B - C occurs sequentially.
2-) if B - C occurs sequentially AND if A - B - C does not occur.
Accordingly I will subscribe.
For example if A - B - C occurs I will print only ABC but not BC, whereas if X - B - C occurs then I will print BC. How can I do this ?

If your source is IObservable<char> then try these:
IObservable<string> query1 =
source
.Publish(ss =>
ss
.Zip(ss.Skip(1), (s0, s1) => new { s0, s1 })
.Zip(ss.Skip(2), (s01, s2) => new { s01.s0, s01.s1, s2 }))
.Where(s => s.s0 == 'A' && s.s1 == 'B' & s.s2 == 'C')
.Select(s => String.Join("", s.s0, s.s1, s.s2));
IObservable<string> query2 =
source
.Publish(ss =>
ss
.Zip(ss.Skip(1), (s0, s1) => new { s0, s1 })
.Zip(ss.Skip(2), (s01, s2) => new { s01.s0, s01.s1, s2 }))
.Where(s => s.s0 != 'A' && s.s1 == 'B' & s.s2 == 'C')
.Select(s => String.Join("", s.s1, s.s2));

Related

Tower of Hanoi using Scala Pure function

I am new to functional Programming and I'm trying to implement scala Iterative way of implementing tower of Hanoi. I could solve it using the recursion way but I have difficulty trying to implement it using Iterative method in Scala pure function. The code below is what I have coded so far.
I am using Iterative function since I can simply use it as a stack. So I am trying to avoid using separate functions of implementing it. I have no idea how I can continue from here
/**
* The three pegs of the game. The game starts with all N disks on peg 1 and
* needs to end with all disks on peg 3.
*/
type Peg = 1 | 2 | 3
case class Move(from: Peg, to: Peg):
assert(from != to) // Throws and ends the program if violated.
def towerOfHanoiRecursive(n: Int): Iterator[Move] = {
var a: Iterator[Move] = Iterator()
def helper(n: Int, from: Peg, to: Peg, aux: Peg): Iterator[Move] =
if (n<=0) return a.iterator
helper(n-1, from, aux, to)
a = a ++ Iterator(Move(from,to))
helper(n-1, aux, to , from)
helper(n, 1, 3, 2)
}
def towerOfHanoiIterative(n: Int): Iterator[Move] =
def helper(n: Int, from: Peg, to: Peg, aux: Peg): Iterator[Move] =
Iterator.iterate((List(Problem(n, from, to, aux)), Iterator.empty[Move])) {
case (Problem(0, _, _, _) :: _, _) =>
(List(), Iterator())
case (Problem(1, x, y, _) :: stackTail, _) if (stackTail == List() && x == 1 && y ==3 )=> {
if (stackTail == List() )
( stackTail , Iterator(Move(x,y)))
else if ((stackTail.length %2) == 0)
(stackTail , Iterator(Move(y,x)))
else
(stackTail , Iterator(Move(y,x)))
}
case (Problem(1, x, y, z) :: stackTail, _) =>
if ((stackTail.length %3) == 0)
( stackTail , Iterator(Move(z,x)))
else if ((stackTail.length %3) == 1)
( stackTail , Iterator(Move(z,y)))
else
( stackTail , Iterator(Move(z,y)))
case (Problem(k, f, t, a)::stackTail, _) if (n%2) == 0 => {
if ((stackTail.length %3) ==0)
(List(Problem(k-1, f, t, a))::: List(Problem(k-1, t,f ,a)) ::: stackTail ,Iterator(Move(f,a)))
else if ((stackTail.length % 3) ==1)
(List(Problem(k-1, f, a, t))::: List(Problem(k-1, a,f ,t)) ::: stackTail ,Iterator(Move(f,a)))
else
println("3rd")
(List(Problem(k-1, a, t, f))::: List(Problem(k-1, a,f ,t)) ::: stackTail ,Iterator(Move(a,t)))
}
case (Problem(k, f, t, a)::stackTail, _) if (n %2) == 1 => {
if ((stackTail.length %3) ==0)
(List(Problem(k-1, f, t, a))::: List(Problem(k-1, a,f ,t)) ::: stackTail ,Iterator(Move(f,t)))
else if ((stackTail.length % 3) ==1)
(List(Problem(k-1, f, a, t))::: List(Problem(k-1, f,a ,t)) ::: stackTail ,Iterator(Move(f,a)))
else
(List(Problem(k-1, a, t, f))::: List(Problem(k-1, f,t ,a)) ::: stackTail ,Iterator(Move(a,t)))
}
case (Nil, _) =>
println("nil")
(List(),Iterator())
}.takeWhile { case (p,o) => p.nonEmpty || o.nonEmpty }.flatMap(_._2)
helper(n, 1, 3, 2)

SCALA: Generating a list of Tuple2 objects meeting some criteria

I want to generate a list of Tuple2 objects. Each tuple (a,b) in the list should meeting the conditions:a and b both are perfect squares,(b/30)<a<b
and a>N and b>N ( N can even be a BigInt)
I am trying to write a scala function to generate the List of Tuples meeting the above requirements?
This is my attempt..it works fine for Ints and Longs..But for BigInt there is sqrt problem I am facing..Here is my approach in coding as below:
scala> def genTups(N:Long) ={
| val x = for(s<- 1L to Math.sqrt(N).toLong) yield s*s;
| val y = x.combinations(2).map{ case Vector(a,b) => (a,b)}.toList
| y.filter(t=> (t._1*30/t._2)>=1)
| }
genTups: (N: Long)List[(Long, Long)]
scala> genTups(30)
res32: List[(Long, Long)] = List((1,4), (1,9), (1,16), (1,25), (4,9), (4,16), (4,25), (9,16), (9,25), (16,25))
Improved this using BigInt square-root algorithm as below:
def genTups(N1:BigInt,N2:BigInt) ={
def sqt(n:BigInt):BigInt = {
var a = BigInt(1)
var b = (n>>5)+BigInt(8)
while((b-a) >= 0) {
var mid:BigInt = (a+b)>>1
if(mid*mid-n> 0) b = mid-1
else a = mid+1
}; a-1 }
val x = for(s<- sqt(N1) to sqt(N2)) yield s*s;
val y = x.combinations(2).map{ case Vector(a,b) => (a,b)}.toList
y.filter(t=> (t._1*30/t._2)>=1)
}
I appreciate any help to improve in my algorithm .
You can avoid sqrt in you algorithm by changing the way you calculate x to this:
val x = (BigInt(1) to N).map(x => x*x).takeWhile(_ <= N)
The final function is then:
def genTups(N: BigInt) = {
val x = (BigInt(1) to N).map(x => x*x).takeWhile(_ <= N)
val y = x.combinations(2).map { case Vector(a, b) if (a < b) => (a, b) }.toList
y.filter(t => (t._1 * 30 / t._2) >= 1)
}
You can also re-write this as a single chain of operations like this:
def genTups(N: BigInt) =
(BigInt(1) to N)
.map(x => x * x)
.takeWhile(_ <= N)
.combinations(2)
.map { case Vector(a, b) if a < b => (a, b) }
.filter(t => (t._1 * 30 / t._2) >= 1)
.toList
In a quest for performance, I came up with this recursive version that appears to be significantly faster
def genTups(N1: BigInt, N2: BigInt) = {
def sqt(n: BigInt): BigInt = {
var a = BigInt(1)
var b = (n >> 5) + BigInt(8)
while ((b - a) >= 0) {
var mid: BigInt = (a + b) >> 1
if (mid * mid - n > 0) {
b = mid - 1
} else {
a = mid + 1
}
}
a - 1
}
#tailrec
def loop(a: BigInt, rem: List[BigInt], res: List[(BigInt, BigInt)]): List[(BigInt, BigInt)] =
rem match {
case Nil => res
case head :: tail =>
val a30 = a * 30
val thisRes = rem.takeWhile(_ <= a30).map(b => (a, b))
loop(head, tail, thisRes.reverse ::: res)
}
val squares = (sqt(N1) to sqt(N2)).map(s => s * s).toList
loop(squares.head, squares.tail, Nil).reverse
}
Each recursion of the loop adds all the matching pairs for a given value of a. The result is built in reverse because adding to the front of a long list is much faster than adding to the tail.
Firstly create a function to check if number if perfect square or not.
def squareRootOfPerfectSquare(a: Int): Option[Int] = {
val sqrt = math.sqrt(a)
if (sqrt % 1 == 0)
Some(sqrt.toInt)
else
None
}
Then, create another func that will calculate this list of tuples according to the conditions mentioned above.
def generateTuples(n1:Int,n2:Int)={
for{
b <- 1 to n2;
a <- 1 to n1 if(b>a && squareRootOfPerfectSquare(b).isDefined && squareRootOfPerfectSquare(a).isDefined)
} yield ( (a,b) )
}
Then on calling the function with parameters generateTuples(5,10)
you will get an output as
res0: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,4), (1,9), (4,9))
Hope that helps !!!

generate doubles between a and b

import org.scalacheck._
import org.scalacheck.Prop._
object Doubles extends Properties("Gen Doubles") {
val positiveDouble = Arbitrary.arbitrary[Double] suchThat (_ > 0.0)
val normalize = Arbitrary.arbitrary[Double] map (f => math.abs(f) / Double.MaxValue)
def between(a: Double, b: Double) = normalize map (_ * (b - a) + a)
property("normalize") = forAll(normalize) { f => 0.0 <= f && f <= 1.0 }
property("between") = forAll(positiveDouble, positiveDouble) { (a: Double, b: Double) =>
forAll(between(a, b)) { f =>
a <= f && f <= b
}
}
}
Output via http://scastie.org/13056
+ Gen Doubles.normalize: OK, passed 100 tests.
! Gen Doubles.between: Falsified after 0 passed tests.
> ARG_0: 2.9635128477431505E249
> ARG_1: 1.807071439895287E-167
Where does my math fail?
EDIT solution:
val ascendingTuple = (for {
a <- Arbitrary.arbitrary[Double]
b <- Arbitrary.arbitrary[Double]
} yield(a, b))suchThat({case (a, b) => a < b})
The problem is that you are not enforcing that b should be greater than a, but your test assumes this. When the generated value for b is less than a, you get a number such that b <= f <= a, which fails your test. For a simple fix, try:
forAll(between(a, b)) { f =>
if (a < b) {
a <= f && f <= b
} else {
b <= f && f <= a
}
}

Implementing map for an intensionally-defined set in Scala

type Set = Int => Boolean
/**
* Returns whether all bounded integers within `s` satisfy `p`.
*/
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (contains(s, a) && !p(a)) false
else iter(a + 1)
}
iter(-bound)
}
/**
* Returns whether there exists a bounded integer within `s`
* that satisfies `p`.
*/
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, (x => !p(x)))
/**
* Returns a set transformed by applying `f` to each element of `s`.
*/
def map(s: Set, f: Int => Int): Set = (x => exists(s, (y: Int) => f(y) ==
x))
so for this piece of code. I don't understand function map.
I see its input are 2 arguments, which are set and method f. But the "body" part, I tried so hard but still don't get it. And what is that "y", and why using f(y) == x makes it apply method f to set elemtns?
need some explanation for me.
thank you!
To be succinct:
If you say: val set2 = map(set1, f),
then set2(x) will returns true if and only if there exits y in set1 such as f(y) == x
That's exactly what exists(set1, y => f(y) == x) is checking.
To put it an other way, an integer is in set2 only if you can obtain it by applying f to an element of set1.
We can try to understand this piece of code by applying it backwards.
The map method here would return true for every given x and function f, if x is a result of the function f applied to the elements of the original set.
It is done by checking that if we go over the original map and apply f to every element of this map, at least one of them will be equal to x (that is what the part (x => exists(s, (y: Int) => f(y) == x)) does).
Regarding exists itself, it is a statement that if we go over all elements of the set (using forall method) with a given predicate p, for at least one of the elements this predicate will not be false (this is the part !forall(s, (x => !p(x)))).
And what is that "y"
exists takes a function Int => Boolean as its second argument. This function is (y: Int) => f(y) == x, and y is simply the name we give to its argument, same as x in x => !p(x).
and why using f(y) == x makes it apply method f to set elemtns?
This definition says "x is a member of map(s, f) when exists(s, y => f(y) == x). Now consider a simple case: s is the set {1, 2} represented by a function x => (x == 1) || (x == 2), and f = z => z + 1 over it. Then we have
s2 = map(s, z => z + 1) = x => exists(s, y => y + 1 == x)
by inlining f into definition of map. You can check that:
2 is a member of s2, i.e. s2(2) is exists(s, y => y + 1 == 2) is exists(s, y => y == 1) is true.
0 is not a member of s2, i.e. s2(2) is exists(s, y => y + 1 == 0) is exists(s, y => y == -1) is false.
Thinking a bit more, you should be able to list all members of s2, and then to generalize to any s and f.

Kendall tau distance in Scala

Is this a correct implementation of Kendall tau distance in Scala
def distance[A : Ordering](s: Seq[A], t: Seq[A]): Int = {
assert(s.size == t.size, "Both sequences should be of the same length")
s.combinations(2).zip(t.combinations(2)).count {
case (Seq(s1, s2), Seq(t1, t2)) =>
(s1 > s2 && t1 < t2) || (s1 < s2 && t1 > t2)
}
}
The problem is I do not have enough data to test the algorithm on, only a few examples from Wikipedia. And I do not understand the algorithm well enough to generate my own test data. Most sources are about Kendall tau rank correlation coefficient, which is related but different animal. Maybe I could somehow derive one from the other?
For now let's say that performance is not important.
UPDATE
So, now I have three implementations of Kendall tau distance algorithm. Two of them (distance1 and distance3) give identical results (see bellow). So, which one is correct?
import scala.math.Ordering.Implicits._
val permutations = Random.shuffle((0 until 5).permutations).take(100)
println("s\tt\tDist1\tDist2\tDist3")
permutations.sliding(2).foreach { case Seq(s, t) =>
println(s.mkString(",")+"\t"+t.mkString(",")+"\t"+distance1(s, t)+"\t"+distance2(s, t)+
"\t"+distance3(s, t))
}
def distance1[A : Ordering](s: Seq[A], t: Seq[A]): Int = {
assert(s.size == t.size, "Both sequences should be of the same length")
s.combinations(2).zip(t.combinations(2)).count { case (Seq(s1, s2), Seq(t1, t2)) =>
(s1 > s2 && t1 < t2) || (s1 < s2 && t1 > t2)
}
}
def distance2[A](a: Seq[A], b: Seq[A]): Int = {
val aMap = a.zipWithIndex.toMap // map of a items to their ranks
val bMap = b.zipWithIndex.toMap // map of b items to their ranks
a.combinations(2).count{case Seq(i, j) =>
val a1 = aMap.get(i).get // rank of i in A
val a2 = aMap.get(j).get // rank of j in A
val b1 = bMap.get(i).get // rank of i in B
val b2 = bMap.get(j).get // rank of j in B
a1.compare(a2) != b1.compare(b2)
}
}
def distance3(τ_1: Seq[Int], τ_2: Seq[Int]) =
(0 until τ_1.size).map { i =>
(i+1 until τ_2.size).count { j =>
(τ_1(i) < τ_1(j) && τ_2(i) > τ_2(j)) || (τ_1(i) > τ_1(j) && τ_2(i) < τ_2(j))
}
}.sum
And here are some results:
s t Dist1 Dist2 Dist3
3,0,4,2,1 1,4,3,0,2 6 6 6
1,4,3,0,2 0,4,1,2,3 3 5 3
0,4,1,2,3 4,0,1,3,2 8 2 8
4,0,1,3,2 1,2,0,4,3 4 6 4
1,2,0,4,3 2,3,1,4,0 3 5 3
2,3,1,4,0 1,0,3,2,4 8 6 8
1,0,3,2,4 1,3,2,4,0 7 3 7
1,3,2,4,0 4,3,0,1,2 6 6 6
4,3,0,1,2 1,0,2,4,3 7 7 7
1,0,2,4,3 3,4,1,2,0 8 8 8
3,4,1,2,0 1,4,2,0,3 5 5 5
1,4,2,0,3 1,0,3,4,2 8 4 8
I don't think this is quite right. Here's some quickly written code that emphasizes that what you are comparing is the rank of the items in the sequences (you don't really want to keep those get(n).get calls in your code though). I used compare, too, which I think makes sense:
def tauDistance[A](a: Seq[A], b: Seq[A]) = {
val aMap = a.zipWithIndex.toMap // map of a items to their ranks
val bMap = b.zipWithIndex.toMap // map of b items to their ranks
a.combinations(2).count{case Seq(i, j) =>
val a1 = aMap.get(i).get // rank of i in A
val a2 = aMap.get(j).get // rank of j in A
val b1 = bMap.get(i).get // rank of i in B
val b2 = bMap.get(j).get // rank of j in B
a1.compare(a2) != b1.compare(b2)
}
}
So, the Wikipedia defines K on the ranks of the elements like this:
K(τ_1,τ_2) = |{(i,j): i < j, (τ_1(i) < τ_1(j) && τ_2(i) > τ_2(j)) || (τ_1(i) > τ_1(j) && τ_2(i) < τ_2(j))}|
We can implement this pretty directly in Scala, remembering that the inputs are sequences of ranks, not the items themselves:
def K(τ_1: Seq[Int], τ_2: Seq[Int]) =
(0 until τ_1.size).map{i =>
(i+1 until τ_2.size).count{j =>
(τ_1(i) < τ_1(j) && τ_2(i) > τ_2(j)) || (τ_1(i) > τ_1(j) && τ_2(i) < τ_2(j))
}
}.sum
This is actually a bit preferable to the tauDistance function above, since that function assumes all the items are unique (and so will fail if the sequences have duplicates) while this one works on the ranks directly.
Working with combinatoric functions is hard sometimes, and it's often not enough just to have unit tests that pass.