TransWikia.com

How to golf wrap-around assignments?

Code Golf Asked by WallyWest on February 5, 2021

This is a relatively simple question. I’m trying to golf a Snake game I’ve written, and I’m trying to work out if there’s a way to golf the following conditional assignments which control x and y coordinates of the snake ensuring a wrap around of the play area:

if (P<0) {
  P = T-1;
}
if (P>T-1) {
  P = 0;
}
if (Q<0) {
  Q = T-1;
}
if (Q>T-1) {
  Q = 0;
}

Is there a simpler way of expressing these, regardless of the value of T?

One Answer

Try the following, it ensures x to be inside [0, n] (say n = 5), only when x > -n and x < 2n.

x = (5 + x) % 5

Thanks to ovs!

Try it online!


As mentioned by xash in the comments, if you want to make it work for any x, then do

x = ((x % 5) + 5) % 5

Try it online!

Answered by vrintle on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP