Home > Back-end >  Get a sequence number from 0 and alternate positive/negative incrementing every other time
Get a sequence number from 0 and alternate positive/negative incrementing every other time

Time:10-28

I would like to be able to obtain a (non-convergent) sequence of numbers by a simple calculation that would look like this: 0, 1, -1, 2, -2, 3, -3, 4, -4 ...

By simple calculation I mean being able to do it with a single variable that would start from 1 (or 0) without having to rearrange this sequence.

I made several (unsuccessful) attempts in Lua, here is what it should look like in principle (this example only alternates 0s and 1s):

do
    local n = 0
    for i = 1, 10 do print(n)
        n = n==0 and 1 or -n   (n/n)
    end
end

Is this possible and how?

Update:

I just succeeded like this:

local n, j = 0, 2
for i = 1, 10 do print(n)
    n = n==0 and 1 or j%2==0 and -(n (n/math.abs(n))) or -n
    j = j   1
end

But I have to help myself with a second variable, I would have liked to know if with only n it would be possible to do it?

CodePudding user response:

Simply "emit" both n and n * -1 in each iteration:

for n = 0, 10 do
  print(n)
  print(n * -1)
end

CodePudding user response:

The whole numbers are enumerable. Thus there exists a mapping from the natural numbers to whole numbers. You'll now have to use a loop to loop over natural numbers, then compute a function that gives you a whole number:

-- 0, 1...10, -1...-10 -> 21 numbers total
for n = 1, 21 do
    local last_bit = n % 2
    local sign = 1 - (2 * last_bit)
    local abs = (n - last_bit) / 2
    print(sign * abs)
end

prints

-0
1
-1
2
-2
...
10
-10

on Lua 5.1; on newer Lua versions, you can use n // 2 instead of (n - last_bit) / 2 to (1) use ints and (2) make extracting the abs cheaper.

  • Related