Skip to content

Instantly share code, notes, and snippets.

@aiya000
Created October 18, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aiya000/5b15f2a757b33871c4c72f74086b76c3 to your computer and use it in GitHub Desktop.
Save aiya000/5b15f2a757b33871c4c72f74086b76c3 to your computer and use it in GitHub Desktop.

negatable index to positive index

mearning

[1, 2, 3][-2] == 2
[1, 2, 3, 4, 5][-4] == 2
[1, 2, 3, 4, 5][-2] == 4

Let's check the f.

f([1, 2, 3], 1)        = 1
f([1, 2, 3], -2)       = 1
f([1, 2, 3, 4, 5], -4) = 1
f([1, 2, 3, 4, 5], -2) = 3

if the second argument is positive, simply return it, or return (len(xs) + x) % len(xs) if it is negative.

Implementation v

f(xs, x) = x  (if x is positive)
f(xs, x) = `(len(xs) + x) % len(xs)` (if x is negative)

e.g.

(5 - 2) % 5 = 4 % 5 = 4
(5 - 4) % 5 = 2 % 5 = 2
(3 - 2) % 3 = 2 % 3 = 2

(3 + 1) % 3 = 5 % 3 = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment