def multiplyStringNumericChars(list: String): Int = {
var product = 1;
println(s"The actual thing + $list")
list.foreach(x => { println(x.toInt);
product = product * x.toInt;
});
product;
};
This is a function that takes a String like 12345 and should return the result of 1 * 2 * 3 * 4 * 5. However, I'm getting back doesn't make any sense. What is the implicit conversion from Char to Int actually returning?
It appears to be adding 48 to all the values. If instead I do product = product * (x.toInt - 48) the results are correct.
It does make sense: that is the way how characters encoded in ASCII table: 0 char maps to decimal 48, 1 maps to 49 and so on. So basically when you convert char to int, all you need to do is to just subtract '0':
scala> '1'.toInt
// res1: Int = 49
scala> '0'.toInt
// res2: Int = 48
scala> '1'.toInt - 48
// res3: Int = 1
scala> '1' - '0'
// res4: Int = 1
Or just use x.asDigit, as #Reimer said
scala> '1'.asDigit
// res5: Int = 1
Related
I'm making a simple program to make a calculation for a game I play. I tried 2 attempts and it wasn't working. I made all the variables doubles but I still get this odd result.
The values of actionTicks would be 1-10, skillLevel would be 1-99.
My current output is :
Your chance of receiving a pet is: 1.6E-6
Your chance is 0
Could someone explain why the result is wrong and how I'd fix it.
import scala.io.StdIn._
object PetRates {
def main(args: Array[String]): Unit = {
var baseDiv: Double = 50000000
println("Enter amount of ticks per action: ")
var actionTicks = readDouble()
println("Now enter your skill level: ")
var skillLvl = readDouble()
var result: Double = actionTicks*skillLvl
println("Your chance is: " + (result / baseDiv))
println("Your chance is " + ((8 * 10)/50000000) )
}
}
Your app appears to have delivered exactly what you're asking it to. It looks like you might be confused by the scientific notation:
scala> (8.0 * 10.0) / 50000000.0
// res1: Double = 1.6E-6
scala> 0.0000016
// res2: Double = 1.6E-6
As to (8 * 10) / 50000000, it's an integer division returning an integer (that rounds towards 0) since the operands are all Int type:
scala> (8 * 10) / 50000000
// res3: Int = 0
scala> 40000000 / 50000000
// res4: Int = 0
scala> 80000000 / 50000000
// res5: Int = 1
scala> -40000000 / 50000000
// res5: Int = 0
To add to Leo's answer, you can write either of the terms in fractions as a double so that the result is also double, like
(8.0 * 10)/50000000)
I have written a function in Scala that should calculate the sum of the squares of the digits of a number. Eg: 44 -> 32 (4^2 + 4^2 = 16 + 16 = 32)
Here it is:
def digitSum(x:BigInt) : BigInt = {
var sum = 0
val leng = x.toString.toList.length
var y = x.toString.toList
for (i<-0 until leng ) {
sum += y(i).toInt * y(i).toInt
}
return sum
}
However when I call the function let's say with digitSum(44) instead of 32 I get 5408.
Why is this happening? Does it have to do with the fact that in the list there are Strings? If so why does the .toInt method do not work?
Thanks!
The answer to your questions has been already covered here Scala int value of String characters, have a good read through and you will have more information than required ;)
Also looking at your code, it can benefit more from Scala expressiveness and functional features. The same function can be written in the following manner:
def digitSum(x: BigInt) = x.toString
.map(_.asDigit)
.map(a => a * a)
.sum
In the future try to avoid using mutable variables and standard looping techniques if you could.
When you do toString you're mapping the String to Chars not Ints and then to Ints later. This is what it looks like in the repl:
scala> "1".toList.map(_.toInt)
res0: List[Int] = List(49)
What you want is probably something like this:
def digitSum(x:BigInt) : BigInt = {
var sum = 0
val leng = x.toString.toList.length
var y = x.toString.toList
for (i<-0 until leng ) {
sum += (y(i).toInt - 48) * (y(i).toInt - 48) //Subtract out char base
}
sum
}
I want to serialize an into into a Byte array or array buffer.
I realise that I can use 'java.nio.ByteBuffer' but I am experimenting for fun and trying to do it myself.
The following code works for positive Int but goes wrong when I serialize a negative Int.
Can anyone explain why or show me a correction?
import scala.collection.mutable.ArrayBuffer
object b {
val INTBYTES:Int = 4 // int is 4 bytes
def toArrayBuf(x:Int): ArrayBuffer[Byte] = {
val buf = new ArrayBuffer[Byte](INTBYTES)
for(i <- 0 until INTBYTES) {
buf += ((x >>> (INTBYTES - i - 1 << 3)) & 0xFF).toByte
}
buf
}
}
the following test works as expected:-
int the REPL it prints:-
scala> val test:Int = 0x4f0f0f0f
test: Int = 1326386959
scala> println(test.toBinaryString)
1001111000011110000111100001111
scala> val t1 = b.toArrayBuf(test)
t1: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(79, 15, 15, 15)
scala> t1.foreach( it => printf("%s ",it.toInt.toBinaryString))
1001111 1111 1111 1111
but this with a negative int does something wierd:-
scala> val test2:Int = 0x8f0f0f0f
test2: Int = -1894838513
scala> println(test2.toBinaryString)
10001111000011110000111100001111
scala> val t2 = b.toArrayBuf(test2)
t2: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(-113, 15, 15, 15)
scala> t2.foreach( it => printf("%s ",it.toInt.toBinaryString))
11111111111111111111111110001111 1111 1111 1111
notice that the first byte has been 1 filled for the whole int it shoild be '10001111'
Any ideas?
FYI
Im using :-
scala -version
Scala code runner version 2.10.1 -- Copyright 2002-2013, LAMP/EPFL
java -fullversion
java full version "1.7.0_40-b31"
with OpenJDK
Thanks
Scala's toBinaryString method defers to the Java one on Integer. From those documents:
public static String toBinaryString(int i)
Returns a string representation of the integer argument as an unsigned
integer in base 2. The unsigned integer value is the argument plus
2^32 if the argument is negative; otherwise it is equal to the
argument. This value is converted to a string of ASCII digits in
binary (base 2) with no extra leading 0s.
In other words it's working as specified. Your bit-twiddling seems to be OK, but when you're printing the numbers out, you need to realise that the number of characters is dependent on the length of the data type. (E.g. -1: Int in binary is 11111111111111111111111111111111 while -1: Byte is 11111111.) You get away with it for positive numbers only because the leading zeros are not displayed, as specified above.
Solution: make your own toBinaryString for bytes, or just taking the rightmost 8 digits from the Int version should work (though less efficient) i.e.
it.toInt.toBinaryString.takeRight(8)
Taking Luigi's advice I hacked up a pimp for Byte that provides a toBinaryString that works properly, in case anyone else is struggling with similar problems here is what I did.
object b {
val INTBYTES:Int = 4 // int is 4 bytes
val SIZEBYTE:Short = 8
def toArrayBuf(x:Int): ArrayBuffer[Byte] = {
val buf = new ArrayBuffer[Byte](INTBYTES)
for(i <- 0 until INTBYTES) {
buf += ((x >>> (INTBYTES - i - 1 << 3)) & 0xFF).toByte
}
buf
}
def toBinaryString(x: Byte): String = {
val buf = new StringBuilder(SIZEBYTE)
for(i <- 0 until SIZEBYTE) {
buf.append((x >>> (SIZEBYTE - i - 1)) & 0x01)
}
buf.toString()
}
}
//pimp Byte
implicit def fooBar(byte: Byte) = new {def toBinaryString = b.toBinaryString(byte)}
Now when I run the previous experiment it works properly
scala> val test:Int = 0x4f0f0f0f
test: Int = 1326386959
scala> println(test.toBinaryString)
1001111000011110000111100001111
scala> val t1 = toArrayBuf(test)
t1: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(79, 15, 15, 15)
scala> t1.foreach( it => printf("%s ",it.toBinaryString))
01001111 00001111 00001111 00001111
and
scala> val test2:Int = 0x8f0f0f0f
test2: Int = -1894838513
scala> println(test2.toBinaryString)
10001111000011110000111100001111
scala> val t2 = toArrayBuf(test2)
t2: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(-113, 15, 15, 15)
scala> t2.foreach( it => printf("%s ",it.toBinaryString))
10001111 00001111 00001111 00001111
Thanks Luigi
I want to convert a char to an int value.
I am a bit puzzled by the way toInt works.
println(("123").toList) //List(1, 2, 3)
("123").toList.head // res0: Char = 1
("123").toList.head.toInt // res1: Int = 49 WTF??????
49 pops up randomly for no reason.
How do you convert a char to int the right way?
For simple digit to int conversions there is asDigit:
scala> "123" map (_.asDigit)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
Use Integer.parseInt("1", 10). Note that the 10 here is the radix.
val x = "1234"
val y = x.slice(0,1)
val z = Integer.parseInt(y)
val z2 = y.toInt //equivalent to the line above, see #Rogach answer
val z3 = Integer.parseInt(y, 8) //This would give you the representation in base 8 (radix of 8)
49 does not pop up randomly. It's the ascii representation of "1". See http://www.asciitable.com/
.toInt will give you the ascii value. It's probably easiest to write
"123".head - '0'
If you want to handle non-numeric characters, you can do
c match {
case c if '0' <= c && c <= '9' => Some(c - '0')
case _ => None
}
You can also use
"123".head.toString.toInt
If there is any way to call a def from a block
def factor (n: Int) : Int = if (n == 0 ) 1 else n * factor(n-1)
val i = 1000
i.toString.foreach ( x => sum += factor(x.toInt) )
at the end I want to get the sum of factorial of every digit
But it seems like def doesn't return a value, everytime is 0
How to fix it?
Thanks!
The problem actually has nothing to do with Scala per se; your code and your def are fine. The issue is with toInt:
scala> '3'.toInt
res7: Int = 51
toInt doesn't actually convert it as a decimal digit, but as a unicode (ish?) character value. These are producing very large numbers which go beyond what factor can handle:
scala> factor(6)
res8: Int = 720
scala> factor(20)
res9: Int = -2102132736
scala> factor(100)
res10: Int = 0
So instead use (thanks to Luigi)
x.asDigit