MATRIZ -TROCAR VALORES

CISCO 03/04/2014 11:14:22
#436844
Boas
Bom, o objectivo do exercício é, dada uma matriz, trocar o máximo pelo mínimo. por exemplo:
1 2 3 6 2 3
4 5 6 = 4 5 1

eis o módulo que já fiz:
Public Function minpormax(ByVal x(,) As Double) As Double(,)
Dim max, min, a, b, c, d, aux1, aux2 As Single
max = x(1, 1)
min = x(1, 1)
For i = 1 To UBound(x, 1)
For j = 1 To UBound(x, 2)
If x(i, j) > max Then
max = x(i, j)
a = i
b = j
End If
Next
Next
For i = 1 To UBound(x, 1)
For j = 1 To UBound(x, 2)
If x(i, j) < min Then
min = x(i, j)
c = i
d = j
End If
Next
Next
For i = 1 To UBound(x, 1)
For j = 1 To UBound(x, 2)
aux1 = x(a, b)
x(a, b) = x(c, d)
x(c, d) = aux1
Next
Next
Return x
end function
sendo o programa:
Dim x(,), y(,) As Double
x = lermatriz()
y = minpormax(x)
For i = 1 To UBound(x, 1)
For j = 1 To UBound(x, 2)
ListBox1.Items.Add(y(i, j))
Next
Next
eu acho que o erro está quando faço a troca dos valores utilizando a variavel auxiliar...
alguem me consegue ajudar?
JABA 07/04/2014 00:41:03
#436958
Eu fiz um exemplo com matrizes fixas. Qualquer coisa dá uma adaptada ai.

Jogue todo esse codigo abaixo num Form:
===================================

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

Dim matriz(1, 2) As Integer

matriz(0, 0) = 1
matriz(0, 1) = 2
matriz(0, 2) = 3
matriz(1, 0) = 4
matriz(1, 1) = 5
matriz(1, 2) = 6

Exibir(matriz)
Exibir(TrocarMaxPorMin(matriz))

End Sub

Public Sub Exibir(vetor(,) As Integer)

Dim valor As String = [Ô][Ô]
For x As Integer = 0 To 1
For y As Integer = 0 To 2
valor = valor & [Ô] | [Ô] & vetor(x, y) & [Ô] | [Ô]
If y = 2 Then valor = valor + vbNewLine
Next
Next
MsgBox(valor)
End Sub

Public Function GetIndiceMenorValor(vetor(,) As Integer) As Point
Dim valor As Integer = vetor(0, 0)
Dim p As New Point
For x As Integer = 0 To 1
For y As Integer = 0 To 2
If vetor(x, y) < valor Then
valor = vetor(x, y)
p.X = x
p.Y = y
End If
Next
Next
Return p
End Function

Public Function GetIndiceMaiorValor(vetor(,) As Integer) As Point
Dim valor As Integer = vetor(0, 0)
Dim p As New Point
For x As Integer = 0 To 1
For y As Integer = 0 To 2
If vetor(x, y) > valor Then
valor = vetor(x, y)
p.X = x
p.Y = y
End If
Next
Next
Return p
End Function

Public Function TrocarMaxPorMin(vetor(,) As Integer) As Array
Dim p1 As Point = GetIndiceMaiorValor(vetor)
Dim p2 As Point = GetIndiceMenorValor(vetor)
Dim max As Integer = vetor(p1.X, p1.Y)
Dim min As Integer = vetor(p2.X, p2.Y)
vetor(p1.X, p1.Y) = min
vetor(p2.X, p2.Y) = max
Return vetor
End Function

End Class
Faça seu login para responder