Cheluis
Cheluis

Reputation: 1412

Clojure sub arrays

I'm trying to learn Clojure and Functional Programming in general, and for this I'm tring to resolve exercises from Codingbat. I'm stuck when I have to find a subarray [1 2 3] from another sub array. from the page:

Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.

I would love, not the answer per se, but the ideas of how could I solve. Well, that's almost equal to the answer but any idea will be fine.

Thanks.

Upvotes: 1

Views: 1148

Answers (2)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

take it from thinking in "items in the array" to functions that take sequences and return sequences. This decomplexts the task of matching and deciding if what you matched solves your problem. (Im fairly sure that decomplect is ONLY in the Clojure dictionary)

in general:

  • from the input data create a sequence that will contain what you are looking for: autotestbed.core> (partition 3 1 (range 10))
    ((0 1 2) (1 2 3) (2 3 4) (3 4 5) (4 5 6) (5 6 7) (6 7 8) (7 8 9))
  • then from that sequence extract just the parts that fit your criteria:
    (filter your-predicate-here (partition ...)
  • then decide if your answer has been found: (some true? ....)

in larger example some people would choose to devide this into several functions and then compose them.


To address your original question: (for thous whom google brings from the question title)

the subvec function returns subvectors in order-1 time

user>(subvec (vec (range 1000)) 10 20)
[10 11 12 13 14 15 16 17 18 19]

Upvotes: 5

Jonas
Jonas

Reputation: 19642

With a combination of some and partition:

(some #{[1 2 3]} (partition 3 1 some-collection))

Note that the above does not return a boolean result (but it can still be used as test in conditionals). If you really want a boolean result you can use boolean

Upvotes: 7

Related Questions