Hello, I am not really making a game right now or having problems or anything, just curious. How would I go about finding an ordered set of numbers in a table? For example
local table = {8,2,4,6}
while task.wait() do
table.insert(table,math.random(1,5))
end
If this kept running, and the table has 1, 2, 3 in order anytime, how would I go about checking this? For example 8, 2, 4, 6, 1, 2, 3. It has 1, 2, 3 in the table order, how would I check this? Thanks!
Your table is named table. Need I tell you how bad of an idea that is? It overrides the global table, which means that your table will never grow. Here is your script with the code added and the table renamed:
local nums = {8,2,4,6}
while task.wait() do
table.insert(nums, math.random(1,5))
local found = table.find(nums, 1)
if found and nums[found + 1] == 2 and nums[found + 2] == 3 then
print("Found 1, 2, 3 starting at " .. found)
break
end
end
You can solve this using the sliding window algorithm which runs in linear time as opposed to quadratic time. The solution listed above is O(n^2) which is decent but can be refined.
The algorithm works by making a window of sorts to start on an index and end on another index. Inside of that window we would check the starting index which will be 1 and our ending index which would be 3.
local arr = {8,9,2,3,1,2,3}
local start, windowEnd = 1, 1
local max = #arr
local foundIndices = {}
while end < max do
task.wait()
if arr[start] == 1 then
foundIndices[arr[start]] = start
windowEnd += 1
if arr[windowEnd] == arr[start] + 1 or arr[windowEnd] == arr[windowEnd] + 1 then
foundIndices[arr[windowEnd]] = windowEnd
if #foundIndices == 3 then
break
end
else
foundIndices = {}
start += 1
windowEnd = start
end
end
local arr = {8,9,2,3,1,2,3}
local start, windowEnd = 1, 1
local max = #arr
local foundIndices = {}
while end < max do
task.wait()
if arr[start] == 1 then
foundIndices[arr[start]] = start
windowEnd += 1
if arr[windowEnd] == arr[start] + 1 or arr[windowEnd] == arr[windowEnd] + 1 then
foundIndices[arr[windowEnd]] = windowEnd
if #foundIndices == 3 then
break
end
else
foundIndices = {}
start += 1
windowEnd = start
end
end
end
I need a new spacebar. (Yes, I indented that by hand. Yes, you missed an end.)
Does this one look/do better? It also should be more efficient.
local nums = {8,2,4,6}
while task.wait() do
table.insert(nums, math.random(1,5))
local l = #nums
print("[" .. l .. "] = " .. nums[l])
if nums[l] == 3 and nums[l - 1] == 2 and nums[l - 2] == 1 then
print("Found 1, 2, 3 starting at " .. found)
break
end
end
local nums = {8,2,4,6}
while task.wait() do
table.insert(nums, math.random(1,5))
local l = #nums
print("[" .. l .. "] = " .. nums[l])
if nums[l] == 3 and nums[l - 1] == 2 and nums[l - 2] == 1 then
print("Found 1, 2, 3 starting at " .. l-2)
break
end
end
Why are you trying to do this again? This seems like an x-y problem.