Setras Posted December 20, 2010 Share Posted December 20, 2010 Как-то раздражать начинает "ERROR_TITLE_LENGTH" на форуме - пишешь пишешь пост, жмешь "отправить" и тут он оворит что "слишком длинный заголовок"... Как проверить таблицу на наличие в ней элемента равного определенному значению? Есть к примеру индексированная таблица в которой есть значения по индексу. Как быстро проверить есть ли в таблице элемент равный какому-то определенному значению? Либо, например, в таблице есть словарные(правильно перевел?) таблицы, и нужно проверить нет ли в начальной таблице такого элемента, элемент "х" которого был бы равен определенному значению? (чтоб не перебирать table[1].x table[2].x и т.п. какой-нибудь функцией типа for i, v in table do if i.x == CertainValue then return true end end) Надеюсь свой вопрос сформулировал правильно. Quote Link to comment Share on other sites More sharing options...
Ciuine Posted December 20, 2010 Share Posted December 20, 2010 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 Quote Link to comment Share on other sites More sharing options...
SLA Posted December 21, 2010 Share Posted December 21, 2010 Имхо, нет такого способа. Придётся перебирать весь массив: Code: local Found = falsefor _,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. Quote Link to comment Share on other sites More sharing options...
Setras Posted December 21, 2010 Author Share Posted December 21, 2010 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". Quote Link to comment Share on other sites More sharing options...
duvo Posted December 21, 2010 Share Posted December 21, 2010 По-моему, если 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". ,то двоичный поиск -- то, что доктор прописал. Я в программировании шарю не очень, так что не обессудьте Quote Link to comment Share on other sites More sharing options...
Nikon Posted December 21, 2010 Share Posted December 21, 2010 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 Quote Link to comment Share on other sites More sharing options...
SLA Posted December 21, 2010 Share Posted December 21, 2010 Как вариант, возможно (если скорость поиска гораздо важнее объема памяти), можно попробовать, параллельно с первой таблицей, создавать вторую, в которой ключами были бы значения из первой таблицы. Code: MyTable [ MyIndex ] = MyValueSpecialSearchTable [ MyValue ] = true ... if SpecialSearchTable [ MyValue ] then ............ Но это нужно сначала протестировать, будет ли такой способ действительно быстрее. К тому же, это уже утопия Цикл FOR достаточно быстр, имхо, чтобы что-то вот так усложнять. P.S. Интересно, каким методом Lua ищет ИНДЕКС в таблице. Quote Link to comment Share on other sites More sharing options...
SLA Posted December 21, 2010 Share Posted December 21, 2010 Есть готовые решения на Lua: 1) http://lua-users.org/wiki/BinarySearch 2) http://lua-users.org/wiki/InterpolatingSearch Quote Link to comment Share on other sites More sharing options...
Nikon Posted December 21, 2010 Share Posted December 21, 2010 Кстати, ЛУА с массивами работает не сильно медленнее, чем С, к примеру А вот обработка таблиц уже идет медленнее Таблица остается массивом, пока с ее индексами никто ничего не химичит (те, все нормально, пока элементы добавляются через table.insert, удаляются через table.remove) Где то там Quote Link to comment Share on other sites More sharing options...
Ciuine Posted December 21, 2010 Share Posted December 21, 2010 Ah, I think the original post might have changed after or during my reply, or I just outright misread it. Either way, the question makes more sense now, since its in English underneath this and seems like it has been answered. Quote Link to comment Share on other sites More sharing options...
Setras Posted December 21, 2010 Author Share Posted December 21, 2010 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts