Is it possible to write loop in Scala Console? - scala

I try to test this in Scala Console (I mean console not script file):
while i < 10 {print(i) i += 1}
It doesn't work. I tried multiple lines it doesn't seem to either.
Am I obliged to use a script file just to test a simple loop ?

Yes it's possible. You have some syntax errors though:
var i = 0
while (i < 10) { println(i); i += 1 }
Or on multiple lines:
var i = 0
while (i < 10) {
println(i)
i += 1
}

As usual, there is more than one way to do this:
// join values beforehand and print the string in one go
println(0 to 9 mkString("\n"))
// using foreach
(0 to 9).foreach(println)
// using for
for(i <- 0 to 9) println(i)

scala> while i < 10 {print(i) i += 1}
<console>:1: error: '(' expected but identifier found.
while i < 10 {print(i) i += 1}
^
As indicated by the error message, a while must be followed by an "(", as the condition it tests for must be enclosed inside parenthesis. The same thing holds true for "if" and "for", by the way.

What you want is this:
var i = 0; while (i < 10) { print(i); i += 1 };

On the other hand, Scala encourages you to not use a mutable variable and while + condition
If you want to print the numbers from 0 to 9, use a sequence comprehension :
for (var <- range ) doSomethingWith (var)
In your case will be:
for (i <- 0 to 9) print (i)
(yes, the example looks pretty silly, but it helps to transition to a more "Scalaish" code)

Related

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong.
var arr = [0,1,2,3,4,5,6,7,8]
var result = 0;
for a in 0..<arr.count{
for b in 1..<arr.count - 1{
for c in 2..<arr.count - 2 {
arr[a] + arr[b] + arr[c] <= input[1] ? result = arr[a] + arr[b] +arr[c] : continue
}
}
}
[this is my error]
[1]: https://i.stack.imgur.com/UdiUB.png
In Swift, the ternary condition operator is an expression which takes the form
<condition> ? <expression if true> : <expression if false>
Expressions are part of larger statements, and the ternary specifically is one which evaluates to either the expression after the ?, or the one after the : depending on the truth of the condition.
continue, however, is not an expression but a statement on its own, which means that it cannot be on either side of the ternary.
Thinking about this another way: expressions evaluate to some value (e.g., can be put on the right-hand-side of an assignment, like x = <some expression>), while statements do not (e.g., it doesn't make sense to write x = continue).
You will need to express this in the form of a regular if-statement then:
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] +arr[c]
} else {
continue
}
Note that the above code might be grammatically correct (in that it will compile), but it is unlikely to be what you mean: the loop will automatically continue at the end of execution even if arr[a] + arr[b] + arr[c] <= input[1] by default, which means that your result may get overwritten later in the loop. It seems likely that you mean something like
outer_loop: for a in 0 ..< arr.count {
for b in 1 ..< arr.count - 1 {
for c in 2 ..< arr.count - 2 {
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] + arr[c]
// `break` would only exit the `c` loop, but with this label
// we can exit all loops at once.
break outer_loop
}
}
}
}

How to print ONCE if there are multiple correct answers? (MATLAB)

So I have arr = randi([0,20],20,1). I want to show: If there are numbers less than 5, fprintf('Yes\n') only once. Im using a for loop (for i = 1 : length(arr)) and indexing it.
As your description, maybe you need if statement within for loop like below
for i = 1:length(arr)
if arr(i) < 5
fprintf('Yes\n');
break
end
end
If you want to print Yes once, you can try
if any(arr < 5)
fprintf('Yes\n')
endif
If you don't want to use break, the code below might be an option
for i = 1:min(find(arr <5))
if (arr(i) < 5)
fprintf('Yes\n');
end
end
You can use a break statement upon finding the first value under 5 and printing the Yes statement.
Using a break Statement:
arr = randi([0,20],20,1);
for i = 1: length(arr)
if arr(i) < 5
fprintf("Yes\n");
break;
end
end
Extension:
By Using any() Function:
Alternatively, if you'd like to concise it down without the need for a for-loop the any() function can be used to determine if any values within the array meet a condition in this case arr < 5.
arr = randi([0,20],20,1);
if(any(arr < 5))
fprintf("Yes\n");
end
By Using a While Loop:
Check = 0;
arr = randi([0,20],20,1);
i = 1;
while (Check == 0 && i < length(arr))
if arr(i) < 5
fprintf("Yes\n");
Check = 1;
end
i = i + 1;
end

Programs for printing reverse triangle patterns with * in scala

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).

Scala for loop value example [duplicate]

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.

simple loop in coffeescript

I have this code:
count = $content.find('.post').length;
for x in [1...count]
/*
prev_el_height += $("#content .post:nth-child(" + x + ")").height();
*/
prev_el_height += $content.find(".post:nth-child(" + x + ")").height();
I expected this to turn into
for (x = 1; x < count; x++) { prev_el ... }
but it turns into this:
for (x = 1; 1 <= count ? x < count : x > count; 1 <= count ? x++ : x--) {
Can somebody please explain why?
EDIT: How do I get my expected syntax to output?
In CoffeeScript, you need to use the by keyword to specify the step of a loop. In your case:
for x in [1...count] by 1
...
You're asking to loop from 1 to count, but you're assuming that count will always be greater-than-or-equal-to one; the generated code doesn't make that assumption.
So if count is >= 1 then the loop counter is incremented each time:
for (x = 1; x < count; x++) { /* ... */ }
But if count is < 1 then the loop counter is decremented each time:
for (x = 1; x > count; x--) { /* ... */ }
Well, you want x to go from 1 to count. The code is checking whether count is bigger or smaller than 1.
If count is bigger than 1, then it has to increment x while it is smaller than count.
If count is smaller than 1, then it has to decrement x while it is bigger than count.
For future reference:
$('#content .post').each ->
prev_el_height += $(this).height()
Has the same effect, assuming :nth-child is equivalent to .eq(), and x going past the number the elements is a typo.