0

I had to swap 2 numbers in one line expression using no other variable except x and y. So I wrote the following .c program to swapp two numbers with the given conditions and it works like charm.


int main() {
    
    int x =5, y =2;
    x = y-x+(y=x);
    printf("X=%d, y=%d", x, y);

    return 0;
}

But when i try to do the same in kotlin it gives me an error that

Assignments are not expressions, and only expressions are allowed in this context,

I can resolve this issue by introducing a third variable just like this. But I'm not allowed to have any other variable except x and y which are already given. So is there any other way I can do this in one line using any kotlin property?

Below is the kotlin program

fun main() {
    
    var x = 5
    var y = 10
    x = y-x+(y=x)   
    println("X = $x, Y = $y")

}
5
  • 1
    are you required to use one line, or is the only restriction that you can't use a 3rd variable? Commented Sep 10, 2022 at 3:30
  • 4
    Kotlin doesn’t support that, but you can do a = b.also { b = a } Commented Sep 10, 2022 at 3:30
  • @nigh_anxiety in one line expression without any 3rd variable, just like i did in c. Commented Sep 10, 2022 at 3:32
  • 2
    if the requirement is a single line, then x = x+y; y = x-y; x = x-y does the trick. If it has to be a single statement then TenFour's suggestion of x = y.also{y = x} appears to work when testing in a Kotlin playground Commented Sep 10, 2022 at 5:16
  • 2
    Why do you want to do this though? Kotlin isn't C, and although you can technically do this stuff on a single written line, the bytecode it gets compiled to will create extra variables and generally be more verbose (nigh_anxiety's example aside!). If it's about neat, efficient memory tricks, it's not really that kind of language. If it's about conciseness, just do the also thing, or write a reusable swap function that takes property references so you can go swap(::a, ::b) or something like that Commented Sep 10, 2022 at 19:23

2 Answers 2

4

While I have two suggestions below, I want to start with a recommendation against either of them, at least in this simple example.

It's usually a lot more clear to optimise code for developers to read in the following ways:

  • create an extra variable with a descriptive name
  • prefer val over var to avoid accidental mutations
  • and try to make the code 'linear', so the operations can be read from top-to-bottom without jumping between functions
  • avoid code that needs an IDE to see what the type-hints are

And I'll trust that the compiler will make make the code performant.

fun main() {
  val x = 5
  val y = 10

  val newX = y
  val newY = x

  println("X = $newX, Y = $newY")
}

Local function

You could use a local function to perform the swap, as the function will still be able to access the original values.

fun main() {
  var x = 5
  var y = 10

  fun swap(originalX: Int, originalY: Int) {
    y = originalX
    x = originalY
  }

  swap(x, y)

  println("X = $x, Y = $y")
}

Scope function

This could be code-golfed into one line

fun main() {
  var x = 5
  var y = 10

  (x to y).apply { x = second; y = first }

  println("X = $x, Y = $y")
}

One line? Yes. More difficult to read? I think so.

Sign up to request clarification or add additional context in comments.

1 Comment

“Programs must be written for people to read, and only incidentally for machines to execute.” — Abelson & Sussman, Structure And Interpretation Of Computer Programs, preface to the 1st edition
0

I had to swap 2 numbers in one line expression using no other variable except x and y.

Using only two variables can sometimes be reasonable, given extreme constraints (like working solely with a small set of CPU registers, etc.), although that wouldn't typically apply to the use cases for a high-level language like Kotlin.

However, writing it all in one line is definitely not reasonable; it just makes it pointlessly harder to read. Don't do that.


The common way to swap two variables without a temporary is this (as written in Kotlin):

x = x xor y
y = x xor y
x = x xor y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.