Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to create tuples from an array in JavaScript?

How to create tuples from an array in JavaScript?

Problem

IF I have an array, names = ['Jon', 'Stewart', 'Oliver'], I want to get all 3-tuples and 2-tuples:

Jon, Stewart, Oliver
Jon, Stewart
Stewart, Oliver
Oliver, Jon

What algorithm can I use for this? The array can also be VERY large (200+ items), so whatever code I use should be asynchronous in nature.

Problem courtesy of: Shamoon

Solution

I think you might be confusing "asynchronous" here. The process of creating the tuples will always block. So possibly what you'll want to do is create an algorithm that only generates a tuple when it's required, based on some parameters, then cache it for later.

Since you've tagged this as node.js I'm going to assume that's the programming language of interest. Based on that assumption, and the assumption that you actually don't want this to be blocking, your best bet is to spawn multiple processes and pipe out the process creating these tuples. Here's a very rough example script (emphasis on rough):

var cluster = require('cluster');
var names = ['Jon', 'Stewart', 'Oliver'];

if (cluster.isWorker) {
  var count = +process.env.tupple_count;
  var tuples = [];

  // Process tuple here, then return it.

  process.send(JSON.stringify(tuples));
  return;
}

cluster.fork({ tupple_count: 2 }).on('message', function(msg) {
  // Receive tuple here:
  var tuple = JSON.parse(msg);
  console.log(tuple);
});

// Go about my life.

Then you could write a general algorithm to return these. Here's a good link on how to do this: Algorithm to return all combinations of k elements from n

Solution courtesy of: Trevor Norris

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to create tuples from an array in JavaScript?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×