When statement kotlin greater than or equals - kotlin

In kotlin when statement I can do in 2..4 which is equivalent to >= 2 and <= 4.
How do I just look for >= 2? I tried an infinite range: in 2.., but this doesn't seem to be a thing.
I also tried just putting in >= 2, but no luck either.
How do I do this in kotlin? Or do I have to switch to an if statement?

Should be
in 2..Integer.MAX_VALUE
Assumed your values are integers, as you are looking for an iterable range.

What was the problem with >=?
This works fine:
val x = 3
val y = when {
x + 1 >= 4 -> "one"
x + 1 < 4 -> "two"
else -> "else"
}
println(y)

Related

Axiomatic Semantics - How to calculate a weakest precondition of a program

Assuming the post-condition, how can I compute the weakest pre-condition of a program containing two statements?
For example :
a=x;
y = 0
{x = y + a}
Another example:
y = x;
y = x + x + y
{y = 3x ^ z> 0}
I tried to solve them but both questions resulted in pre-conditions or post-condition that are identical to the statement and I don't know if this is valid.
for example, the precondition of the last statement is "y=x" , thus it is the post condition of the preceding statement which is " y=x" as well
You can apply the rules of Hoare Logic here. Specifically, for the examples you have, you only need the rule for assignment:
{ P[E/x] } x = E { P }
Here, P[E/x] means take P and substitute (i.e. replace) all occurrences of x with E. For example, if P is x == 0 then P[0/x] gives 0 == 0.
To calculate the weakest precondition, you start from the end and work backwards. For your first example, we start with the last statement:
{ ??? } y = 0 { x == y + a }
The goal is to determine something suitable for ???. Applying our rule for assignment above, we can see that this is a solution:
{ x == 0 + a } y = 0 { x == y + a }
We can further simplify this to { x == a }. Then, we move on to address the statement before y = 0, and so on.

Struggling with using iteration and println in Julia

I am new to Julia and trying to understand how things work.
Below is the sample code I just wrote.
(This is the baseline code and I am planning to add other lines one by one.)
I expected to see something like 1 2 3 4 5 6 7... from test = check(m)
However, I don't see any result.
Any help will be very much appreciated.
using Pkg
using Optim
using Printf
using LinearAlgebra, Statistics
using BenchmarkTools, Optim, Parameters, QuantEcon, Random
using Optim: converged, maximum, maximizer, minimizer, iterations
using Interpolations
using Distributions
using SparseArrays
using Roots
# ================ 1. Parameters and Constants ============================
mutable struct Model
# Model Parameters and utility function
δ::Float64
function Model(;
δ = 0.018,
)
new(
δ
)
end
end
function check(m)
it = 0
tol=1e-8
itmax = 1000
dif = 0
# Iteration
while it < itmax && dif >=tol
it = it + 1;
V = Vnew;
println(it)
end
return itmax
end
m=Model()
test = check(m)
dif = 0
tol = 1e-8
while it < itmax && dif >= tol
Now explain to me how
dif >= tol

Sum Up all Numbers before and after an operator Sign in a String user input

i am new to programming and starting up with kotlin . i've been stuck on this problem for a few days and i really need some assistance . i am trying to read a user input of Strings in a format like this 3 + 2 + 1, go through the String and wherever there is an operator , add up the numbers before and after the operator sign . so the above 3 + 2 + 1 should output 6.
Here's a snippet of my code
fun main() {
val userInput = readLine()!!.split(" ")
var sum = 0
for (i in 0 until userInput.size) {
if (userInput.get(i) == "+"){
sum += userInput.get(i-1).toInt() + userInput.get(i+1).toInt()
}
}
println(sum )
}
my code works until the point of adding up the numbers . it repeats the next number after the operator , so using the above example of 3 + 2 + 1 it outputs 8 thus 3 + 2 + 2 + 1. I'm so confused and don't know how to go about this .
Try not to increment the sum value each time, but rewrite the last number which was participated in sum. Just like that:
You have the case: 1 + 2 + 3 + 4
Split them
Now you have the array [1, +, 2, +, 3, +, 4]
Then you iterate this array, stuck with the first plus and sum the values.
Rewrite the second summed value with your sum.
Now you have new array [1, +, 3, +, 3, +, 4]
At the end of the loop, you will have this array [1, +, 3, +, 6, +, 10]
And your sum is the last element of the array
The logic of your code is that for each "+" encountered, it adds the sum of the numbers left and right of the "+" to the sum. For the example "1 + 2 + 3", here's what is happening:
Starting sum is 0.
At first "+", add 1 + 2 to sum, so now sum is 3.
At second "+", add 2 + 3 to sum, so now the sum is 3 + 5 = 8.
So you are adding all the middle numbers to the total twice, because they each appear next to two operators.
One way to do this is start with the first number as your sum. Then add only the number to the right of each "+", so numbers are only counted once.
fun main() {
val userInput = readLine()!!.split(" ")
var sum = userInput[0].toInt()
for (i in userInput.indices) {
if (userInput[i] == "+") {
sum += userInput[i + 1].toInt()
}
}
println(sum)
}
sum += userInput.get(i-1).toInt() + userInput.get(i+1).toInt()
This is only valid for the first iteration, so if the user puts 1 + 2 + 3.
So
userInput[0] is 1
userInput[1] is +...
the first time that line will be triggered sum will be 1 + 2, and that's quite fine, but the second time, in the second +, you will sum i-1 (which is 2 and was in the total sum already) and i+1, that will be 3, so you are doing 1+2+2+3.
You need to understand why this is happening and think of another way to implement it.
Check this is working for me
var sum = 0
readLine()?.split(" ")?.filter { it.toIntOrNull() != null }?.map { sum += it.toInt() }
println(sum)

Find the first element in a list that verify a condition

Assuming we are given a list of integers R = [3,5,3,6,0,6,7], an threshold x (integer) and a window size (integer) p. For example, x=4 and p = 2.
I need to find the first index t that verifies the the following conditions:
R[t] >= 4, R[t+1] >= 4. Since p=2, we need to only verify for two boxes t and t+1. If p was equal to 3 we will need to verify for t, t+1 and t+2.
Here the t I am looking for is 5 (indexing is starting from 0).
How to write this in a elegant way in Kotlin (rather than looping on the elements).
A tentative that is giving an error (x=4 and p = 2. The output should be 3 since we start indexing by 0):
val numbers = listOf(1, 2, 3, 4, 6, 8, 2)
val firstIndex = numbers.find { it >= 4 for it in it..it+2-1}
val numbers = listOf(1, 2, 3, 4, 6, 8, 2)
val p = 2
val x = 4
val t = numbers.windowed(p).indexOfFirst { window -> window.all { it >= x } } // t == 3
t will be equal to -1 in case if no matches will be found
Use windowed to check groups of values for each index in the list. Use withIndex() so you are iterating with the indices, which you need in your final result. Then use firstOrNull() (which find() is a redundant alias of). And finally, take ?.index to get the index of the first entry that satisfies the condition, or null if none satisfy.
val x = 4
val p = 3
val list = listOf(2,5,3,6,0,6,7)
val t = list
.windowed(p)
.withIndex()
.firstOrNull { (_, sublist) -> sublist.all { it >= x } }
?.index
find Returns the first element matching the given predicate, or null if no such element was found.
If I've understood correctly, this should work:
fun main() {
val list = listOf(3,5,3,6,0,6,7)
val p = 2
val x = 4
val t = list.withIndex().windowed(p).firstOrNull() { window ->
window.all { it.value >= x }
}?.first()?.index
println(t)
}
Output:
5

Kotlin - same condition: multiple if statements or one if statement

In Kotlin you can use if statements kind of like ternary operators.
We have the option to do something like this:
val x = if (isOdd) 1 else 2
but if we have multiple variables that need to be set based on some condition is it more correct to do it the old fashioned way like so:
val x: Int
val y: Int
val z: Int
if (isOdd) {
x = 1
y = 3
z = 5
} else {
x = 2
y = 4
z = 6
}
or like this :
val x = if (isOdd) 1 else 2
val y = if (isOdd) 3 else 4
val z = if (isOdd) 5 else 6
the second way looks much cleaner to me, but I'd like to know if the first method would be computed faster since it only needs to calculate the condition once whereas the second way needs to check the condition 3 times.
Is the second way actually slower or will it be optimized by the compiler?
I'd prefer something like this, looks way more Kotlinesque:
data class Point3D(val x: Int, val y: Int, val z: Int)
fun foo(isOdd: Boolean): Point3D = if (isOdd) Point3D(1, 3, 5) else Point3D(2, 4, 6)
//or using destructureing see https://kotlinlang.org/docs/reference/multi-declarations.html)
val (x,y,z) = if (isOdd) Triple(1, 3, 5) else Triple(2, 4, 6)
Also it combines the best of both, using if as expression and only one if is needed. (At the cost of an additional object allocation).
But to answer your question. Do what you like and think is most readable. Performance wise I doubt you will make a difference.
if is an expression in Kotlin, not a statement: it returns a value, whereas it doesn't in Java's case.
I don't think here is such an optimization issue you should ever think about, honestly. Premature optimization is a common source of problems. If this boolean variable is thread-confined, then I think the compiler will perform all the optimizations that are possible in this context, so it will be almost no overhead at all (if not completely).
Wise choice in OO languages is to prefer clearness and flexibility over low-level optimization issues (especially when compilers are able to resolve them).
Okay, so just saw this question again and got curious... So I did some tests.
Turns out there is actually a HUGE difference, heres the results:
Code
fun main() {
for (i in 0 until 3) {
val t1_s = System.currentTimeMillis()
for (j in 0 until 100000) {
when (i){
0 -> a(j % 2 == 0)
1 -> b(j % 2 == 0)
2 -> c(j % 2 == 0)
}
}
val t1_e = System.currentTimeMillis()
println("Test $i - time ${t1_e - t1_s}")
}
}
fun a(isOdd: Boolean): Int {
val x: Int
val y: Int
val z: Int
if (isOdd) {
x = 1
y = 3
z = 5
} else {
x = 2
y = 4
z = 6
}
return x + y + z
}
fun b(isOdd: Boolean): Int {
val x = if (isOdd) 1 else 2
val y = if (isOdd) 3 else 4
val z = if (isOdd) 5 else 6
return x + y + z
}
fun c(isOdd: Boolean): Int {
val (x,y,z) = if (isOdd) Triple(1, 3, 5) else Triple(2, 4, 6)
return x + y + z
}
Output
Test 0 - time 3
Test 1 - time 1
Test 2 - time 8
It seems my second solution is the fastest, my first suggestion next, and the top answer as MUCH slower.
Does any one know why this might be? Obviously these are milliseconds so it almost always wouldn't matter, but it is neat to think that one method is 5-10 times faster
EDIT:
So tried bumptin the iterations up to 100000000 and the results were:
Test 0 - time 6
Test 1 - time 41
Test 2 - time 941
I Guess the first 2 options are getting optimized out but the third option is always creating a new object making it much slow
Try it online!