I'm trying to generate sequence of increasing numbers using ScalaCheck.
I would like to achieve something like this:
0 2 4 6
Which was achieved by increasing range 0..3 by step of 2:
0 * 2 = 0
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
Thanks for help.
Sorry if question has been questioned before.
Well it appears not so difficult to generate random sequence. Sorry I needed to be more specific about predictability.
object GenerateSequence {
def apply(maxSize: Int, maxStep: Int): Gen[Seq[Int]] = {
for {
size <- Gen.chooseNum(1, maxSize)
step <- Gen.chooseNum(1, maxStep)
} yield {
(0 to size).map(_ * step)
}
}
}
It's not really using ScalaCheck, but you can use the stream of even numbers:
>val even = Stream.from(0,2)
>even.take(4)
// Display
// res2: Stream[Int] = Stream(0, 2, 4, 6)
Related
I am trying to explore Scala. I am new to Scala. This might be a simple question and searched in google to get below scenario to solve. But couldn't get answers. Instead of Scala I am getting Java related things.
My requirement to print format like below.
* * * * *
* * * *
* * *
*
Can someone suggest me how to get this format.
Thanks in advance.
Kanti
Just for the sake of illustration, here are two possible solution to the problem.
The first one is completely imperative, while the second one is more functional.
The idea is that this serves as an example to help you think how to solve problems in a programmatic way.
As many of us have already commented, if you do not understand the basic ideas behind the solution, then this code will be useless in the long term.
Here is the imperative solution, the idea is simple, we need to print n lines, each line contains n - i starts (where i is the number of the line, starting at 0). The starts are separated by an empty space.
Finally, before printing the starts, we need some padding, looking at example inputs, you can see that the padding starts at 0 and increases by 1 for each line.
def printReverseTriangle(n: Int): Unit = {
var i = 0
var padding = 0
while (i < n) {
var j = padding
while (j > 0) {
print(" ")
j -= 1
}
var k = n - i
while (k > 0) {
print("* ")
k -= 1
}
println()
i += 1
padding += 1
}
}
And here is a more functional approach.
As you can see, in this case we do not need to mutate anything, all the high level operators do that for us. And we only need to focus on the description of the solution.
def printReverseTriangle(size: Int): Unit = {
def makeReverseTriangle(size: Int): List[String] =
List.tabulate(size) { i =>
(" " * (size - i)) + ("* " * i)
}.reverse
println(makeReverseTriangle(size).mkString("\n"))
}
To add an alternative to Luis's answer, here's a recursive solution:
import scala.annotation.tailrec
def printStars(i: Int): Unit = {
#tailrec
def loop(j: Int): Unit = {
if(j > 0) {
val stars = Range(0, j).map(_ => "*").mkString(" ") // make stars
if(i == j) println(stars) // no need for spaces
else println((" " * (i - j)) + stars) // spaces before the stars
loop(j - 1)
}
}
loop(i)
}
printStars(3)
// * * *
// * *
// *
This function will take a maximum triangle size (i), and for that size until i is no longer greater than 0 it will print out the correct number of stars (and spaces), then decrement by 1.
Note: Range(0, j).map(_ => "*").mkString(" ") can be replaced with List.tabulate(j)(_ => "*").mkString(" ") per Luis's answer - I'm not sure which is faster (I've not tested it).
I didn't understood the concept of the For-In loop in swift 3 , can anyone explain to us it m thanks in advance
var total = 0
for i in 0..<4 {
total += i
}
print(total)
The result of total is 6 , Why ?
i=0 =>
total = 0+0 =0
i=1 =>
total = 0+1 = 1
i=2 =>
total = 1+2 = 3
i=3 =>
total = 3+3 =6
it's simply alogrithm ;-)
i never reach 4 because you said it STRICTLY inferior to 4 =)
(Do I answer your question?)
Your loop will be vary from 0 to 3 i.e. 0,1,2,3 but if you want it will vary from 0 to 4 then try this -
var total = 0
for i in 0...4 {
total += i
}
print(total)
To find how many ways we have of making change for the amount 4 given the coins [1,2,3], we can create a DP algorithm that produces the following table:
table[amount][coins.count]
0 1 2 3 4
-----------
(0) 1 | 1 1 1 1 1
(1) 2 | 1 1 2 2 3
(2) 3 | 1 1 2 3 4
The last position being our answer. The answer is 4 because we have the following combinations: [1,1,1,1],[2,1],[2,2],[3,1].
My question is, is it possible to retrieve these combinations from the table I just generated? How?
For completeness, here's my algorithm
func coinChange(coins: [Int], amount: Int) -> Int {
// int[amount+1][coins]
var table = Array<Array<Int>>(repeating: Array<Int>(repeating: 0, count: coins.count), count: amount + 1)
for i in 0..<coins.count {
table[0][i] = 1
}
for i in 1...amount {
for j in 0..<coins.count {
//solutions that include coins[j]
let x = i - coins[j] >= 0 ? table[i - coins[j]][j] : 0
//solutions that don't include coins[j]
let y = j >= 1 ? table[i][j-1] : 0
table[i][j] = x + y
}
}
return table[amount][coins.count - 1];
}
Thanks!
--
Solution
Here's an ugly function that retrieves the combinations, based on #Sayakiss 's explanation:
func getSolution(_ i: Int, _ j: Int) -> [[Int]] {
if j < 0 || i < 0 {
//not a solution
return []
}
if i == 0 && j == 0 {
//valid solution. return an empty array where the coins will be appended
return [[]]
}
return getSolution(i - coins[j], j).map{var a = $0; a.append(coins[j]);return a} + getSolution(i, j - 1)
}
getSolution(amount, coins.count-1)
Output:
[[1, 3], [2, 2], [1, 1, 2], [1, 1, 1, 1]]
Sure you can. We define a new function get_solution(i,j) which means all solution for your table[i][j].
You can think it returns an array of array, for example, the output of get_solution(4,3) is [[1,1,1,1],[2,1],[2,2],[3,1]]. Then:
Case 1. Any solution from get_solution(i - coins[j], j) plus coins[j] is a solution for table[i][j].
Case 2. Any solution from get_solution(i, j - 1) is a solution for table[i][j].
You can prove Case 1 + Case 2 is all possible solution for table[i][j](note you get table[i][j] by this way).
The only problem remains is to implement get_solution(i,j) and I think it's good for you to do it by yourself.
If you still got any question, please don't hesitate to leave a comment here.
This question already has answers here:
Get list of elements that are divisible by 3 or 5 from 1 - 1000
(6 answers)
Closed 7 years ago.
How to do it this problem in Scala? Do it in For-loop.
sum of all the multiples of 3 and 5 below 1000;
Example: 1*3+2*5+3*3+4*5+5*3+6*5 ... so on 999*3+1000*5 = How much?
I don't think that 1000*5 is a multiple of 5 below 1000. 1000*5 is 5000 which is not below 1000.
It seems like what you want is:
(1 to 1000).filter(x => x % 3 = 0 || x % 5 == 0).sum
Which doesn't use a "for-loop". A lot of people would cringe at such a term, scala doesn't really have for-loops. if MUST use the for construct, perhaps you would write
(for (x <- 1 to 1000 if x % 3 == 0 || x % 5 == 0) yield x).sum
which is exactly the same thing as above.
you could also (though I would not recommend it) use mutation:
var s = 0
for { x <- 1 to 1000 } { if(x % 3 == 0 || x % 5 == 0) s += x }
s
which could also be
var s = 0
for { x <- 1 to 1000 if (x % 3 == 0 || x % 5 == 0) } { s += x }
s
If you want to use the principles of functional programming you would do it recursive - better you can use tail recursion (sorry that the example is not that good but it's pretty late).
def calc(factorB:Int):Int = {
if(factorB+1 >= 1000)
3*factorB+5*(factorB+1)
else
3*factorB+5*(factorB+1)+calc(factorB+2)
}
In a for-loop you can do it like
var result = 0
for(i <- 1 to 1000){
result += i*(i%2==0?5:3)
}
After the for-loop result yields the calculated value. The downside is that you're using a var instead of val. Iam not sure if the statement i%2==0?5:3 is valid in scala but I don't see any reasons why it shouldn't.
I'm trying to recursively define an observable that either emits items from a subject or, if a certain amount of time passes, a default value, in this case I'm using the timer's default value of zero. I'm using RxScala and have begun with the following code:
val s = PublishSubject[Int]()
def o: Observable[Unit] = {
val timeout = Observable.timer(1 second)
Observable.amb(s, timeout)
.first
.concatMap((v) => {
println(v)
o
})
}
ComputationScheduler().createWorker.schedule {
var value = 0
def loop(): Unit = {
Thread.sleep(5000)
s.onNext(value + 1)
value += 1
loop()
}
loop()
}
o.toBlocking.last
This seems like it should work, but the output is confusing. Every other sequence of zeros contains two instead of the expected four. Two zeros are emitted and the remaining three seconds elapses, but without output.
0
0
0
0
1
0
0
2
0
0
0
0
3
0
0
4
0
0
0
0
5
0
0
6
0
0
0
0
7
0
0
8
This one is puzzling indeed! So here's a theory:
In truth, your code is producing 4 ticks every 5 seconds rather than 5.
There is a race condition on the 4th, one, won first by the timeout, then the worker, then the timeout, etc.
So, instead of the sequence being 00001 002 00003... look at it as 0000 1002 0000...
So you might have 2 separate problems here and I can't do much without fiddling with it, but things you can try:
Add also a serial number to o(), so you can see which timouts are not winning the race.
Change the values from 1 and 5 seconds to some that are not multiple of each other, like 1.5 and 5. This might help you take one problem out and focus on the other.
Put an external, unrelated worker to print "----" every second. Start it after 0.3 seconds or so. Might give you a better idea of where the divide is.
Refactoring your code to the following generates the expected result (on my machine):
object Test {
def main(args: Array[String]) {
val s = PublishSubject[Int]()
val timeout = Observable.timer(1 second)
def o: Observable[Unit] = {
Observable.amb(s, timeout).first
.concatMap((v) => {
println(v)
o
})
}
var value = 0
NewThreadScheduler().createWorker.scheduleRec {
Thread.sleep(5000)
value += 1
s.onNext(value)
}
o.toBlocking.last
}
}
Notice the switch to the NewThreadScheduler and the use of the scheduleRec method as opposed to manual recursive scheduling.