Jump to content
Alloder.pro  about Allods with love 😱
Search In
  • More options...
Find results that contain...
Find results in...

Servers monitoring and the Addons Editor

We present you two legends. All dreams come true.

Servers monitoring The Addons Editor

Digest April

We talk about what was done and updated in the past month. We help keep abreast of events.

Read more

Game tooltips

Tooltips provide a way for 3rd party fansites and extensions to display detailed information on mouseover.

Read more

Есть ли в таблице элемент равный х?


Setras
 Share

Recommended Posts

Как-то раздражать начинает "ERROR_TITLE_LENGTH" на форуме - пишешь пишешь пост, жмешь "отправить" и тут он оворит что "слишком длинный заголовок"...

Как проверить таблицу на наличие в ней элемента равного определенному значению?

Есть к примеру индексированная таблица в которой есть значения по индексу.

Как быстро проверить есть ли в таблице элемент равный какому-то определенному значению?

Либо, например, в таблице есть словарные(правильно перевел?) таблицы, и нужно проверить нет ли в начальной таблице такого элемента, элемент "х" которого был бы равен определенному значению? (чтоб не перебирать table[1].x table[2].x и т.п. какой-нибудь функцией типа for i, v in table do if i.x == CertainValue then return true end end)

Надеюсь свой вопрос сформулировал правильно.

Link to comment
Share on other sites

HealthDb uses a good example of what this question is asking. The table.value concept is what I believe you are talking about. The .value equals the value inside table. Then you just ask == some value against that value.

Google Translate:

HealthDb использует хороший пример того, что этот вопрос задает. table.value концепции то, что я думаю, что вы говорите. .value равно значению внутри таблицы. Тогда вы просто спросите == некоторое значение в отношении этого значения.

Example:

Code:
params = {value = 1,}

if params.value == 2 then do stuff end

if params.value == 1 then do other stuff end

Link to comment
Share on other sites

Имхо, нет такого способа. Придётся перебирать весь массив:

Code:
local Found = false

for _,v in MyTable do

    if v == MyValue then

        Found = true

        break

    end

end

if Found then .........

@Ciuine:

No, he asked, if there is any quick method to determine, whether there is a certain VALUE in the table. I told him, no, he have to use the FOR cicle to find it.

Link to comment
Share on other sites

Sure, i wanted to find a better way to know if there IS some VALUE in the table or not.

Like we have table = {1, 2, 54, 7, 48, 23} and we ask "is there a value equal to 48??" "Yes" or "Is there a value equal to 49?" "No, there is not".

Link to comment
Share on other sites

По-моему, если

Quote:
we have table = {1, 2, 54, 7, 48, 23} and we ask "is there a value equal to 48??" "Yes" or "Is there a value equal to 49?" "No, there is not".
,

то двоичный поиск -- то, что доктор прописал.

Я в программировании шарю не очень, так что не обессудьте :)

Link to comment
Share on other sites

Quote:
классический алгоритм поиска элемента в отсортированном массиве (векторе)

Т.е., массив д.б. предварительно отсортирован, а тот заполнен рандомно
Будет сортировка + 2-й поиск быстрее чем простой перебор?

Quote:
Like we have table = {1, 2, 54, 7, 48, 23} and we ask "is there a value equal to 48??" "Yes" or "Is there a value equal to 49?" "No , there is not".

How we learn it? Only simple search of all values of an array
Link to comment
Share on other sites

Как вариант, возможно (если скорость поиска гораздо важнее объема памяти), можно попробовать, параллельно с первой таблицей, создавать вторую, в которой ключами были бы значения из первой таблицы.

Code:
MyTable [ MyIndex ]  = MyValue

SpecialSearchTable [ MyValue ]  = true

...

if SpecialSearchTable [ MyValue ]  then ............

Но это нужно сначала протестировать, будет ли такой способ действительно быстрее.

К тому же, это уже утопия :) Цикл FOR достаточно быстр, имхо, чтобы что-то вот так усложнять.

P.S. Интересно, каким методом Lua ищет ИНДЕКС в таблице.

Link to comment
Share on other sites

Кстати, ЛУА с массивами работает не сильно медленнее, чем С, к примеру

А вот обработка таблиц уже идет медленнее

Таблица остается массивом, пока с ее индексами никто ничего не химичит (те, все нормально, пока элементы добавляются через table.insert, удаляются через table.remove)

Где то там

Link to comment
Share on other sites

IMO the simple "for k, v" is best here, coz other stuff is kinda "fuck my brain!"...

I was creating this post with a simple thought: "what if there is some simple search(table, value) function and i don't know about it?", but it seems that there is none.

Link to comment
Share on other sites

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

By using our site you agree to the Terms of Use