Ternary operator - exercise. I didn't get it, how the counting mechanics works - detailed explanation needed - conditional-operator

Thank you in advance for your time and help.
Exercise:
Write the code for sumDigitsInNumber(int number). The method takes a three-digit whole number. You need to calculate the sum of the digits of this number, and then return the result.
Consider this example:
The sumDigitsInNumber method is called with argument 546.
Example output:
15
CODE:
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
}
}
This is a solution and the task has been passed. The problem is the solution had been implemented by someone (not by me) therefore I can't understand How this function does its job.
I tried to test the function parts separately, just to see what would happen, and here is the result:
number%10 = 546%10;
546/10 = 54;
output:
6+sumDigitsInNumber(546/10) - which is totally wrong.
I don't understand HOW sumDigitsInNumber is treated by the ternary operator in there and how this short line of code:
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
makes such a complicated calculation?
Can anyone explain it to me in a way it would have explained to a Java-child?
TYVM in advance.

So, using the example number of 546, let's step through the code.
In the first run, it does indeed return 6+sumDigitsInNumber(546/10), that is all correct.
Because sumDigitsInNumber's parameter (number) is int, the decimal portion of the division is truncated, resulting in essentially a floor operation (forced round down). And we recursively call sumDigitsInNumber's, so we just keep "looping" that section of code. So for the second run, it is equivalent to sumDigitsInNumber(54), plus the additional 6 from the first run (6+sumDigitsInNumber(54)).
The second call returns 4+sumDigitsInNumber(54/10) by following the same logic as the first call. This is equivalent to 4+sumDigitsInNumber(5).
Then we run the whole process again, which returns 5+sumDigitsInNumber(5/10), equivalent to 5+sumDigitsInNumber(0).
The final call, sumDigitsInNumber(0), will return 0 because of the ternary operator in the return statement.
To expand this all out:
sumDigitsInNumber(546)
= 6+sumDigitsInNumber(546/10) = 6+sumDigitsInNumber(54)
= 6+(4+sumDigitsInNumber(54/10)) = 6+(4+sumDigitsInNumber(5))
= 6+(4+(5+sumDigitsInNumber(5/10))) = 6+(4+(5+sumDigitsInNumber(0)))
= 6+(4+(5+0))
= 6+(4+(5))
= 6+(9)
= 15

Related

What does the int value returned from compareTo function in Kotlin really mean?

In the documentation of compareTo function, I read:
Returns zero if this object is equal to the specified other object, a
negative number if it's less than other, or a positive number if it's
greater than other.
What does this less than or greater than mean in the context of strings? Is -for example- Hello World less than a single character a?
val epicString = "Hello World"
println(epicString.compareTo("a")) //-25
Why -25 and not -10 or -1 (for example)?
Other examples:
val epicString = "Hello World"
println(epicString.compareTo("HelloWorld")) //-55
Is Hello World less than HelloWorld? Why?
Why it returns -55 and not -1, -2, -3, etc?
val epicString = "Hello World"
println(epicString.compareTo("Hello World")) //55
Is Hello World greater than Hello World? Why?
Why it returns 55 and not 1, 2, 3, etc?
I believe you're asking about the implementation of compareTo method for java.lang.String. Here is a source code for java 11:
public int compareTo(String anotherString) {
byte v1[] = value;
byte v2[] = anotherString.value;
if (coder() == anotherString.coder()) {
return isLatin1() ? StringLatin1.compareTo(v1, v2)
: StringUTF16.compareTo(v1, v2);
}
return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
: StringUTF16.compareToLatin1(v1, v2);
}
So we have a delegation to either StringLatin1 or StringUTF16 here, so we should look further:
Fortunately StringLatin1 and StringUTF16 have similar implementation when it comes to compare functionality:
Here is an implementation for StringLatin1 for example:
public static int compareTo(byte[] value, byte[] other) {
int len1 = value.length;
int len2 = other.length;
return compareTo(value, other, len1, len2);
}
public static int compareTo(byte[] value, byte[] other, int len1, int len2) {
int lim = Math.min(len1, len2);
for (int k = 0; k < lim; k++) {
if (value[k] != other[k]) {
return getChar(value, k) - getChar(other, k);
}
}
return len1 - len2;
}
As you see, it iterated over the characters of the shorter string and in case the charaters in the same index of two strings are different it returns the difference between them. If during the iterations it doesn't find any different (one string is prefix of another) it resorts to the comparison between the length of two strings.
In your case, there is a difference in the first iteration already...
So its the same as `"H".compareTo("a") --> -25".
The code of "H" is 72
The code of "a" is 97
So, 72 - 97 = -25
Short answer: The exact value doesn't have any meaning; only its sign does.
As the specification for compareTo() says, it returns a -ve number if the receiver is smaller than the other object, a +ve number if the receiver is larger, or 0 if the two are considered equal (for the purposes of this ordering).
The specification doesn't distinguish between different -ve numbers, nor between different +ve numbers — and so neither should you.  Some classes always return -1, 0, and 1, while others return different numbers, but that's just an implementation detail — and implementations vary.
Let's look at a very simple hypothetical example:
class Length(val metres: Int) : Comparable<Length> {
override fun compareTo(other: Length)
= metres - other.metres
}
This class has a single numerical property, so we can use that property to compare them.  One common way to do the comparison is simply to subtract the two lengths: that gives a number which is positive if the receiver is larger, negative if it's smaller, and zero of they're the same length — which is just what we need.
In this case, the value of compareTo() would happen to be the signed difference between the two lengths.
However, that method has a subtle bug: the subtraction could overflow, and give the wrong results if the difference is bigger than Int.MAX_VALUE.  (Obviously, to hit that you'd need to be working with astronomical distances, both positive and negative — but that's not implausible.  Rocket scientists write programs too!)
To fix it, you might change it to something like:
class Length(val metres: Int) : Comparable<Length> {
override fun compareTo(other: Length) = when {
metres > other.metres -> 1
metres < other.metres -> -1
else -> 0
}
}
That fixes the bug; it works for all possible lengths.
But notice that the actual return value has changed in most cases: now it only ever returns -1, 0, or 1, and no longer gives an indication of the actual difference in lengths.
If this was your class, then it would be safe to make this change because it still matches the specification.  Anyone who just looked at the sign of the result would see no change (apart from the bug fix).  Anyone using the exact value would find that their programs were now broken — but that's their own fault, because they shouldn't have been relying on that, because it was undocumented behaviour.
Exactly the same applies to the String class and its implementation.  While it might be interesting to poke around inside it and look at how it's written, the code you write should never rely on that sort of detail.  (It could change in a future version.  Or someone could apply your code to another object which didn't behave the same way.  Or you might want to expand your project to be cross-platform, and discover the hard way that the JavaScript implementation didn't behave exactly the same as the Java one.)
In the long run, life is much simpler if you don't assume anything more than the specification promises!

converting imgradient matlab equivalent in python for a more complex scenario

I have a problem with converting Matlab equivalent in Python.
I have a problem with the following line of code :
instance_contour = uint8(imgradient(instance_map) > 0);
converting this line to python is the problem. As per the method suggested in imgradient matlab equivalent in Python , I would get magnitude and angle separately, but combining them and comparing with an integer value to get a new result is the place i'm stuck. I have added the full Matlab code for reference:
instance_map = imread(fullfile(human_inst_root, [imname '.png']));
instance_contour = uint8(imgradient(instance_map) > 0);
imwrite(instance_contour, fullfile(output_root, [imname '.png']));
imwrite(instance_contour*255, fullfile(vis_output_root, [imname '.png']));
Functions in MATLAB that can return multiple values will only do so when you specify multiple variables to hold those values, e.g. (from the documentation for imgradient):
[Gmag,Gdir] = imgradient(I)
If you specify only one return variable, e.g.:
Gsomething = imgradient(I)
only the first return value will be stored*, in this case the magnitude. This is what is happening in the line
instance_contour = uint8(imgradient(instance_map) > 0);
There is only one (implied) return variable that is used in the logical comparison, so you're only really comparing the magnitude of the gradient to 0. There is no need to try to combine this with the direction.
* You can choose which variable to return using the ~ to skip values similar to the _ in Python. [~,Gdir] = imgradient(I) would return only the second return value from the function.

How can I get an integer out of a String with sections

I try to get an integer (right after "PLAYING:STATION\nID:"out of the String shown in my screenshot by using the following code:
int zahl = Integer.parseInt(sentence.substring(sentence.indexOf("PLAYING:STATION\n
ID:")+1).trim());
But all I get is a NumberFormatException. How can I tell the trim()-method that it has to stop right after the number?
Screenshot of the complete String
Since you must select a specific ID: entry among several ones, I think the best way to proceed is using a regular expression. Using your output sample, I wrote the following code:
String text = "PLAYING_MODE\nID:\nPLAYING:STATION\nID:2\nNAME:wazee.org";
Pattern p = Pattern.compile("PLAYING:STATION\nID:(\\d+)");
Matcher m = p.matcher(text);
if (m.find()) {
int number = Integer.parseInt(m.group(1));
System.out.println(number);
}
which correctly parses the ID number that immediately follows PLAYING_STATION.
You could as well repeatedly work with the overloaded String.indexOf() method (find PLAYING:STATION, then the following ID:, then the following \n). I think the code might be harder to read, but it would still do the job.
I hope this will be helpful...
Cheers,
Jeff

Is good to call function in other function parameter?

I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.

Maths in processing language

Ok, so I am a little lost with Processing Programming Language again, so wondering if anyone can help my brain become unblocked?
This is the question - "Write a program which compares two numbers, if one of the numbers is larger than the other then the two numbers are added together and the result is printed in the console window."
So I have got this, but im getting errors on just the 'int' value code which is making me think ive completely misunderstood this?.. possibly misunderstood how the language works :/
Here is my code;
void setup() {
int a = 30
int b = 20
if (a > b) {printIn("a+b");}
}
Generally it helps if you post what errors you're getting. However, in this case you have a very basic syntax problem: you need to terminate your statements with semicolons - including the assignments. Eg: int a = 30;
Oh, and it's println (with a lowercase L) not printIn. And, as noted by logoff, you're doing the sum inside a quoted string, which will just print as a literal.
If I understad it correctly you have to declare the variables outside the setup() method. Intialization can be done inside the method.
The l in println(); should be lowercase.
There is no need for the quotes around the variables.
This works:
void setup() { int a = 30; int b = 20; if(a > b) {println(a + b); }}

Resources