Reputation: 23
def logic(n : Int):String = {
var rows = Math.pow(2,n).toInt;
var i = 0;
var str : String = "";
for(i<-0 until rows)
{
var j = n-1 ;
for(j<-(0 to n-1).reverse)
{
str+=(print((i/(Math.pow(2,j).toInt))%2)).toString;
}
str+=(println()).toString;
}
println(str.toString);
return str.toString;}
When i run println(postfix) i just see a lot of () help me to add print((i/(Math.pow(2,j).toInt))%2) into a string.Thanks
Upvotes: 1
Views: 876
Reputation: 13807
print
and println
doesn't return a String
, it prints to the standard output. The ()
you are seeing in the console is scala Unit
- which is a tuple of 0 elements, since print
and println
return Unit
(which is similar in terms of semantics to javas void
). To append the evaluated String value of your calculation simply do this
str += ((1 / (Math.pow(2, 1).toInt)) % 2).toString
Then use print
or println
to output it to the standard out:
println(str)
However, to make your code more idiomatic, I would look at
mkString
on collections (random resource)Looking at those a bit more concise solution:
def truthtable(n: Int) = (0 until Math.pow(2, n).toInt).map { i =>
(0 to n - 1).reverse.map(j => (i / (Math.pow(2, j).toInt)) % 2).mkString("")
}.mkString("\n")
This returns the truthtable as a String then all you have to do is print it:
println(truthtable(5))
Note that I didn't check if your algorithm is correct, just refactored what you already have.
Upvotes: 1