四种语言完美实现组合算法

php

<?php

function rxn($start, $bit, $n, $m) {
    static $name = __FUNCTION__;
    static $result = array();
    static $arr = array();
    
    for ($i=$start; $i<$n-$m+$bit; $i++) {
        $arr[$bit-1] = $i;
        if ($bit == $m) {
            array_push($result, $arr);
        } else if ($bit < $m) {
            $name($i+1, $bit+1, $n, $m);
        }
    }
    return $result;
}

$result = rxn(0,1, 3,2);

var_dump($result);

 

js

var result = [];
var rxn = function(start, bit, arr, n, m) {
    var name = arguments.callee;
    
    for (var i=start; i<n+m-bit; i++) {
        arr[bit-1] = i;
        if (bit == m) {
            result.push(Array.prototype.slice.call(arr));
        } else if (bit < m) {
            name.call(null,i+1, bit+1, arr, n, m);
        }
    }
}

var n = 3,
    m = 2;
    
ret = rxn(0,1,[],n,m);
console.log(result);

 

python 

#! /usr/bin/python3

import copy

def rxn(start, bit, arr, n, m, result=[]):
    for i in range(start, n+m-bit):
        arr[bit-1] = i
        if bit == m:
            result.append(copy.copy(arr))
        elif bit < m:
            rxn(i+1, bit+1, arr, n, m)
    return result

n, m = 3, 2
result = rxn(0,1,[None for i in range(m)], n, m)

print(result)

 

go

package main

import "fmt"

var result [][]int

func rxn(start, bit, n, m int, arr map[int]int) {
    for i:=start; i<n+m-bit; i++ {
        arr[bit-1] = i
        if bit == m{
            var t []int
            for _, v := range arr {
                t = append(t, v)
            }
            result = append(result, t);
        } else if bit < m {
            rxn(i+1, bit+1, n, m, arr)
        }
    }
}

func main() {
    n,m := 3,2
    arr := make(map[int]int)
    rxn(0, 1, n, m, arr)
    
    fmt.Println(result)
}

  

posted on 2013-11-05 23:57  mtima  阅读(214)  评论(0编辑  收藏  举报

导航