Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia way of searching tokens in integer arrays

Tags:

julia

Let's say I have buffer=Int[1,2,3,2,3] and token=[2,3]. Is there any preferred way of searching the occurrence of token in buffer to find [2,4] as the answer.

Or, perhaps, is there any split equivalent function for the integer arrays in julia?

(I know how I can perform this operation using 2 nested loops. However, I am especially interested if there is a more Julian way of doing this.)

like image 558
tantuni Avatar asked Mar 15 '23 19:03

tantuni


2 Answers

Because Julia doesn't have conditionals in list comprehensions, I would personally use filter(). Thus if arr = Int64[1,2,3,4,5,2,3,6,2,3,3,2,2]:

filter(x -> arr[x] == 2 && arr[x + 1] == 3, 1 : length(arr) - 1)

=> [2,6,9]

To make it a little more reusable:

pat = [2,3]

filter(x -> arr[x : x + length(pat) - 1] == pat, 1 : length(arr) - length(pat) + 1)

=> [2,6,9]

Julia does have built-ins like find([fun], A), but there's no way that I'm aware of to use them to return indexes of an ordered sublist.

Of course it's arguably more legible to just

ndxs = Int64[]

for i = 1:length(arr)-1
  if arr[i] == 2 && arr[i+1] == 3
    push!(ndxs, i)
  end
end

=> [2,6,9]
like image 78
Chase Ries Avatar answered Mar 28 '23 16:03

Chase Ries


For practice I have also made trial-and-errors and the following patterns have worked for Julia0.4.0. With A = Int[1,2,3,2,3] and pat = Int[2,3], the first one is

x = Int[ A[i:i+1] == pat ? i : 0 for i=1:length(A)-1 ]
x[ x .> 0 ]    # => [2,4]

the second one is

x = Int[]
[ A[i:i+1] == pat ? push!(x,i) : 0 for i=1:length(A)-1 ]
@show x     # => [2,4]

and the third one is

find( [ A[i:i+1] == pat for i=1:length(A)-1 ] )   # => [2,4]

(where find() returns the index array of true elements). But personally, I feel these patterns are more like python than julia way...

like image 27
roygvib Avatar answered Mar 28 '23 15:03

roygvib