Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create tuples from an array in JavaScript?

Tags:

node.js

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.

like image 863
Shamoon Avatar asked May 18 '26 22:05

Shamoon


1 Answers

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

like image 156
Trevor Norris Avatar answered May 20 '26 21:05

Trevor Norris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!