ちょっと複雑になりすぎたのでFindItemをつかってAのネスト化された配列の中にBの配列があるかどうかを比較するにはどうすればいいかな
- User
ちょっと複雑になりすぎたのでFindItemをつかってAのネスト化された配列の中にBの配列があるかどうかを比較するにはどうすればいいかな
Assistant
findItemを使ってネスト配列内の配列を探す場合、いくつか注意点があります。以下、段階的に解説します:
1. 基本的な
findItemの挙動findItemは第1階層のみを検索し、ネストされた要素の中身までは見ません:A = #(1, 2, #(3, 4), 5) B = #(3, 4) -- 直接的な検索 result = findItem A B print result -- => 3 (3番目の要素として見つかる) -- これは見つからない C = #(4) result2 = findItem A C print result2 -- => 0 (見つからない)
2. ネスト配列を再帰的に検索する関数
深い階層まで検索したい場合は、カスタム関数が必要です:
fn findNestedArray haystack needle = ( -- 第1階層で検索 local idx = findItem haystack needle if idx > 0 do return idx -- 再帰的に検索 for i = 1 to haystack.count do ( if classof haystack[i] == Array then ( if findNestedArray haystack[i] needle > 0 do return i -- 見つかった階層のインデックスを返す ) ) 0 -- 見つからない ) -- 使用例 A = #(1, #(2, #(3, 4)), 5) B = #(3, 4) result = findNestedArray A B print result -- => 2 (2番目の要素の中に存在)
3. 配列の内容を比較する簡易版
配列の参照ではなく内容で比較したい場合:
fn arrayEquals a b = ( if a.count != b.count do return false for i = 1 to a.count do if a[i] != b[i] do return false true ) fn findArrayByContent haystack needle = ( for i = 1 to haystack.count do ( if classof haystack[i] == Array then ( if arrayEquals haystack[i] needle do return i ) ) 0 ) -- 使用例 A = #(1, #(2, 3), #(4, 5)) B = #(2, 3) result = findArrayByContent A B print result -- => 2
4. 実用的な検索関数(パス付き)
どの階層で見つかったかも知りたい場合:
fn findArrayPath haystack needle path:#() = ( for i = 1 to haystack.count do ( local elem = haystack[i] local currentPath = path + #(i) if classof elem == Array then ( -- 内容が一致するか確認 if elem.count == needle.count and (and (elem == needle)) then return currentPath -- 再帰的に検索 local subResult = findArrayPath elem needle path:currentPath if subResult != undefined do return subResult ) ) undefined ) -- 使用例 A = #(1, #(2, #(3, #(4, 5))), 6) B = #(4, 5) path = findArrayPath A B if path != undefined then format "Found at path: %\n" path -- => #(2, 2, 1) else print "Not found"
5. シンプルな存在確認だけなら
存在するかどうかだけ知りたい場合の最もシンプルな方法:
fn containsArray haystack needle = ( for item in haystack do ( if classof item == Array and item.count == needle.count then ( if (and (item == needle)) do return true ) ) false ) -- 使用例 A = #(1, #(2, 3), 4) B = #(2, 3) C = #(5, 6) print (containsArray A B) -- => true print (containsArray A C) -- => false
まとめ
- 単純な
findItemは第1階層のみ検索 - ネスト検索 にはカスタム関数が必要
- 配列の内容比較 には
and (arr1 == arr2)が便利 - 用途に応じて、インデックス返却/パス返却/真偽値返却を選択
最もシンプルな「存在確認」なら、最後の
containsArray関数がおすすめです!- 単純な
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.