2012年5月14日 星期一

最小距離

請設計一個程式,能在一個數列中,找出相鄰兩數的最小距離。例如,有一個數列為8,20,27,17,13,28,35,31,8與20的距離為12;20與27的距離為7,與前一個例子相比,其距離較小。

輸入說明:輸入之奇數列為下一行數列中的個數,偶數列為數列資料,代表一組測試資料。每個數字與數字間的區隔為一個空白符號,當奇數列為0時表示結束。(請參照輸入範例)
輸入範圍:每個數列最少有2個數字,最多不超過100個。每個數列中的數字皆大於0,小於1000,且不重覆。
輸入範例:in.txt
8
8 20 27 17 13 28 35 31
15
13 14 55 21 66 72 23 73 1 2 88 83 84 24 7
0

輸出說明:每組測試的數列皆要輸出最小距離。(請參照輸出範例)
輸出範例:out.txt
4
1

6 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    Input #1, n
    If n = 0 Then Exit Do
    Line Input #1, x
    a = Split(x)
    Min = Abs(a(1) - a(0))
    For i = 1 To UBound(a)
    If Abs(a(i) - a(i - 1)) < Min Then Min = Abs(a(i) - a(i - 1))
    Next
    Print #2, Min
    Loop Until n = 0
    Close
    Close
    End
    End Sub

    回覆刪除
  2. 作者已經移除這則留言。

    回覆刪除
  3. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim a(100) As Integer
    Do
    Input #1, n
    If n = 0 Then Exit Do
    For i = 1 To n
    Input #1, a(i)
    Next i
    Min = 1000
    For j = 1 To n - 1
    If Min > Abs(a(j) - a(j + 1)) Then Min = Abs(a(j) - a(j + 1))
    Next j
    Print #2, Min
    Loop Until n = 0
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  4. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim a(100) As Integer
    Dim min As Integer
    Do
    Input #1, n
    If n = 0 Then Exit Do
    For i = 1 To n
    Input #1, a(i)
    Next i
    min = 1000
    For h = 1 To (n - 1)
    g = Abs(a(h + 1) - a(h))
    If g < min Then
    min = g
    End If
    Next h
    Print #2, min
    Loop
    Close
    Close
    End
    End Sub

    回覆刪除
  5. Dim QQ() As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    Input #1, x
    If x = 0 Then Exit Do
    ReDim QQ(Val(x))
    For i = 1 To Val(x)
    Input #1, y
    QQ(i) = Val(y)
    Next i
    Min = Abs(QQ(2) - QQ(1)): ans = 0
    For i = 3 To UBound(QQ())
    If Abs(QQ(i) - QQ(i - 1)) < Min Then ans = ans + 1
    Min = Abs(QQ(i) - QQ(i - 1))
    Next i
    Print #2, ans
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除