Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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_]?

share|improve this question
3  
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]). – kirma Mar 2 at 22:03
up vote 8 down vote accepted

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 *)
share|improve this answer
    
if the input is a list of truth values you can also use the built-in function Majority (+1) – kglr Mar 2 at 22:06
    
@kglr Cool, I didn't know that the built-in existed! I should follow my own oft-repeated advice and consult the docs first :-) – MarcoB Mar 2 at 22:08

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}]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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