How can I test whether an array mfselc is composed of zeroes or all zeroes except for a single value being 1.

Thus mfselc [0 0 1 0 0 0] is acceptable

Also mfselc [0 0 0 0 0 0] is acceptable

But mfselc [0 1 1 0 0 0] is not acceptable

2 Answers 2

(defun acceptable-p (zeros-and-ones-array)
  "Test ZEROS-AND-ONES-ARRAY for comprising at most one 1.
All elements are either 0 or 1."
  (<= (reduce #'+ zeros-and-ones-array) 1))

reduce applies the same function cumulatively to each element of a sequence. It's a solution that should leap to mind whenever you see a problem where you want a single-thing output from a collection of some kind. So what we're doing here is summing the elements of the array (by cumulatively applying the function called +) and then testing that the resulting sum is no more than 1.

  • 1
    Thanks for jumping in with this elegant solution! I saw reduce being heavily used in some Clojure book before, but I don't have much experience with it. And somehow I failed to conclude that the question 'implies' that the arrays are only composed of zeros and ones. Anyway, this certainly is an 'affirmative answer to the question 'Can a solution be made more readable?' I think it is generally recommended to prefix reduce with seq- (or cl-) b.t.w. Nov 15, 2022 at 21:27

You can get the number of occurrences of a certain element in a sequence using seq-count. You can check if all elements are the same using seq-every-p:

(let ((seqs '([0 0 0]
              [0 0 1]
              [0 1 1])))
  (mapcar (lambda (seq)
            (unless (> (seq-count (apply-partially #'= 1) seq) 1)
              (seq-every-p #'zerop (seq-remove (apply-partially #'= 1) seq))))
  • This is quite an esoteric solution. Can a solution be made more readable?
    – Dilna
    Nov 15, 2022 at 16:22
  • Ah, I see now that I did not read the question correctly. Nov 15, 2022 at 16:49
  • Have looked at the documentation for seq-count and is not informative.
    – Dilna
    Nov 15, 2022 at 17:01
  • The docstring of 'seq-count` is as clear as it can be. However, you should look up what 'predicate' means in lisp. Nov 15, 2022 at 17:09
  • You have over-complicated even more.
    – Dilna
    Nov 15, 2022 at 18:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.