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
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this community(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.
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))))
seqs))
seq-count
and is not informative.