1

I have an array of team names which is like this:

teams = ['team1', 'team2', 'team3', 'team4']

I want to create a set of matches based on this, so at the moment, for a set of matches using the teams array you would get:

teamMatches : [
  [ teams[0],  teams[1] ],
  [ teams[2],  teams[3] ]
]

My question is, can anyone think of a way to produce this teamMatches array based upon a teams array with length n. The teams array will always be a correct number, 4,8,16 etc. I have tried using Math.pow with 2 to try to produce the brackets with no success.

Any ideas?

2 Answers 2

3

A procedural solution:

xs = [0,1,2,3,4,5,6,7,8,9]
result = []
n = 2 // n=3 gives a list of triples, etc
for(var i = 0; i < xs.length; i += n)
    result.push(xs.slice(i, i + n))

A functional programming solution:

function zip() {
    var args = [].slice.call(arguments, 0);
    return args[0].map(function(_, n) {
        return args.map(function(a) {return a[n] })
    })
}

xs = [0,1,2,3,4,5,6,7,8,9]
result = zip(
    xs.filter(function(_, n) { return n % 2 == 0 }),
    xs.filter(function(_, n) { return n % 2 != 0 })
)
// [[0,1],[2,3],[4,5],[6,7],[8,9]]

Explanation: zip is a function (built-in in some programming languages, but not in Javascript) that takes N arrays and groups together elements at the same position:

zip([1,2,3], [10,20,30]) -> [ [1,10], [2,20], [3,30] ]

We split an array into even and odd parts:

[0,2,4,6...]
[1,3,5,7...]

and zip them together, getting a list of ordered pairs.

Sign up to request clarification or add additional context in comments.

4 Comments

shouldn't it be javascript though?
@meewoK: eh? this is javascript.
Ah..you implemented Zip function in javascript. Nice one.
@alex23: by convention, _ denotes unused/ignored parameters, a kind of placeholder.
1

How about this

var teams = ['team1', 'team2', 'team3', 'team4'];
var teamMatches = new Array();
for(var i=0;i<teams.length; i+=2)
{       
  teamMatches.push([teams[i],teams[i+1]]);
}

2 Comments

I like this due to its simplicity so thanks, didn't think the answer was as simple as this so maybe I was overthinking it. This should work for an array of size 4/8/16 etc as well shouldn't it?
This is great. The question was actually much simpler than everyone thought at first. The questioner was not looking for some over complex round robit, etc algorithm.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.