• alic
    2018-12-28
    password = 'bacdce'
    classes = ['a', 'b', 'c', 'd', 'e']

    def get_password(n, result = ''):
        if n == 0:
            if result == password:
                print(password)
        else:
            for i in classes:
                new_result = copy.copy(result)
                new_result = new_result + i
                get_password(n - 1, new_result)

    get_password(6)
    展开

    作者回复: 可以的👍

     1
     18
  • qinggeouye
    2019-02-08
    python
    一、田忌和齐王双方都随机选择马匹出战顺序
    import copy
    # 设置齐王的马跑完所需时间
    q_horses_time = {"q1": 1.0, "q2": 2.0, "q3": 3.0}
    # 设置田忌的马跑完所需时间
    t_horses_time = {"t1": 1.5, "t2": 2.5, "t3": 3.5}
    # 双方均随机选择出战的马匹

    q_horses = ["q1", "q2", "q3"]
    t_horses = ["t1", "t2", "t3"]

    def permutation(horses, result=None, all_results=None):
        """
        使用函数的递归(嵌套)调用,找出所有可能的马匹出战顺序
        :param all_results: 马匹出战顺序的所有排列(全排列)
        :param horses: 目前还剩多少马没有出战
        :param result: 保存当前已经出战的马匹及顺序(其中一种排列)
        :return:
        """
        if result is None:
            result = []
        if all_results is None:
            all_results = []

        # 所有马匹都已经出战,返回出战顺序
        if len(horses) == 0:
            all_results.append(result)
            return

        for k in range(len(horses)):
            # 从剩下的未出战马匹中 选择一匹 加入结果
            new_result = copy.copy(result)
            new_result.append(horses[k])
            # 将已选择的马匹从未出战的列表中移除
            rest_horses = copy.copy(horses)
            rest_horses.pop(k)
            # 递归调用 对于剩余的马匹继续生成排列
            permutation(rest_horses, new_result, all_results)
        return all_results


    def compare(t, q):
        t_won_cnt = 0
        for m in range(len(t)):
            print(str(t_horses_time.get(t[m])) + ',' + str(q_horses_time.get(q[m])))
            if t_horses_time.get(t[m]) < q_horses_time.get(q[m]):
                t_won_cnt = t_won_cnt + 1
        if t_won_cnt > len(t)//2:
            print("田忌获胜!")
        else:
            print("齐王获胜!")

    if __name__ == '__main__':
        # 双方均随机安排马匹出战,田忌获胜的概率仍为 1/6
        t_results = permutation(t_horses)
        q_results = permutation(q_horses)
        print(t_results)
        print(q_results)
        for i in range(len(t_results)):
            for j in range(len(q_results)):
                compare(t_results[i], q_results[j])
    展开
    
     5
  • 菩提
    2018-12-30
    交作业:
    public class L7_2 {

        public static void calLetterList(ArrayList<String> l, ArrayList<String> result) {
            if (result.size() == l.size()) {
                System.out.println(result);
                return;
            }

            for (String letter : l) {
                ArrayList<String> newResult = (ArrayList<String>) result.clone();
                newResult.add(letter);
                calLetterList(l, newResult);
            }
        }

        public static void main(String[] args) {
            ArrayList<String> l = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
            calLetterList(l, new ArrayList<>());
        }

    }
    展开

    作者回复: 很赞

    
     5
  • Joe
    2019-01-09
    C++形式交作业,好像用list数据结果会方便一点。
    /** permutaion: 排列。
     * 从n个数中选出m个数的方式,若不考虑顺序Cn(m),若考虑顺序An(m)
     */

    /* 问题:密码排列
     * 假设有一个 4 位字母密码,每位密码是 a~e 之间的小写字。
     * 编写密码可能排列方式。
     */
    #include <iostream>
    #include <vector>
    using namespace std;

    class Permutation {
      private:
      int resultCount_ = 0;

      public:
      /** Details: 根据输入字母列表,获得所有的排列方式。
       * params: result- 当前排列形式, candidate- 未排列字母表。
       * return: null
       */
      void breakPassword(vector<string> result, vector<string> candidate) {
        int len = candidate.size();
        if (0 == len) {
          // 无字母剩余,输出排列结果
          outputResult(result);
          resultCount_++;
          return;
        }
        for (int i = 0; i < len; i++) {
          vector<string> resultNew;
          vector<string> candidateLeft;
          // 读取排列字母
          resultNew = result;
          resultNew.push_back(candidate[i]);
          // 获得剩余字母表
          candidateLeft = candidate;
          vector<string>::iterator it = candidateLeft.begin();
          candidateLeft.erase(it + i);
          // 递归
          breakPassword(resultNew, candidateLeft);
        }
      }
      // 输出结果
      void outputResult(vector<string> result) {
        for (unsigned int i = 0; i < result.size(); i++) {
          cout << result[i];
        }
        cout << endl;
      }
      // 获得所有可能密码总数
      int getResultCount() {
        return resultCount_;
      }
    };

    int main(void) {
      vector<string> fourAlphabetString = {"a", "b", "c", "d", "e"};
      vector<string> res;
      Permutation test;
      test.breakPassword(res, fourAlphabetString);
      cout << "可能的密码形式:";
      cout << test.getResultCount() << "种" << endl;
    }
    展开

    作者回复: c语言确实更简洁👍

    
     4
  • Jing
    2019-04-05
    //思考题 c#版本
    private static char[] _letters = { 'a', 'b', 'c', 'd', 'e' };
    public static void GetPassword()
    {
    string password = "abded";
    CrackPassword(password.Length, new StringBuilder(), password);
    }

    private static void CrackPassword(int length, StringBuilder result, string realPsd)
    {
    if (length == 0)
    {
    if (realPsd.Equals(result.ToString()))
    {
    Console.WriteLine("Your password is:" + result.ToString());
    }
    result.Length = 0;
    return;
    }
    else if (length < 0)
    {
    return;
    }
    for (int i = 0; i < _letters.Length; i++)
    {
    StringBuilder temp = new StringBuilder();
    temp.Append(result.ToString());
    temp.Append(_letters[i]);
    CrackPassword(length - 1, temp, realPsd);
    }
    }
    展开
    
     2
  • 瓶子🍼
    2019-01-09
    var chars = ['a', 'b', 'c', 'd', 'e']
    var result = []

    function getPassword(passwordChars, num, password) {
        if (num == 0) {
            return result.push(password)
        } else {
            for (var i = 0; i < passwordChars.length; i++) {
                getPassword(passwordChars, num - 1, password + passwordChars[i])
            }
        }
    }
    getPassword(chars, 4, '')
    展开

    作者回复: 代码很简洁

    
     2
  • 文刂 氵共 超
    2018-12-28
    思考题 - 递归思想-C++
    #include <iostream>
    #include<string>

    using std::string;
    using namespace std;

    void BreakPassword( string Words, int PasswordLen, string result)
    {
        if (result.length() == PasswordLen)
        {
            //C++中string类型不能直接输出,需加头问题#include<string>,不能用#include<string.h>
            cout << result << " ";
            return;
        }

        for (int i = 0; i < Words.length(); ++i)
        {
            string newResult = result;
            newResult.insert( newResult.end(), Words[i] );
            BreakPassword(Words, PasswordLen, newResult);
        }
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
        int passwordLen = 4;
        string words("abcde");
        string result = "";
        
        BreakPassword(words, passwordLen, result);

        return 0;
    }
    展开
    
     2
  • alic
    2018-12-28
    怎么用递归来求?

    作者回复: 具体是指哪道题目?

    
     2
  • 毛毛
    2018-12-28
    最笨的方法,一个数组A容纳a~e,四个for循环遍历数组A,拼成一个新一维数组B,多个数组B再拼成二维数组,就是最后结果。

    作者回复: 密码短的话,循环嵌套就可以了。如果密码很长,或者长度是满足某种条件的,就需要递归

    
     2
  • QFann
    2019-04-29
    交作业
    /**
         *
         * @param password 密码组成元素
         * @param result 密码可能组合
         * @param number 密码个数
         */
        public static void getPassword(ArrayList<String> password,ArrayList<String> result,int number){

            if(result.size() >= number ){
                System.out.println(result);
                return;
            }

            for (int i = 0;i < password.size() ; i++){
                ArrayList<String> new_result = (ArrayList<String>) result.clone();
                new_result.add(password.get(i));
                getPassword(password,new_result,number);

            }

        }
    展开
    
     1
  • suiyueranzly
    2019-01-07
    来补作业了,老师
    -------------------------代码-----------------------------------
     /**
         * 排列
         *
         * @param passwords 待排列的字符
         * @param results 排列的结果
         ***/
        public void range(ArrayList<String> passwords, ArrayList<String> results) {
            //如果为空则不需要排列
            if (passwords.isEmpty()) {

                String collect = String.join("", results);

                System.out.print(collect + "\t");

            }

            for (int i = 0; i < passwords.size(); i++) {

                String password = passwords.get(i);

                ArrayList<String> newResult = (ArrayList<String>) results.clone();

                ArrayList<String> newPassword = (ArrayList<String>) passwords.clone();

                newResult.add(password);

                newPassword.remove(i);

                range(newPassword,newResult);

            }
        }
    展开

    作者回复: 逻辑清晰

    
     1
  • 风轨
    2018-12-28
    public class Crack {
        static char[] pwdcs = new char[] { 'a', 'b', 'c', 'd', 'e' };
        static String[] crack(int len) {
            String[] ps = new String[] { "" };
            while (len-- > 0) {
                String[] nps = new String[ps.length * pwdcs.length];
                int nsbsi = 0;
                for (String pwd : ps) {
                    for (char c : pwdcs) {
                        nps[nsbsi++] = pwd + c;
                    }
                }
                ps = nps;
            }
            return ps;
        }
        
        
        public static void main(String[] args) {
            String[] pwds = crack(4);
            for (String pwd : pwds) {
                System.out.println(pwd);
            }
            /**
             * 输出结果
             * aaaa
             * aaab
             * aaac
             * aaad
             * aaae
             * aaba
             * ....
             * 省略517行
             * ....
             * eeed
             * eeee
             *
             */
        }
    }
    展开
    
     1
  • 石佳佳_Gemtra
    2018-12-28
    对于 n 个元素里取出 m(0<m≤n) 个元素的重复排列数量是 nxnxnx…xn,也就是 n^m。
    
     1
  • Nikola
    2020-01-30
    再说一遍ASCII字符一共有多少?256?这基础漏洞有点大了吧?更别提去掉32个不可输出字符,只有96个可输出字符。

    作者回复: 确实标注的ASCII只有128个,加上扩展的才256个,而且很多还无法输出。

    
    
  • Me.Gao
    2020-01-26
    #python version
    import copy

    passPool = ['a', 'b', 'c', 'd', 'e']
    password = 'beca'

    def passFinder(paWord):
        if len(paWord) > 4:
            return
        if len(paWord) == 4:
            if paWord == password:
                print('Password found, which is', paWord)
                return
        for i in passPool:
            new_paWord = copy.deepcopy(paWord)
            new_paWord += i
            passFinder(new_paWord)

    if __name__ == '__main__':
        passFinder('')
    展开
    
    
  • Me.Gao
    2020-01-26
    import copy
       
    t_horse_time = dict([('t1', 1.5), ('t2', 2.5), ('t3', 3.5)])
    q_horse_time = dict([('q1', 1), ('q2', 2), ('q3', 3)])
    q_horse = ['q1', 'q2', 'q3']

    def compare(t, q):
        """To Compare which one wins the horse race
            
        t, q: the horse sequence list
        """
        t_won_cnt = 0
        for i in range(len(t)):
            print(t_horse_time[t[i]], q_horse_time[q[i]])
            if t_horse_time[t[i]] < q_horse_time[q[i]]:
                t_won_cnt += 1
        if (t_won_cnt > (len(t) / 2)):
            print('田忌获胜!')
        else:
            print('齐王获胜!')
            
    def permulation(horses, result):
        """列出所有可能的比赛方式
        
        horses: 目前还有多少马没有出战, result: 保存当前已经出战的马匹顺序
        """
        # 所有马匹都已经出战,判断哪方获胜,输出结果
        if (len(horses) == 0):
            print(result)
            compare(result, q_horse)
            return
        for cnt in range(len(horses)):
            #从剩下的未出战马匹中,选择一匹,加入结果
            new_result = copy.deepcopy(result)
            new_result += [horses[cnt]]
            #将已选择的马匹从未出战的列表中移出
            new_horses = copy.deepcopy(horses)
            del new_horses[cnt]
            #递归调用,对于剩余的马匹继续生成排列
            permulation(new_horses, new_result)

    if __name__ == '__main__':
        horses = ['t1', 't2', 't3']
        permulation(horses, [])
    展开
    
    
  • 王宇
    2020-01-16
    void permutationRecursive(QStringList restData, QStringList resultData){
        if(restData.isEmpty())
        {
            qDebug()<<resultData;
            return;
        }

        for(int i=0; i<restData.length(); i++){
            QStringList newResultData = resultData;
            newResultData.append(restData[i]);

            QStringList newRestData = restData;
            newRestData.removeAt(i);

            permutationRecursive(newRestData, newResultData);
        }
    }

    void permutationIteration(QStringList list){
        QList<QStringList> result, tmp;

        result<<QStringList(list[0]);
        for(int j=1; j<list.count(); j++){
            for(int k=0; k<result.count(); k++){
                for(int m=0; m<result[k].count()+1; m++){
                    QStringList aa = result[k];
                    aa.insert(m, list[j]);
                    tmp<<aa;
                }
            }
            result = tmp;
            tmp.clear();
        }
        for(int i= 0; i < result.count(); i++){
            qDebug()<<result[i];
        }
    }

    void repeatPermutationRecursive(QStringList list, QStringList result){
        if(list.count() == result.count()){
            qDebug()<<result;
            return;
        }
        for(int i=0; i<list.count(); i++){
            QStringList resultCopy = result;
            resultCopy<<list[i];
            repeatPermutationRecursive(list, resultCopy);
        }
    }

    void repeatPermutationIteration(QStringList list){
        QList<QStringList> result, resultTmp;

        if(list.count() == 0)
            return;

        for(int i=0; i<list.count(); i++){
            result<<QStringList(list[i]);
        }
        for(int i=1; i<list.count(); i++){
            for(int j=0; j<list.count(); j++){
                for(int k = 0; k<result.count(); k++){
                    QStringList tmp = result[k];
                    tmp.append(list[j]);
                    resultTmp.append(tmp);
                }
            }
            result = resultTmp;
            resultTmp.clear();
        }
        for(int i= 0; i < result.count(); i++){
            qDebug()<<result[i];
        }
    }
    展开
    
    
  • 江河顺水
    2020-01-15
    排列是从n个元素的集合中选择m个元素,按照一定的顺序排列,这个过程叫做排序。选择的顺序列可有有重复的元素叫做重复排列。全部元素的排列是全排列。编码思路是通过递归,穷举不同的情况。
    
    
  • Joker
    2020-01-07
    ```
    java
    public class Lesson7_02 {
        private static ArrayList<ArrayList<String>> ans = new ArrayList<>();
        private static String[] chars = {"a", "b", "c", "d", "e"};
        private static void permutate_1(ArrayList<String> tempList, int len, int charsLen) {
            if (tempList.size() == len) {
                ans.add(tempList);
                return;
            }
            for (int i = 0; i < charsLen; i++) {
                ArrayList<String> newList = (ArrayList<String>) tempList.clone();
                newList.add(chars[i]);
                permutate_1(newList, len, charsLen);
            }
        }
        public static void main(String[] args) {
            permutate_1(new ArrayList<>(), 4, chars.length);
            for (ArrayList<String> item : ans) {
                System.out.println(item);
            }
        }
    }
    ```
    展开
    
    
  • cwtxz
    2019-12-25
    我个人也有了几年的编程经历,不说对编程这门手艺多么精通,但至少略有感悟。不说把算法和数据结构研究得多么深入,但至少,对一些常见的数据结构和常用的算法还是比较了解。学习算法和数据结构到一定程度的时候,我就明白了,算法对于优化程序很重要,良好的数据结构和算法设计会让程序变得更为健壮和优雅。只要你是程序员,那一定离不开算法和数据结构,这是编程的基石。然而高效优雅的算法设计又离不开数学思维的主导,所以,数学,才是一切的源头,是工具,是方法,是理解算法本质的东西。任何有志问鼎更高层次的程序员,都应该下足功夫去研究数学,只有这样才能对计算机世界有本质的理解。加油!!!
    
    
我们在线,来聊聊吧