2020年3月29日 星期日

3.3-PlayfairCipher-Lab

解題思路:
其實照著題目步驟一步步寫就好了,只要不要會錯意應該就沒有大問題。

程式碼:
#include <iostream>
#include <string>
using namespace std;
void findPosition(char c,char table[5][5],int &x,int &y)
{
 for (int i = 0; i < 5; i++)
 {
  for (int j = 0; j < 5; j++)
  {
   if (c == table[i][j])
   {
    x = i, y = j;
    return;
   }
  }
 }
}

int main() {
 string plaintext, key;
 
 while (cin >> plaintext >> key)
 {
  char table[5][5] = {'\0'};
  int alphabetIndex[26] = { 0 }; // check if alphabet is recorded in table
  alphabetIndex['j' - 'a'] = 1; // aviod error
  int currentRow = 0, currentColumn = 0, currentPoint = 0; // current recorded position
  string answer = "";
  for (int i = 0; i < key.size(); i++)
  {
   if (alphabetIndex[key[i] - 'a'] == 0) // if new
   {
    table[currentRow][currentColumn] = key[i];
    currentColumn++;
    if (currentColumn >= 5) // next line
    {
     currentColumn %= 5;
     currentRow++;
    }
   }
   if (key[i] == 'j' && alphabetIndex['i' - 'a'] == 0) // 'j' case
   {
    table[currentRow][currentColumn] = 'i';
    currentColumn++;
    if (currentColumn >= 5) // next line
    {
     currentColumn %= 5;
     currentRow++;
    }
    alphabetIndex['i' - 'a']++;
   }
   alphabetIndex[key[i] - 'a']++; // increase index record
  }
  for (int i = 0; i < 26; i++) //fill the table
  {
   if (alphabetIndex[i] == 0)
   {
    table[currentRow][currentColumn] = (i + 'a');
    currentColumn++;
    if (currentColumn >= 5) // next line
    {
     currentColumn %= 5;
     currentRow++;
    }
   }
  }
  while (currentPoint <= plaintext.size() - 1) // encode
  {
   int c1Row = 0, c1Column = 0, c2Row = 0, c2Column = 0;
   if (currentPoint == plaintext.size()-1)
   {
    findPosition(plaintext[currentPoint], table, c1Row, c1Column);
    findPosition('x', table, c2Row, c2Column);
    currentPoint++;
   }
   else if (plaintext[currentPoint] != plaintext[currentPoint + 1]) // they are different
   {
    findPosition(plaintext[currentPoint], table, c1Row, c1Column);
    findPosition(plaintext[currentPoint + 1], table, c2Row, c2Column);
    currentPoint += 2; // to the next point
   }
   else
   {
    findPosition(plaintext[currentPoint], table, c1Row, c1Column);
    findPosition('x', table, c2Row, c2Column);
    currentPoint += 1;
   }

   if (c1Row == c2Row)
   {
    answer += table[c1Row][(c1Column + 1) % 5];
    answer += table[c2Row][(c2Column + 1) % 5];
   }
   else if (c1Column == c2Column)
   {
    answer += table[(c1Row + 1) % 5][c1Column];
    answer += table[(c2Row + 1) % 5][c2Column];
   }
   else
   {
    answer += table[c1Row][c2Column];
    answer += table[c2Row][c1Column];
   }
  }
  cout << answer << endl;
  //for (int i = 0; i < 5; i++) // print table
  //{
  // for (int j = 0; j < 5; j++)
  //  cout << table[i][j];
  // cout << endl;
  //}
 }
    return 0;
}

沒有留言:

張貼留言