I have read some number of binary representation from a file, then I summed them up and tried to find the number of zeroes and one's occurrences.
The problem is that some digits get lost or whatever else happens, so the total number of digits in a sum is more than a sum of zeroes and one's.
Here is my code:
val binaryNums = Source.fromFile("path/task2.txt").getLines.map(BigInt(_)).toList
val sumOfBins = binaryNums.sum.toString
println("Zeroes occurrence " + sumOfBins.count(_ == '0'))
println("Ones occurrence " + sumOfBins.count(_ == '1'))
I would be really grateful if you helped me to find a mistake.
Update: File contents look like this (about 800 digits in each number)
.
By default toString converts the number to its decimal representation. To convert to binary you have to provide the radix argument to toString:
val sumOfBins = binaryNums.sum.toString(2)
Related
Why does NumberFormat(".##").format(17.46) leads to a string of 17.46 and not .46?
How can I achieve the latter, i.e. remove all digits in front of the decimal sign?
The NumberFormat only changes the way that a number is being displayed(basically, what formatting is). So you can't get the fractional part of the number(it doesn't work like pattern matching).
Instead, you can use:
var num = 17.46;
var fraction = num.toString().split('.')[1];
Note: you can use '.' + num.toString().split('.')[1] to get the fraction part with the starting dot.
You can read more about the ICU Formatting that NumberFormat uses in this link.
Just as an alternative to the other answer, you can try to remove the integer part before converting to String, and not after:
String formatFraction (num a){
num b = a.floor();
num c = a-b;
return NumberFormat(".##").format(c);
}
This way you can guarantee it will work despite of locale.
‘#’ in the NumberFormat class marks a single digit (omitted if the value is zero). So the number of hashtags after the decimal point denotes how many decimal places you want. For example:
double number = 12.1234;
NumberFormat(".#").format(number); //prints 12.1
NumberFormat(".##").format(number); //prints 12.12
NumberFormat(".###").format(number); //prints 12.123
NumberFormat(".####").format(number); //prints 12.1234
You could use substring and indexOf to remove everything before the decimal point, like so:
String str = "12.36";
String newStr = str.substring(str.indexOf('.') + 1);
//If you want to include the decimal point, remove the + 1.
Trying to create a simple function whereby a String value is passed in i.e. "1" and the formatter should return the value with leading zeros and 5 decimal points however instead of a dot '.' I'm trying to return it with a comma ','
This is what I have attempted however its not working because the decimalFormatter can only handle numbers and not a string. The end goal is to get from "1" to "000000001,00000" - character length is 14 in total. 5 0's after the comma and the remaining before the comma should be padded out 0's to fill the 9 digit requirement.
Another example would be going from "913" to "000000913,00000"
def numberFormatter (value: String): String =
{
import java.text.DecimalFormat
val decimalFormat = new DecimalFormat("%09d,00000")
val formattedValue = decimalFormat.format(value)
return formattedValue
}
Any help would be much appreciated. Thank you in advance.
It's easy enough to format a String padded with spaces, but with zeros not so much. Still, it's not so hard to roll your own.
def numberFormatter(value :String) :String =
("0" * (9 - value.length)) + value + ",00000"
numberFormatter("1") //res0: String = 000000001,00000
numberFormatter("913") //res1: String = 000000913,00000
Note that this won't truncate the input String. So if value is longer than 9 characters then the result will be longer than the desired 15 characters.
def f(value:String) = new java.text.DecimalFormat("000000000.00000").format(value.toFloat).replace(".", ",")
scala> f(913f)
res5: String = 000000913,00000
// Edit: Use .toFloat (or .toInt, .toLong, etc.) to convert your string to a number first.
I like to print a lot of numbers between -1 and 1 and need them to be aligned by the decimal point.
What I get with %2.2f is:
val (a, b) = (0.38, -0.38); println (f"${a}%2.2f\n${b}%2.2f ")
0,38
-0,38
What I like to get is:
0,38
-0,38
Is there an elegant solution?
What you can actually do is to add -+ preceding the formatting likewise:
scala> val (a, b) = (0.38, -0.38); println (f"${a}%-+2.2f\n${b}%-+2.2f")
+0.38
-0.38
a: Double = 0.38
b: Double = -0.38
You will get the + before the number though.
EDIT:
If you know the number of digits of the numbers (the first number of %n.m indicates the length of the digits), you can actually go like:
scala> printf("%5.2f", a);
0.38
scala> printf("%5.2f", b);
-0.38
Although there is already an accepted answer, I'll add one more for future reference. Scala f"" string interpolator actually uses Java formatting infrastructure and in the Java documentation you may find following flag:
' ' '\u0020' Requires the output to include a single extra space ('\u0020') for non-negative values.
So you might actually want to use it. Here is an example that shows the difference:
val arr = Array(0.38, -0.38, 10.38, -10.38, 123.38, -123.38)
println("Without space:")
arr.foreach(a => println(f"${a}%6.2f"))
println("----------------")
println("With space:")
arr.foreach(a => println(f"${a}% 6.2f"))
which produces following output:
Without space:
0,38
-0,38
10,38
-10,38
123,38
-123,38
----------------
With space:
0,38
-0,38
10,38
-10,38
123,38
-123,38
note the difference for 123.38/-123.38 i.e. for the case when there is an "overflow"
The solution is trivial: The first number does not indicate digits before the dot, but digits total, and does not yield to an errormessage, if too short. So for 2 digits after the dot, plus dot, plus one in front and an optional minus sign, I need 5 digits in total, and then it works:
val (a, b) = (0.38, -0.38); println (f"${a}%5.2f\n${b}%5.2f ")
0,38
-0,38
And no, a plus sign is not an option.
I'm trying to create a string from hex values in an array, but whenever a hex in the array starts with a zero it disappears in the resulting string as well.
I use String(value:radix:uppercase) to create the string.
An example:
Here's an array: [0x13245678, 0x12345678, 0x12345678, 0x12345678].
Which gives me the string: 12345678123456781234567812345678 (32 characters)
But the following array: [0x02345678, 0x12345678, 0x02345678, 0x12345678] (notice that I replaced two 1's with zeroes).
Gives me the string: 234567812345678234567812345678 (30 characters)
I'm not sure why it removes the zeroes. I know the value is correct; how can I format it to keep the zero if it was there?
The number 0x01234567 is really just 0x1234567. Leading zeros in number literals don't mean anything (unless you are using the leading 0 for octal number literals).
Instead of using String(value:radix:uppercase), use String(format:).
let num = 0x1234567
let str = String(format: "%08X", num)
Explanation of the format:
The 0 means to pad the left end of the string with zeros as needed.
The 8 means you want the result to be 8 characters long
The X means you want the number converted to uppercase hex. Use x if you want lowercase hex.
String to Integer (atoi)
This problem is implement atoi to convert a string to an integer.
When test input = " +0 123"
My code return = 123
But why expected answer = 0?
======================
And if test input = " +0123"
My code return = 123
Now expected answer = 123
So is that answer wrong?
I think this is expected result as it said
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
Your first test case has a space in between two different digit groups, and atoi only consider the first group which is '0' and convert into integer