Insert into an array between certain values

Asked

Viewed 263 times

6

I have two values in time format, 20:03:02 and 20:03:35, who are in a array in Lua.

hora_array={"20:03:02", "20:03:35"}

The difference between the two values is 33 seconds (20:03:02 - 20:03:35 = 33).

I want to insert in that same array the values of one in a second, namely 20:03:03, 20:03:04 until it reaches the value 20:03:35 (+ 33 elements in the array).

How can I add a number to a string? The final result of array would be this:

hora_array={"20:03:02","20:03:03","20:03:04","..." "20:03:35"}
  • Could you rephrase the question?

  • I just wanted to add in the array, between the first element and the second element all values until it reaches 20:03:35. That is to always add one more, and insert in the array.

  • okay, come on!!!

1 answer

5


I don’t know if it’s the best way or if you’re totally problem-free but I think this is what you need:

function str2time(hora) 
    return tonumber(string.sub(hora, 1, 2)) * 3600 + tonumber(string.sub(hora, 4, 5)) * 60 + tonumber(string.sub(hora, 7, 8))
end

hora_array = {"20:03:02", "20:03:35"}
horaInicial = str2time(hora_array[1])
horaFinal = str2time(hora_array[2])
hora_array = {}
for i = horaInicial, horaFinal do
    hora = math.floor(i / 3600)
    minuto = math.floor((i - hora * 3600) / 60)
    segundo =  math.floor(i - hora * 3600 - minuto * 60)
    table.insert(hora_array, string.format("%02d:%02d:%02d", hora, minuto, segundo))
end

for i, v in ipairs(hora_array) do print(v) end

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 1

    in how many languages you program, my son? :P

  • 3

    I can program, the language doesn’t matter much. When it’s just a matter of algorithm even if I don’t know a language, just take a look at the documentation. When it’s a language-specific problem, the technologies she uses there I can only do what I work or have worked on. Language doesn’t matter. Making an analogy, I know how to drive cars, it can be any make and model. What matters is knowing how to drive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.