Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate all possible combinations

Preface

Consider a list, array or string of 12 elements, of an irrelevant value (lets say E). Each element can be linked to, at most, one other adjacent element, or if it is the last element of the list, it can be linked to the first element.

Examples of valid lists, where dashes indicate links, and "E" represents an element.

E E E E E E E E E E E E 
E E-E E-E E E E-E E-E E
E E E-E E E-E E-E E E E-

An example of an invalid list.

E-E-E E E E E-E E E E E-

Question

I want to calculate the total number of unique lists, and print them.

To approach this problem, what might be the best way to represent the data?

Would it be best to implement a data structure specific to this problem?

I am looking to implement this in Java, but if you believe that a different language is better suited, I am open to suggestions.

Why

This is NOT a homework question.

The idea is to find every rhythmic pattern in a bar of 12/8 consisting of only single and double groupings of eighth notes, of which can be tied across a barline.

like image 793
Mike M Avatar asked Nov 02 '12 04:11

Mike M


1 Answers

Calculating the number of possibilities here actually has an incredibly neat solution (in my opinion).

Notice that for n notes, the number of possible connections ( C(n) ) if the first note is connected to the second is C(n-2). Otherwise it is C(n-1). This means that

C(n) = C(n-1) + C(n-2)
C(1) = 3 //Either the first and second are connected, 
         //neither are connected, or the end is connected.
C(0) = 2 //Either the end is connected or it isn't

Note: If the last note in a single note example can be connected "to itself" G(0) is 1 Otherwise, it is 0. In addition I am unclear whether E-E and E E- are separate, if they aren't then, C(1) is 2 not 3. Note these only apply for sequences of 0 or 1 on their own you'd have to have an if statement outside of the actual function C(n) to return 1 instead of 2. Otherwise it screws up the whole recurrence. A bit messy, but that's the nature of real world data in algorithms

This means you've basically got a variant on the fibonacci series! Cool right?

Data Representation

I would have a list of n booleans. An array would work fine. If 2 notes are connected, then that entry in the array should be true. I would have index 0 be the connection be the first and second notes, and index n-1 be whether or not the last note is connected to anything.

Permutation Generation

The way in which we calculate the total number of possibilities lends itself nicely to a generation method (G(n)). For n we need to tack on E-E to G(n-2) and E to G(n-1).

At the base of this recurrence we have:

G(0) = {E, E-} 
G(1) = {E-E, E E, E E-}
like image 59
Daniel Gratzer Avatar answered Oct 04 '22 21:10

Daniel Gratzer