How to iterate through 3 parameters to find the largest value? [closed] - iteration

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 29 days ago.
Improve this question
public Person getOldest(Person personA, Person personB, Person personC) {
A method passes in 3 parameters of object Person in which Person can use the getAge() method. I'm trying to find the oldest person but some of them may be null in which case will return the oldest person that isn't null. If all three are null then it will return null.
I thought of using a bunch of nested if, else if loops to go through every combination of null and getAge() to find the oldest Person but there has to be a better method.

You can make another method called getOldest(p1, p2) with only 2 parameters and then do the following:
Person getOldest(p1, p2) {
if (p1 == null && p2 == null) { return null; }
if (p1 == null) { return p2; }
if (p2 == null) { return p1; }
if ( p1.getAge() > p2.getAge() ) { return p1; } else { return p2; }
}
Person getOldest(p1, p2, p3) { return getOldest(p1, getOldest(p2, p3)); }
Sorry for the formatting, I'm on a phone.

Related

How to use if statement when function returns 2 arguments?

I recently created a function that checks if a pair exists in my swap smart contract.
The functoin looks like this:
function checkIfPairExists(address _token1, address _token2) internal returns(uint, bool) {
for (uint index = 0; index < tokenPairs.length; index++) {
if (tokenPairs[index].token1 == _token1 && tokenPairs[index].token2 == _token2) {
return (index, true);
}
else if (tokenPairs[index].token2 == _token1 && tokenPairs[index].token1 == _token2) {
return (index, true);
} else {
return (0, false);
}
}
}
This function works fine but then when I try to use the function in an if statement like this:
if (checkIfPairExists(_token1, _token2) == (uint256, true))
How do I write it so it is correct? I am trying to receive index of the pair for my array and bool to see if the pair exists. I then need to save that index to find which pair it should add to.
Hope it makes sense.
Let me know if I should rephrase the question so more people will understand it and it can help them.
Thanks
You need to assign the returned values to two separate variables. Then you can validate either of them.
(uint256 index, bool exists) = checkIfPairExists(_token1, _token2);
if (exists == true) {
// do something with `index`
}
As said in the above answer by #pert-hejda, you will need to assign the function return values then you can use those to check the condition. Why? Because multiple returns are represented as tuples and currently the feature you want is not supported in solidity. So, you will need to assign the return values and use those values in conditionals. Thank you.

Kotlin if else and let issue, can't add a command [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Maybe I'm too tired, but when adding the following Log.d in the code (now commented out) the , Studio shows a compile error on the last "else if" (where (formId == 98))... Please advise
formViewModel?.questionGeneralData?.id?.let { formId ->
if (formId == 10 && !interactor.getIsRetroactive()) {
interactor.setCaffeineCounter(answer.toString())
// Log.d("5732", "455ryhrdhgbfhbdrfhbg")
} else if (formId == 14) {
if (answer == 0) {
if (BuildConfig.FLAVOR == BOOST_FLAVOR) {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM)
} else {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM_REFRESH)
}
} else {
interactor.removeSkippedForm(15)
}
} else if (formId == 97 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, caffeineTaken, answer)
} else if (formId == 98 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, alcoholTaken, answer)
}
}
I would say that when you do that, the return type of that first if statement is different than all the other statements. Since the let function (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html) expects a type for the return value that might be causing this compilation issue.
Use .also instead OR return same data-type from all if-else branches.
Also, put that log statement above interactor.setCaffeineCounter(answer.toString()).
Based on Joao Dias answer, the solution is to switch places the Log.d with the line before it (put it after the Log.d), so first the Log is executed, and then the line after it runs, and returns the value, that the let expects

object variable is not getting updated in Golang [duplicate]

This question already has answers here:
How to set and get fields in struct's method
(3 answers)
Closed 2 years ago.
I have created a struct Person and a method AddPerson which acts as a constructor for that struct.
package main
import "fmt"
type Person struct {
name string
salary int
balance int
}
func AddPerson(name string, salary int) Person {
p := Person{}
p.name = name
p.salary = salary
p.balance = salary
return p
}
After that I added a method spendMoney which does the following:
func (p Person) spendMoney(amountSpent int) {
p.balance = p.salary - amountSpent
fmt.Println("The amount spent is : ", amountSpent)
fmt.Println("Balance left is : ", p.balance)
}
and a main method shown below:
func main(){
p1 := AddPerson("A", 1500)
p2 := AddPerson("B", 2000)
p1.spendMoney(500)
p2.spendMoney(1000)
fmt.Println(p1.balance) //wanted to check the balance of p1 after spending.
}
I wanted to check the balance of p1 after he has spent the money, but it is still showing the same as before (i.e. 1500). I am new to Golang and come from a Python background, where this way works just fine.
You need to define the method on a pointer to your object, not to the value of your object.
func (p *Person) spendMoney(amountSpent int) {
p.balance = p.salary - amountSpent
}
Contrary to Python, you have to make the distinction between values and pointers. Values are basically copies of variables, modifying them will not make the variable itself change, unless explicitly assigning a new value to that variable.
This tutorial may make you better understand this.

how to make control flow based on nullable variable in Kotlin? [duplicate]

This question already has answers here:
Swift 'if let' statement equivalent in Kotlin
(16 answers)
Closed 4 years ago.
let say I have this variable
val number : Int? = 12
I want to make control flow based on the variable, if the variable is null then do something, otherwise do something else
in Swift I can make something like this:
if let number = number {
print(number)
} else {
// do something else
}
I actually can do like this
if number != null {
print(number!!) // I want to avoid exclamation mark like this
} else {
// do something else
}
but I want to avoid exclamation mark, like in print(number!!)
I previously though that I can do something like this
number?.let {
print(it)
} else {
// else block is not available in let in Kotlin
}
so how to solve this ?
The ?. means it will be executed only if the left side is not null.
The ?: operator executes the right side only if the left side is not null.
You may have something like:
theExpression().toCompute().theNumber?.let { number ->
print("This is my number $number
} ?: run {
print("There is no number")
}
Here we use T.let extension function for the then clause and run{ } (extension) function for the else clause.
Warning: The semantics is that you expected to return non-null value from the let {...} closure to avoid the `run {..} closure from being executed. Thus the code like:
number?.let { null } ?: run { 42 } === 42 (and not null)

Test function for adding 2 numbers

A couple of days ago I had an interview for an internship and I've been asked to write a function that tests if another function (which was adding 2 numbers together) is working. My answer was something similar to this:
bool addTest(double a, double b){
if((a+b) == addFunction(a, b))
return true;
else
return false;
}
However, they did not seem impressed with my answer. How else could I do it?
Test cases should be written with parameters and expected answers hard coded into them to eliminate any uncertainty.
bool addTest(){
//2+2=4
if (addfunction(2,2) !=4){
return false;
}
//1.66666+7.9=9.56666
if (addFunction(1.66666, 7.9) != 9.56666){
return false;
}
//0+0=0
if (addFunction(0,0) != 0){
return false;
}
//all tests passed
return true;
}
If a bug is found later on in the development, the conditions that caused the bug should be added to the test function. For example, one day you try to add two negative numbers, only to find they return a positive number. Adding a test case for this will ensure this bug is caught again if the function changes in the future.
//addFunction(-8, -1) //Oops! We return positive 9! Let's fix the bug and make a new test
//-8 + -1 = -9
if (addFunction(-8, -1) != -9){
return false;
}
It also wouldn't hurt to add test cases that verify two values don't produce a wrong answer, though this is harder to cover all test cases.
//-8 + -1 = -9
if (addFunction(-8, -1) == 9){
return false;
}