4
$\begingroup$

I came across the majority function while falling into a Wikipedia link rabbit hole (I wish I could remember how I got there...)

The function is defined for $n$ arguments and given by $$\mathrm{maj}(x_1,\ldots,x_n)=\left\lfloor\frac{1}{2}+\frac{\sum\limits_{i=1}^n x_n-\frac{1}{2}}{n}\right\rfloor$$ It's easy enough to define the function for a predefined list. For example, given the list

t = RandomInteger[{0, 1}, 10]
(* {0, 0, 1, 1, 1, 0, 0, 1, 1, 1} *)

I can compute the "majority" with

Floor[1/2 + (Sum[t[[i]], {i, 1, Length[t]}] - 1/2)/Length[t]]
(* 1 *)

Is there a way to define $\mathrm{maj}$ in a way similar to, say, f[x_, y_]?

$\endgroup$
  • 3
    $\begingroup$ If you are interested of the Boolean-valued majority function, you don't need to look further than Majority (which is a special case of BooleanCountingFunction). Consider Majority@@(# == 1 & /@ IntegerDigits[num, 2]). $\endgroup$ – kirma Mar 2 '16 at 22:03
8
$\begingroup$

You can use Total instead of your Sum:

Clear[maj]
maj[list_?VectorQ] := Floor[1/2 + (Total[list] - 1/2)/Length[list]]

maj[{0, 0, 1, 1, 1, 0, 0, 1, 1, 1}]
(* Out: 1*)

If you want to work with truth values, the Majority function is built-in (thanks to @kglr for pointing that out!).

If you'd like, however, you can write your own by applying the definition directly:

majBoole[list_?VectorQ] := Count[list, True] >= Length[list]/2

majBoole[{0, 0, 1, 1, 1, 0, 0, 1, 1, 1} /. {1 -> True, 0 -> False}]
(* Out: True *)
$\endgroup$
  • $\begingroup$ if the input is a list of truth values you can also use the built-in function Majority (+1) $\endgroup$ – kglr Mar 2 '16 at 22:06
  • $\begingroup$ @kglr Cool, I didn't know that the built-in existed! I should follow my own oft-repeated advice and consult the docs first :-) $\endgroup$ – MarcoB Mar 2 '16 at 22:08
5
$\begingroup$

Since you asked for a form like f[x_, y_], one can define a pure function which takes an arbitrary number of arguments using SlotSequence:

maj = Floor[1/2 + (Total[{##}] - 1/2)/Length[{##}]] &;
maj[1, 0, 0, 1, 1, 1, 1, 0, 0, 1]
(* 1 *)

Alternatively, using BlankSequence:

maj[ins__] := Floor[1/2 + (Total[{ins}] - 1/2)/Length[{ins}]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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