标签: cartesian-product

在JavaScript中创建组合

可以说我在Javascript中有几组选项

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];
Run Code Online (Sandbox Code Playgroud)

什么是一种有效的算法,可以在这样的数组中获得这些选项的所有组合

["red and small and heavy", "red and small and light", "red and medium and heavy" ...]
Run Code Online (Sandbox Code Playgroud)

这是一个警告

此功能必须能够采用任意数量的选项

我有一种感觉,这样做的正确方法是通过某种树遍历,但现在还没有完全考虑到这一点,我还没有喝咖啡

javascript algorithm combinations cartesian-product

3
推荐指数
1
解决办法
2824
查看次数

C++ Cartesian产品迭代器在第一次迭代时调用基类函数

我正在研究一组n维笛卡尔积类型,基于这个解决方案.

对于相同的基本算法集,我有许多不同的数据类型,我想"啊哈!我将使用模板来减少我的整体工作!" 而且,到目前为止,它一直很棒.我正在使用Boost的iterator_facade.

我的问题是我使用的派生类map<char, boost::integer_range<int> >.每次迭代产生一个map<char,int>,但我排除第二个值为0的对,因为就我的算法而言,它们只是浪费空间.

派生类重载生成迭代器的返回值的函数,并且它可以工作.但是,在第一次迭代期间,将调用基类的生成器.我很困惑.有没有人有任何想法?

以下是相关的代码段:


#include <boost/container/flat_map.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/irange.hpp>
#include <utility>
#include <iostream>

using namespace boost;
using namespace boost::tuples;
using namespace std;

template <class Container2DMap,
    class return_type = boost::container::flat_map<typename Container2DMap::value_type::first_type,
    typename Container2DMap::value_type::second_type::value_type> >
class CartProductIterator2DMap : public boost::iterator_facade<
CartProductIterator2DMap<Container2DMap, return_type>,
const return_type,
boost::forward_traversal_tag> {
public:
    typedef typename Container2DMap::value_type::first_type first_type;
    typedef typename Container2DMap::const_iterator first_iterator;
    typedef typename Container2DMap::value_type::second_type::value_type second_type;
    typedef typename Container2DMap::value_type::second_type::const_iterator second_iterator;

    CartProductIterator2DMap(const Container2DMap &container) {
        rangeIterSetup(container);
    } …
Run Code Online (Sandbox Code Playgroud)

c++ templates derived-class cartesian-product

3
推荐指数
1
解决办法
714
查看次数

使用enumeratos的C#中的笛卡尔积

我正在尝试实现C#排列的一系列arraylists问题中找到的解决方案之一 它应该执行笛卡尔积,但它返回正确数量的列表,但每个列表始终只是每个数组的第一个.代码和结果如下.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace TestCartProd
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string[][] myList = new string[3][];
            myList[0] = new string[] { "1", "5", "3", "9" };
            myList[1] = new string[] { "2", "3" };
            myList[2] = new string[] { "a", "93" };

            List<IEnumerable<string>> v = GetPermutations (myList).ToList();

            foreach (IEnumerable t in v) {
                foreach (string u in t) {
                    Console.Write (u);
                }
                Console.WriteLine ();
            } …
Run Code Online (Sandbox Code Playgroud)

c# ienumerable cartesian-product

3
推荐指数
1
解决办法
1560
查看次数

字典的笛卡尔积

我正在尝试编写一些 python 代码来获得以下输出(所有排列)。region和的值gender是概率,result反映给定事件组合的乘积。

似乎可以通过使用itertoolsand来实现apply,但我不太清楚具体的实现。

输入:

region = {'east': 0.5, 'north': 0.20, 'south': 0.10, 'west': 0.20}
gender = {'female': 0.70, 'male': 0.30}
Run Code Online (Sandbox Code Playgroud)

期望的输出:

result = {('east','female'):0.35, 
('east','male'):0.15,
('north','female'):0.14,
('north','male'):0.06,
('south','female'):0.07,
('south','male'):0.03,
('west','female'):0.14,
('west','male'):0.06}
Run Code Online (Sandbox Code Playgroud)

python dictionary cartesian-product

3
推荐指数
1
解决办法
976
查看次数

itertools 产品使用太多内存

我只有两个句子我想产生变化并计算 leveshtein 距离,但是当我尝试使用 itertools 产生这个列表时,即使我的 64GB RAM 机器也会超载。

有没有办法限制这一点,即使我必须将其限制为一定数量的组合。

到目前为止,这是我的代码:

from __future__ import print_function
import itertools
import sys

in_file = sys.argv[1]
X = []


with open(in_file) as f:
        lis = list(f)
X.append([' '.join(x) for x in itertools.product(*map(set, zip(*map(str.split, lis))))])

for x in X:
        print x
Run Code Online (Sandbox Code Playgroud)

python cartesian-product python-itertools

3
推荐指数
1
解决办法
1582
查看次数

查找数组数组的笛卡尔积的时间复杂度

final class Combination {

    public static void findCombinations(String[][] sets) {
        int combinations = 1;
        for(int i = 0; i < sets.length; combinations *= sets[i].length, i++);
        for(int i = 0; i < combinations; i++) {
            int j = 1;
            for(String[] set : sets) {
                System.out.print(set[(i/j)%set.length] + " ");
                j *= set.length;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
         findCombinations(new String[][]{{"a","b","c"}, {"d","e","i"}, {"f","g","h"}});
    }
  }
Run Code Online (Sandbox Code Playgroud)

我的答案是这样的

   a d f 
   b d f 
   c d f 
   a e f 
   b …
Run Code Online (Sandbox Code Playgroud)

java performance cartesian-product time-complexity

3
推荐指数
1
解决办法
1991
查看次数

如何将 TypeScript 可变元组类型用于笛卡尔积函数?

TypeScript 4.0 开始支持Variadic Tuple Types的概念,这是一种很好的类型构造,可以在连接函数等中使用。文档中的一个示例:

type Arr = readonly any[];

function concat<T extends Arr, U extends Arr>(arr1: T, arr2: U): [...T, ...U] {
  return [...arr1, ...arr2];
}
Run Code Online (Sandbox Code Playgroud)

我感兴趣的是这种类型构造是否可用于键入笛卡尔积函数。然后,该函数应从参数推断(混合)类型以生成其返回类型。因此,如果我输入,[number[], string[]]我希望输出的类型为[number, string][]. 在此线程中可以找到笛卡尔积的多个实现,但没有一个是严格类型化的。这是一个例子:

const cartesian =
  (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
Run Code Online (Sandbox Code Playgroud)

我当前使用的实现不使用可变元组类型,并且需要显式类型转换:

const cartesian = <T extends any[]>(...arr: any[][]): T[] =>
  arr.reduce<T[]>(
    (a, b) => a.flatMap<T>(c => b.map<T>(d => [...c, d] as T)),
    [[]] as T
  );

const …
Run Code Online (Sandbox Code Playgroud)

cartesian-product typescript typescript4.0 variadic-tuple-types

3
推荐指数
1
解决办法
1325
查看次数

通过添加第一个和第二个数组的元素来填充第三个数组

我想生成一个数组,其内容代表两个给定字符串数组的笛卡尔积。

换句话说,我需要将String第一个数组中的每个arr1String第二个数组中的每个连接起来arr2

这是我的代码:

String[] arr1 = {"a", "b", "c"};
String[] arr2 = {"d", "e", "f"};

String[] result = new String[arr1.length * arr2.length];

for (int k = 0; k < result.length; k++) {
    for (int i = 0; i <arr1.length; i++) {
        for (int j = 0; j < arr2.length; j++) {
            result[k] = arr1[i] + arr2[j];
        }
    }
}

System.out.println(Arrays.toString(result));
Run Code Online (Sandbox Code Playgroud)

电流输出:

[cf, cf, cf, cf, cf, cf, cf, cf, cf]
Run Code Online (Sandbox Code Playgroud)

期望的输出: …

java arrays algorithm cartesian-product

3
推荐指数
1
解决办法
84
查看次数

数组的笛卡尔积,在Ruby中没有重复

我怎样才能做到与自身的数组的笛卡尔积,不包括既[object i, object j][object j, object i]

目前,我有

array = %w{a b c}
unique_combinations = array.each_with_index.to_a.product(array.each_with_index.to_a).
  find_all{|(first_object, i), (second_object, j)| i < j}.
  map{|(first_object, i), (second_object, j)| [first_object, second_object]}
unique_combinations # => [["a", "b"], ["a", "c"], ["b", "c"]]
Run Code Online (Sandbox Code Playgroud)

这有效,但感觉有点冗长.

我可以

array = %w{a b c}
combinations = array.product(array)
unique_combinations = combinations.find_all{|first_item, second_item| array.index(first_item) < array.index(second_item)}
Run Code Online (Sandbox Code Playgroud)

但这感觉就像我扔掉信息一样,只有当数组中只有唯一的项目时才会起作用.

另一种方法是

unique_combinations = []
array.each_with_index do |first_item, i|
  array.each_with_index do |second_item, j|
    next unless i < j
    unique_combinations << [first_item, …
Run Code Online (Sandbox Code Playgroud)

ruby arrays cartesian-product

2
推荐指数
1
解决办法
689
查看次数

'leet'程序 - 获得所有排列

我写了一个简单的函数,将单词中的字母转换为它们的'leet'数字对应物.

def Leet(word):
    letters = list(word.lower())
    for n, letter, in enumerate(letters):
        if letter == 'o':
            letters[n]= '0'
        elif letter == 'i':
            letters[n]= '1'
        elif letter == 'z':
            letters[n]= '2'
        elif letter == 'e':
            letters[n]= '3'
        elif letter == 'a':
            letters[n]= '4'
        elif letter == 's':
            letters[n]= '5'
        elif letter == 'g':
            letters[n]= '6'
        elif letter == 't':
            letters[n]= '7'
        elif letter == 'b':
            letters[n]= '8'
    return ''.join(letters)
Run Code Online (Sandbox Code Playgroud)

所以当我输入时'zit',程序将返回'217'.

我的问题是,我该怎么改变它给我的每一个可能的置换('217','2it','z1t','zi7' …

python permutation cartesian-product python-itertools

2
推荐指数
1
解决办法
1007
查看次数