What is a BitVector and how to use it as return in Breeze Scala? - scala

I am doing a comparison between two BreezeDenseVectors with the following way a :< b and what i get as a return is a BitVector.
I haven't worked again with this and everything i read about it, was not helpful enough.
Can anyone explain to me how they work?
Additionally, by printing the output, i get: {0, 1, 2, 3, 4 }. What is this supposed to mean?

You can check BitVectorTest.scala for more detail usage.
Basically, a :< b gives you a BitVector, which indicates which elements in a smaller than the ones in b.
For example val a = DenseVector[Int](4, 9, 3); val b = DenseVector[Int](8, 2, 5); a :< b will gives you BitVector(0, 2), it means that a(0) < b(0) and a(2) < b(2), which is correct.

Related

scala array.product function in 2d array

I have 2 d array:
val arr =Array(Array(2,1),Array(3,1),Array(4,1))
I should multiply all inner 1st elements and sum all inner 2nd elements to get as result:
Array(24,3)
I`m looking a way to use map there, something like :
arr.map(a=>Array(a(1stElemnt).product , a(2ndElemnt).sum ))
Any suggestion
Regards.
Following works but note that it is not safe, it throws exception if arr contains element/s that does not have exact 2 elements. You should add additional missing cases in pattern match as per your use case
val result = arr.fold(Array(1, 0)) {
case (Array(x1, x2), Array(y1, y2)) => Array(x1 * y1, x2 + y2)
}
Update
As #Luis suggested, if you make your original Array[Array] to Array[Tuple], another implementation could look like this
val arr = Array((2, 1), (3, 1), (4, 1))
val (prdArr, sumArr) = arr.unzip
val result = (prdArr.product, sumArr.sum)
println(result) // (24, 3)

How can I generate a list of n unique elements picked from a set?

How to generate a list of n unique values (Gen[List[T]]) from a set of values (not generators) using ScalaCheck? This post uses Gen[T]* instead of a set of values, and I can't seem to rewrite it to make it work.
EDIT
At #Jubobs' request I now shamefully display what I have tried so far, revealing my utter novice status at using ScalaCheck :-)
I simply tried to replace gs: Gen[T] repeated parameter to a Set in what #Eric wrote as a solution here:
def permute[T](n: Int, gs: Set[T]): Gen[Seq[T]] = {
val perm = Random.shuffle(gs.toList)
for {
is <- Gen.pick(n, 1 until gs.size)
xs <- Gen.sequence[List[T], T](is.toList.map(perm(_)))
} yield xs
}
but is.toList.map(perm(_)) got underlined with red, with IntelliJ IDEA telling me that "You should read ScalaCheck API first before blind (although intuitive) trial and error", or maybe "Type mismatch, expected: Traversable[Gen[T]], actual List[T]", I can't remember.
I also tried several other ways, most of which I find ridiculous (and thus not worthy of posting) in hindsight, with the most naive being the using of #Eric's (otherwise useful and neat) solution as-is:
val g = for (i1 <- Gen.choose(0, myList1.length - 1);
i2 <- Gen.choose(0, myList2.length - 1))
yield new MyObject(myList1(i1), myList2(i2))
val pleaseNoDuplicatesPlease = permute(4, g, g, g, g, g)
After some testing I saw that pleaseNoDuplicatesPlease in fact contained duplicates, at which point I weighed my options of having to read through ScalaCheck API and understand a whole lot more than I do now (which will inevitably, and gradually come), or posting my question at StackOverflow (after carefully searching whether similar questions exist).
Gen.pick is right up your alley:
scala> import org.scalacheck.Gen
import org.scalacheck.Gen
scala> val set = Set(1,2,3,4,5,6)
set: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)
scala> val myGen = Gen.pick(5, set).map { _.toList }
myGen: org.scalacheck.Gen[scala.collection.immutable.List[Int]] = org.scalacheck.Gen$$anon$3#78693eee
scala> myGen.sample
res0: Option[scala.collection.immutable.List[Int]] = Some(List(5, 6, 2, 3, 4))
scala> myGen.sample
res1: Option[scala.collection.immutable.List[Int] = Some(List(1, 6, 2, 3, 4))

Breakdown of reduce function

I currently have:
x.collect()
# Result: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val a = x.reduce((x,y) => x+1)
# a: Int = 6
val b = x.reduce((x,y) => y + 1)
# b: Int = 12
I have tried to follow what has been said here (http://www.python-course.eu/lambda.php) but still don't quite understand what the individual operations are that lead to these answers.
Could anyone please explain the steps being taken here?
Thank you.
The reason is that the function (x, y) => x + 1 is not associative. reduce requires an associative function. This is necessary to avoid indeterminacy when combining results across different partitions.
You can think of the reduce() method as grabbing two elements from the collection, applying them to a function that results in a new element, and putting that new element back in the collection, replacing the two it grabbed. This is done repeatedly until there is only one element left. In other words, that previous result is going to get re-grabbed until there are no more previous results.
So you can see where (x,y) => x+1 results in a new value (x+1) which would be different from (x,y) => y+1. Cascade that difference through all the iterations and ...

Scala How to get sublist by index

I have a List(1 ,2 ,3 ,4 ,5) and trying to get a sublist: List(3, 4) from it by the following way:
List(1 ,2 ,3 ,4 ,5).slice(this.size - 3 , this.size - 1 )
But I got an error
error: value size is not a member of object
How can I use "this" parameter in Scala just like in Java. Are there other ways to achieve the goal. Thank you so much.
You should first declare the list, and then refer to the list using its name list, not this:
val list = List(1 ,2 ,3 ,4 ,5)
list.slice(list.size -3, list.size -1)
If you really want to do this in one line, then use reverse, but it's not very efficient:
List(1 ,2 ,3 ,4 ,5).reverse.slice(1, 3).reverse
By the way, that code wouldn't be valid in Java either. this refers to the enclosing object, not to the list.
If you want last 3 or n elements, you can use takeRight(3) or takeRight(n).
Edit based on the question edit:
If you need to not take first f and last l elements then
List(1,2,3,....n).drop(f).dropRight(l)
For your case it will be List(1,2,3,4,5).drop(2).dropRight(1)
The problem is that the word this is not pointing your List, if you want to take some parameter in the middle of the List use take and takeRigth please read the Scala Docs at the end is a link
val my_lst = List(1 ,2 ,3 ,4 ,5)
my_lst.takeRight(3).take(2)
my_lst: List[Int] = List(1, 2, 3, 4, 5)
res0: List[Int] = List(3, 4)
first takeRight with the index counting on right my_lst.size - thepositions, so you must write thepositions and then how many elements you want in your new subList
Here is a explanations of how work the methods in scala List
from Scala Help Doc
def slice(from: Int, until: Int): List[A]
returns
a list containing the elements greater than or equal to index from extending up to (but not including) index until of this list.
Definition Classes
List → LinearSeqOptimized → IterableLike → TraversableLike → GenTraversableLike Example:
// Given a list
val letters = List('a','b','c','d','e')
// slice returns all elements beginning at index from and afterwards,
// up until index until (excluding index until.)
letters.slice(1,3) // Returns List('b','c')
in you case use length or size
scala> val my_lst = List(1 ,2 ,3 ,4 ,5)
my_lst: List[Int] = List(1, 2, 3, 4, 5)
scala> my_lst.slice(my_lst.length-3,my_lst.length)
res0: List[Int] = List(3, 4, 5)
but really scala List class has a lot of functions that can fit you. In your case if you want the last 3 elemments use takeRight
def takeRight(n: Int): List[A]
Selects last n elements.
n
the number of elements to take returns
a list consisting only of the last n elements of this list, or else the whole list, if it has less than n elements.
Definition Classes
List → IterableLike
scala> my_lst.takeRight(3)
res2: List[Int] = List(3, 4, 5)
Take a look at the Scala Docs
You have a List(1, 2, 3, 4, 5)
1) Is that a Function or Object or a Class?
2) You want to use return values from List( x , x , 3 , 4 , x )
3) you need to use size outside of the parentheses to return the value from your new List function...
4) create a function to complete this step then return it to a variable...
5) when you fire the function List() use variables with List( A , B , C , D , E )
6) all objects must be completely declared before use. for example, How can you use a basketball without air inside? or How can you use a football without being covered in pigskin? or How can you use a computer without a CPU? all components of objects must be completely declared and working properly in programming!
7) All data, functions, objects inside your List() function must be working properly or ... functioning . . .
8) You said "In general I also want to get some elements in the middle" ..
9) As a veteran programmer... You have to know exactly where the elements are in your List() function
10) Also from the start, before all these functions you wish to "use" you must load the classes, that is filled with all the functions you use, at the head of your program.
11) you cannot use a function the same way you use an object or a class!
12) Lastly, you just want to be creative when the programming language sets the rules or boundaries ...Scala is not Java ...
Does this help? with "error: value size is not a member of object"

Reading the syntax off of this listing at scala-lang

Just learning some basic stuff here.
It appears the count method for Vector will be useful to me for an exercise I'm working on, but from reading its entry at scala-lang I'm having a hard time understanding exactly how to use it, syntactically speaking.
Here's what the entry says:
count(p: (A) => Boolean): Int
I think that's supposed to be telling me the syntax to use when calling the method.
It tells me that "p" is the predicate to be satisfied. Okay, I know what a predicate is in the abstact. What does a predicate look like in Scala though?
Then there's a colon. Do I type that? Or is this meta-linguistic notation of some kind?
Then there's a rocket. Okay. Then that word Boolean--but what is it doing there? I assume I don't literally type "Boolean." (Do I?)
Anyway, hopefully you see my problem(s).
How does this work?
You are almost there!
count needs a parameter p of type (:) A to (rocket) Boolean, where 'A' is the type of elements stored by the vector. So you have to provide a function from A to Boolean.
So you can use it like this:
val v = Vector(1, 2, 3, 4, 5, 6) // == Vector[Int](1, 2, 3, 4, 5, 6)
def odd(elem: Int): Boolean = {
elem % 2 == 0
}
v.count(odd) // == 3
Or using some syntactic sugar:
val v = Vector(1, 2, 3, 4, 5, 6) // == Vector[Int](1, 2, 3, 4, 5, 6)
v.count(_ % 2 == 0) // == 3