1

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.

1
  • Alex deleted an answer well worth voting for :( Commented Jul 15, 2012 at 5:23

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

5

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.