發新話題
打印

請問一個關於數學的全排列組合的寫法

請問一個關於數學的全排列組合的寫法

小弟最近在使用matlab
因為題目的需求
需要使用到全排列組合
而全排列組合的程式碼小弟有找到一個使用遞迴的方式求解
因為小弟在使用窮舉法後仍須取得相關排序
以代入其他程式進行求解
能否請問版上的大大們
是否有較佳的方式可以求解如"迴圈"等方式
謝謝
附上網路找到之matlab程式碼
複製內容到剪貼板
代碼:
clear all;clc;close all;

job_num = 6
n_1 = prod(1:job_num);   % 1~job_num的累乘積值
row = n_1;
col = job_num;
allorder_K = zeros(1:job_num-1);
cnt = 0;
period = n_1/1000;

total = 0;
for allorder_m = 1:n_1
    allorder_flag=zeros(1,job_num);
    allorder_P = zeros(1,job_num);
    for allorder_i = 1:job_num-1
        position = job_num-allorder_K(allorder_i);
        allorder_j = job_num;
        while(allorder_j >= position)
            if(allorder_flag(allorder_j)==1)
                position = position-1;
            end
            allorder_j =allorder_j-1;
        end
        allorder_P(position)=job_num+1-allorder_i;
        allorder_flag(position)=1;
    end
    for allorder_i = 1:job_num
        if (allorder_flag(allorder_i)==0)
            allorder_P(allorder_i)=1;
            break;
        end
    end
    %%%%%%%%以下更新k
    for allorder_i = 1:job_num-1
        allorder_K(job_num-allorder_i)=mod(allorder_K(job_num-allorder_i)+1,allorder_i+1);
        if (allorder_K(job_num-allorder_i)~=0)
            break;
        end
    end
    %%%下面,可以引用allorder_P進行相關處理
        cnt = cnt+1
        allorder_P
%--------------------------------------------------------------------------
% for m =1:row
%     sort_ind = matrix(m, :);
          sort_ind = allorder_P;
%--------------------------------------------------------------------------         
end

TOP

雖然我不懂 Matlab,

不過上面的程式碼看起來就像是用了 for 迴圈,

怎嚜會是遞迴呢?

由於我沒用過 Matlab,不知道其語法,

你可不可以先解說一下上面的程式碼哪段哪些部份是在幹麻呀?

感謝。 ^__^

多喝水。

TOP

excel 版的排列

在教排列組合時, 常常會想要看排列的情形, 3!, 4! 還可以用人工列出來, 5!, 6! 可就麻煩了, 偶然發現以下的Excel VBA , 還不錯, 給大家參考!
http://spreadsheetpage.com/index.php/tip/generating_permutations/
Dim CurrentRow
Sub GetString()
    Dim InString As String
    InString = InputBox("Enter text to permute:")
    If Len(InString) < 2 Then Exit Sub
    If Len(InString) >= 8 Then
        MsgBox "Too many permutations!"
        Exit Sub
    Else
        ActiveSheet.Columns(1).Clear
        CurrentRow = 1
        Call GetPermutation("", InString)
    End If
End Sub

Sub GetPermutation(x As String, y As String)
'   The source of this algorithm is unknown
    Dim i As Integer, j As Integer
    j = Len(y)
    If j < 2 Then
        Cells(CurrentRow, 1) = x & y
        CurrentRow = CurrentRow + 1
    Else
        For i = 1 To j
            Call GetPermutation(x + Mid(y, i, 1), _
            Left(y, i - 1) + Right(y, j - i))
        Next
    End If
End Sub

[ 本帖最後由 荷荷葩 於 2014-9-10 11:11 PM 編輯 ]

TOP

發新話題