Home > Web Front-end > JS Tutorial > body text

Javascript Cartesian product algorithm implementation method_javascript skills

WBOY
Release: 2016-05-16 16:05:16
Original
1546 people have browsed it

The example in this article describes the implementation method of the Cartesian product algorithm in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:

Here you can generate a Cartesian product based on the given object or array

//笛卡儿积组合
function descartes(list)
{
  //parent上一级索引;count指针计数
  var point = {};
  var result = [];
  var pIndex = null;
  var tempCount = 0;
  var temp  = [];
  //根据参数列生成指针对象
  for(var index in list)
  {
    if(typeof list[index] == 'object')
    {
      point[index] = {'parent':pIndex,'count':0}
      pIndex = index;
    }
  }
  //单维度数据结构直接返回
  if(pIndex == null)
  {
    return list;
  }
  //动态生成笛卡尔积
  while(true)
  {
    for(var index in list)
    {
      tempCount = point[index]['count'];
      temp.push(list[index][tempCount]);
    }
    //压入结果数组
    result.push(temp);
    temp = [];
    //检查指针最大值问题
    while(true)
    {
      if(point[index]['count']+1 >= list[index].length)
      {
        point[index]['count'] = 0;
        pIndex = point[index]['parent'];
        if(pIndex == null)
        {
          return result;
        }
        //赋值parent进行再次检查
        index = pIndex;
      }
      else
      {
        point[index]['count']++;
        break;
      }
    }
  }
}
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!