How to Find All Combinations of Items in an Array

Javascript - Generating all combinations of elements in a single array (in pairs)

A simple way would be to do a double for loop over the array where you skip the first i elements in the second loop.

let array = ["apple", "banana", "lemon", "mango"];let results = [];
// Since you only want pairs, there's no reason// to iterate over the last element directlyfor (let i = 0; i < array.length - 1; i++) { // This is where you'll capture that last value for (let j = i + 1; j < array.length; j++) { results.push(`${array[i]} ${array[j]}`); }}
console.log(results);

How to get all possible 3 element combinations from an array of n elements in JavaScript?

I think the simplest and most performant way to do it is for loops like this

const data = [5,7,6,1,7,5,4,8,2,4]

const combinations = []

for(let i = 0; i < data.length -2; i++){
for(let j = i + 1; j < data.length -1; j++){
for(let k = j + 1; k < data.length; k++){
combinations.push([data[i],data[j],data[k]])
}
}
}

console.log(combinations)

Javascript - All Possible Combinations From Single Array Every Order

At first create function to find all combinations of array:

function combinations(array) {
return new Array(1 << array.length).fill().map(
(e1, i) => array.filter((e2, j) => i & 1 << j));
}

Then you have to create function to generate all permutations of given array (for example this using Heap's method:

function permute(permutation) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p;

while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push(permutation.slice());
} else {
c[i] = 0;
++i;
}
}
return result;
}

After that you can combine that to final function:

function calculateAllCombinations(myArray) {
var allValues = combinations(myArray)

var response = allValues

for(let v of allValues) {
response = response.concat(permute(v))
}

//Return removed duplicates
return Array.from(new Set(response.map(JSON.stringify)), JSON.parse)

}

At the end you can call it like this:

var myArray = ["apple", "banana", "lemon", "mango"]

var allValues = calculateAllCombinations(myArray)

find all combination of array items upto n number and array item can be repeated

You could take a recursion which returns either an array with the last item with the leftover count or iterate the number of possible counts of the actual element.

Then push the mapped result of new array to the result set.

Result with unique count of items.

PP PP PP PP
PP PP PP PT
PP PP PP CK
PP PP PT PT
PP PP PT CK
PP PP CK CK
PP PT PT PT
PP PT PT CK
PP PT CK CK
PP CK CK CK
PT PT PT PT
PT PT PT CK
PT PT CK CK
PT CK CK CK
CK CK CK CK

const
getCombinations = ([item, ...array], n) => {
if (!array.length) return [Array(n).fill(item)];

const result = [];
let m = n;

do {
const left = Array(m).fill(item);
result.push(...getCombinations(array, n - m)
.map(right => [...left, ...right])
);
} while (m--);

return result;
},
result = getCombinations(["PP", "PT", "CK"], 4);

result.forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to create all combinations for items in an Array?

If the task is not to implement the algorithm which generates the permutations you need, I would recomend to use a library like combinatoricslib3. If you happen to use Guava or Apache Commons in your projects, those have also some methods to generate combinations / permutations from a given collection. With combinatoricslib3 your code could look something like:

import org.paukov.combinatorics3.Generator;

public class Example {

public static void main(String[] args) {
Integer[] array = {1,2,3,4};
Generator.permutation(array)
.simple()
.stream()
.forEach(System.out::println);

//Example with strings

Generator.permutation("apple", "orange", "cherry")
.simple()
.stream()
.forEach(System.out::println);
}
}

output:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 4, 2, 3]
[4, 1, 2, 3]
[4, 1, 3, 2]
....

and

[apple, orange, cherry]
[apple, cherry, orange]
[cherry, apple, orange]
[cherry, orange, apple]
[orange, cherry, apple]
[orange, apple, cherry]

Find all combinations in array that create wanted result

Python has lots of functions for dealing with stuff like this in the intertools module.

import itertools

start=[(1,'S'),(2,'P','S'),(3,'W','C'),(4,'T','C'),(5,'O','T','C'),(6,'O','S'),(7,'O'),(8,'P','O')]
good_values=set('S','P','C','T','O','W')

# Turn the tuples into sets so you can do subtraction
as_set=map(set, start)

# If the set is smaller when you pull some good_values out it is a set you care about
good_sets=[i for i in as_set if len(i - good_values) != len(i)]

# Now just ask Python for the permutations of these sets
itertools.permutations(good_sets)

Use itertools.permutations if you care about getting every possible order of the items that match. Use itertools.combinations if you care about every possible combination at each size that matches and you don't care about order. Use combinations and then permutations on each combination if you need both but it will be very computationally expensive.

How to get all possible combinations of elements in an array including order and lengths

Finally made it recursive !!
Tried to work down on the the original code posted above moving each loop functionality into simple functions.

function getAllCombinations(inputArray) {  var resultArray = [];  var combine = function() {    for (var i in inputArray) {      var temp = [];      var tempResult = [];      for (var j in arguments) {        tempResult.push(inputArray[arguments[j]]);        if (arguments[j] == i) {          temp = false;        } else if (temp) {          temp.push(arguments[j]);        }      }      if (temp) {        temp.push(i);        combine.apply(null, temp);      }    }    if (tempResult.length > 0) {      resultArray.push(tempResult);    }    return resultArray;  };  return combine();}

Find all combinations of just some elements of an array

One approach would be to use a mask to fill the array's non-valid entries with the values in ls, as many times as permutations there are of ls.

However, this can be made more robust by setting the length of these permutations to the amount of non-valid entries in arr. That way we also account for the case len(ls) > (x == None).sum().

The permutations can be obtained using itertools.permutations:

def fill_combs(x, fill, replace=None):
from itertools import permutations
m = x == replace
for i in permutations(fill, int(m.sum())):
x_ = x.copy()
x_[m] = np.array(i)
yield x_.astype(int)

Sample run:

arr = np.array([
[1, None, 3],
[9, 4, None],
])
ls = [9, 8]

list(fill_with_permut(arr, ls))

Output:

[array([[1, 9, 3],
[9, 4, 8]]),
array([[1, 8, 3],
[9, 4, 9]])]

Or for a larger ls:

ls = [3,5,2]
list(fill_with_permut(arr, ls))

[array([[1, 3, 3],
[9, 4, 5]]),
array([[1, 3, 3],
[9, 4, 2]]),
array([[1, 5, 3],
[9, 4, 3]]),
array([[1, 5, 3],
[9, 4, 2]]),
array([[1, 2, 3],
[9, 4, 3]]),
array([[1, 2, 3],
[9, 4, 5]])]

What is the best way to find all combinations of items in an array?

It is O(n!)

static List<List<int>> comb;
static bool[] used;
static void GetCombinationSample()
{
int[] arr = { 10, 50, 3, 1, 2 };
used = new bool[arr.Length];
used.Fill(false);
comb = new List<List<int>>();
List<int> c = new List<int>();
GetComb(arr, 0, c);
foreach (var item in comb)
{
foreach (var x in item)
{
Console.Write(x + ",");
}
Console.WriteLine("");
}
}
static void GetComb(int[] arr, int colindex, List<int> c)
{

if (colindex >= arr.Length)
{
comb.Add(new List<int>(c));
return;
}
for (int i = 0; i < arr.Length; i++)
{
if (!used[i])
{
used[i] = true;
c.Add(arr[i]);
GetComb(arr, colindex + 1, c);
c.RemoveAt(c.Count - 1);
used[i] = false;
}
}
}


Related Topics



Leave a reply



Submit