簡體   English   中英

如何從3位數字組合中找到一個數字?

[英]How to find a number from its 3 digit combinations?

如果有8位數字65478209(數字中的數字可以重復),並且給出的組合始終按數字的順序排列,則如果給出所有組合8c3 = 56個組合,那么找出最短的解決方案是什么號碼) ?

一個示例場景是銀行登錄,其中用戶需要輸入其代碼的3個隨機數字,例如3rd,5th和6th,這是8c3組合之一。 因此,如果給出了所有8c3組合,那么找到數字的解決方案/邏輯將是什么? (或第一個數字,如果有更多數字作為解決方案)

為了解決編程語言中的問題,輸入將包含56個3位數字的數組,我們必須找到代碼“ 65478209”或任何其他內容。

如何使用排列? 我用c ++風格編寫了簡單的代碼。 核實。

int k = 3;
string digit = "65478209";
int digitLen = digit.length();

int* indexArr = new int[digitLen];
for(int i=0; i < digitLen; i++) indexArr[i] = i;

do
{
    bool isInOrder=true;
    string ret = "";
    for(int i=1; i < k; i++) if(indexArr[i] < indexArr[i-1])
    {
        isInOrder = false;
        break;
    }
    if(!(isInOrder)) continue;

    for(int i=0; i < k; i++) ret += digit[indexArr[i]];
} while(next_permutation(indexArr, indexArr+digitLen));

delete indexArr;

編輯

這是我的解決方案。

vector<string> combinations;
set<int> includedDigit;
vector<int> referCnt;

// Get reference count from all precedences
for(int i=0; i < combinations.size(); i++)
{
    string e = combinations[i];
    for(int j=0; j < k-1; j++)
    {
        includedDigit.insert(e.at(j) - '0');
        for(int l=j+1; l < k; l++)
        {
            int curDigit = e.at(l) - '0';
            referCnt.push_back(curDigit);
        }
    }
}

// Sorting reference counts with digit
vector<pair<int,int>> ret;
for(int i=0; i < 10; i++)
{
    int digitCnt = count(referCnt.begin(), referCnt.end(), i);
    if(digitCnt == 0 && includedDigit.find(i) != includedDigit.end()) ret.push_back(make_pair(1, i));
    else if(digitCnt != 0) ret.push_back(make_pair(digitCnt, i));
}
sort(ret.begin(), ret.end());

// Print the result
for(auto it=ret.begin(); it != ret.end(); it++)
{
    pair<int,int> val = *it;
    cout << val.second;
}

盡管我認為它可以縮短,但是它可以工作。 另外,如果原始數字不是某種排列,它應該更復雜。

k = 3

以下遞歸算法從有序集合中選擇所有k元素組合:

  1. 選擇i作為第一個元素。
  2. i與從大於i的元素集中遞歸選擇的k-1元素的每種組合結合起來。
  3. 對集合中的每個i進行上述迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM