簡體   English   中英

向右旋轉序號

[英]Rotating sequential numbers to right

它很容易將數字向左旋轉。 我將執行以下操作:

int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
  for(int j = 0; j < numberCount; j++)
  {
    System.out.print((i+j) % numberCount + " ");
  }

  System.out.println();
}

在此示例中,將打印以下內容:

0 1 2 3

1 2 3 0

2 3 0 1

3 0 1 2

0 1 2 3

1 2 3 0

2 3 0 1

3 0 1 2

您將如何做同樣的事情,但是將數字向右旋轉?

一旦想到,答案就很明顯了-向左移動數字,然后加上數字,向右移動數字,減去數字。 我以為公式會發生重大變化,所以我想到的是比解決方案復雜得多的公式。

// ensures mod is positive
int mod(int a, int b)
{ return (a%b+b)%b; }

int numberCount = 4;
int rotationCount = 2 * numberCount;

for(int i = 0; i < rotationCount; i++)
{
    for(int j = 0; j < numberCount; j++)
    {
        System.out.print(mod((j-i), numberCount) + " ");
    }

    System.out.println();
}

暫無
暫無

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

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