2010年3月23日 星期二

密碼分析

密碼分析(cryptanalysis)是指把某個人寫的密文加以分解。這個程序通常會對密文訊息做統計分析。你的任務就是寫一個程式來對密文作簡單的分析。
輸入規範
輸入檔案的第一列有一個正整數n,代表以下有多少列需要分析的密文。接下來的n列,每列含有0或多個字元(可能包含空白字元)
輸出規範
每列包含一個大寫字元(A~Z)和一個正整數。這個正整數代表該字元在輸入檔案中出現的次數。輸入中大小寫(例如:A及a)視為相同的字元。輸出時請按照字元出現的次數由大到小排列,如果有2個以上的字元出現次數相同的話,則按照字元的大小(例如:A在H之前)由小到大排列。
請注意:如果某一字元未出現在輸入檔案中,那它也不應出現在輸出檔案中。
輸入範例(test5.txt)
3
This is a test.
Count me 1 2 3 4 5.
Wow!!!! Is this question easy?
輸出範例(result5.txt)
S 7
T 6
I 5
E 4
O 3
A 2
H 2
N 2
U 2
W 2
C 1
M 1
Q 1
Y 1

3 則留言:

  1. Dim abc(26) As String, num(26) As Integer
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, n
    StrA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    For i = 1 To 26
    abc(i) = Mid(StrA, i, 1)
    Next i
    For i = 1 To n
    Input #1, x
    x = UCase(x)
    For j = 1 To Len(x)
    k = Mid(x, j, 1)
    For s = 1 To 26
    If k = abc(s) Then
    num(s) = num(s) + 1
    End If
    Next s
    Next j
    Next i
    For i = 1 To 26
    For j = 1 To 26
    If num(i) > num(j) Then
    change abc(i), abc(j)
    change num(i), num(j)
    End If
    Next j
    Next i
    For i = 1 To 26
    If num(i) <> 0 Then
    Print #2, abc(i); num(i)
    End If
    Next i
    Close #1
    Close #2
    End Sub


    Public Sub change(a, b)
    c = a
    a = b
    b = c
    End Sub

    回覆刪除
  2. 阿瑋好,
    1.你的輸出要看一看,你的排序是不是不影響原有順序的排法。
    2.你的排序,還真是一次也沒少到啊,這個小小難看。至少
    for i = 1 to 25
    for j = i+1 to 26

    這樣是咱們選手隊至少要有的技巧吧。要背起來用。

    回覆刪除
  3. Dim q As String
    Dim num(200) As Integer
    Dim numstr(97 To 122) As String
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, x
    For i = 1 To x
    Line Input #1, q
    q = Replace(q, " ", "")
    q = LCase(q)
    For j = 1 To Len(q)
    num(Asc(Mid(q, j, 1))) = num(Asc(Mid(q, j, 1))) + 1
    Next j
    Next i
    For j = 97 To 122
    If num(j) <> 0 Then
    numstr(j) = Chr(j)
    End If
    Next j
    For i = 97 To 121
    For j = i + 1 To 122
    If num(i) < num(j) Then
    step = num(i)
    num(i) = num(j)
    num(j) = step
    step = numstr(i)
    numstr(i) = numstr(j)
    numstr(j) = step
    End If
    Next j
    Next i
    For i = 97 To 122
    If num(i) <> 0 Then Print #2, UCase(numstr(i)), num(i)
    Next i

    Print
    Close #2
    Close #1
    End Sub

    回覆刪除