Programozás‎ > ‎Feladatok‎ > ‎Célérték keresés‎ > ‎Megoldás‎ > ‎

tb_cel.vb

Letöltés: tb_cel.vb.txt  (A fájlt letöltést után át kell nevezni tb_cel.vb-re.)

Module Celertek
  Private Const ben As Byte = 10
  Private Const bec As Integer = 101
  Private bet() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  Private operators() As Char = {"+"c, "-"c, "*"c, "/"c}

  Private isNotMin As Boolean = True
  Private minDiff As Integer
  Private minOperators(ben) As Byte

  Private Sub Calculate(level As Integer, number As Integer, arrOperator() As Byte, op As Byte)
    If level = ben - 1 Then
      If isNotMin OrElse Math.Abs(minDiff) > Math.Abs(number - bec) Then
        isNotMin = False
        minDiff = number - bec
        arrOperator(level) = op
        arrOperator.CopyTo(minOperators, 0)
      End If
    Else
      arrOperator(level) = op
      Calculate(level + 1, number + bet(level + 1), arrOperator, 0)
      Calculate(level + 1, number - bet(level + 1), arrOperator, 1)
      If Math.Abs(CLng(number) * CLng(bet(level + 1))) <= Integer.MaxValue Then _
        Calculate(level + 1, number * bet(level + 1), arrOperator, 2)
      If bet(level + 1) <> 0 Then _
        Calculate(level + 1, number \ bet(level + 1), arrOperator, 3)
    End If
  End Sub

  Public Sub Main()
    Dim i, temp(ben) As Byte

    Calculate(0, bet(0), temp, 0)

    Console.Clear()
    For i = 0 To ben - 1
      If i > 0 Then
        If i > 1 Then Console.Write(")")
        Console.Write(" " & operators(minOperators(i)) & " ")
      Else
        Console.Write(StrDup(ben - 2, "("))
      End If

      Console.Write(bet(i))
    Next
    Console.WriteLine(" = " & bec + minDiff)

    Console.ReadLine()
  End Sub
End Module
ċ
tb_cel.vb.txt
(2k)
Gábor Fehér,
2012. márc. 4. 7:01
Comments