2015-09-06 21 views
-3

我嘗試在C中創建一個簡單的函數,它允許我們通過給出當前行號,行總數以及行數來找到一系列數字的當前步驟。步驟...的數字系列查找當前步驟中的一系列數字

例子:

line 0 - 0 -- 
line 1 - 0  |--> STEP 1 
line 2 - 0 -- 
line 3 - 1 -- 
line 4 - 1  |--> STEP 2 
line 5 - 1  | 
line 6 - 1 -- 
line 7 - 2 -- 
line 8 - 2  | 
line 9 - 2  |--> STEP 3 
line 10 - 2  | 
line 11 - 2 -- 

Parameters : currentLine = 5; totalLines = 12; steps = 3; 

我在這種情況下,三個不同的步驟,所有步驟由一個多線遞增。每一步都用相同的數字表示,緊靠行號。

在我的示例中,我選擇currentLine = 5,它代表我們想要查找當前步驟的行。所以,在我的情況,我需要找到:2

我的我的功能,給予當前行的當前步驟的原型:

int findCurrentStep(int currentLine, int totalLines, int steps); 

我只是想知道如何計算呢?

編輯:謝謝你的回答,我只是提出了另一種方法。

int findCurrentStep(int currentLine, int totalLines, int steps) 
{ 
    int step; 
    int trim_lines; 

    step = steps; 
    trim_lines = totalLines; 
    while (currentLine <= trim_lines -1) 
    { 
     trim_lines = totalLines - 3 + steps - 1; 
     step--; 
    } 
    return step; 
} 

這適用於只需一個步驟,但沒有幾個的...

+0

那麼,你到目前爲止嘗試過什麼?爲什麼目前的解決方案沒有工作,如果有的話? – Tlacenka

+2

你是什麼意思?「在這種情況下,我有三個不同的步驟,所有步驟都增加一行。」 – vish4071

+0

@ vish4071我認爲通過遞增步數,行數加1(步0 - 3行,步1 - 4行...) – Tlacenka

回答

0

編輯: -

這是一個1級的解決方案。

您需要找到currentLine等於或小於以3開頭的AP的哪個第一個r-項。整個總和超過currentLine的第一項將是currentStep。

讓我們假設currentLine小於或等於總結的AP的第一[R條款。

所以,currentLine < = 3 + ... + 3 +(R-1)* 1。

僞代碼: -

initialStep = 3; // initialStep is 3 in this case. 
sum = currentLine; . 
currentStep = 0; 
while(sum > initialStep){ 
    sum -= initialStep; 
    initialStep = intialStep + 1; 
    currentStep++; 
} 
requiredAnswer = currentStep + 1; 

你的答案是(currentStep + 1)在循環之後,當條件失敗時循環將被終止。

0

如果有x步和n總行,讓第1步出現的次數是a
然後,問題表明,

a + (a+1) + (a+2) + ... + (a+x-1) = n //since x steps and n total lines 

因此,這意味着,

x * (2*a + x - 1) = 2*n 

現在,因爲我們知道xn,解決a
一旦你知道a,如果你的「發現」當前行是c,你可以看到這k,這個不等式成立:

a + (a+1) + ... (a+k) < c <= a + (a+1) + ...(a+k+1) 

然後,k+1將是你的答案。