mercoledì 3 febbraio 2010

Fibonacci rulez.

Ho scritto questo codice per mischiare le parole di un testo usando la successione di Fibonacci [F(n)= F(n-1)+F(n-2) con F(0)=0 e F(1)=1].

Il linguaggio è visual basic (scaricabile gratuitamente MS visual studio express), il form contiene 3 caselle di testo (una invisibile per dati temporanei) e 2 bottoni. Il primo bottone trasforma il testo leggibile in un testo "criptato", il secondo bottone trasforma un testo "criptato" in testo leggibile. Un modulo bas contiene le funzioni.

Non credo sia possibile ottenere un algoritmo più efficiente di questo, se riuscite a crearne uno migliore mandatemelo, sarei felice di studiarlo.

--- codice del form:

Friend Class Form1
Inherits System.Windows.Forms.Form
Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
Dim n As Long
Cursor = System.Windows.Forms.Cursors.WaitCursor
numPAR = contapar((tb1.Text))
numFIB = contafib(numPAR)
Call creaserie(numPAR)
For n = 1 To numPAR
tb2.Text = tb2.Text & PAR(seriefib(n))
Next n
Cursor = System.Windows.Forms.Cursors.Default
End Sub
Private Sub Command2_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command2.Click
Dim n2 As Long
Dim n As Long
Cursor = System.Windows.Forms.Cursors.WaitCursor
numPAR = contapar((tb2.Text))
numFIB = contafib(numPAR)
Call creaserie(numPAR)
For n = 1 To numPAR
For n2 = 1 To numPAR
If seriefib(n2) = n Then
tb2.Text = tb2.Text & PAR(n2)
End If
Next n2
Next n
Cursor = System.Windows.Forms.Cursors.Default
End Sub
Function contapar(ByRef testo As String) As Integer
Dim myc As String
Dim n As Long
tb1.SaveFile(My.Application.Info.DirectoryPath & "/temp.txt", Windows.Forms.RichTextBoxStreamType.PlainText)
FileOpen(1, My.Application.Info.DirectoryPath & "/temp.txt", OpenMode.Input)
n = 1
ReDim PAR(n)
Do While Not EOF(1)
myc = InputString(1, 1)
PAR(n) = PAR(n) + myc
If myc = " " Or myc = vbCrLf Then
n = n + 1
ReDim Preserve PAR(n)
PAR(n) = ""
End If
Loop
FileClose()
contapar = n - 1
End Function
End Class

--- codice del modulo bas

Module Module1
Public PAR() As String
Public numPAR As Integer
Public FIB() As Integer
Public numFIB As Integer
Public serie() As Integer
Public seriefib() As Integer
Sub creaserie(ByRef np As Integer)
Dim n3 As Long
Dim n5 As Long
Dim n4 As Long
Dim n7 As Long
Dim n6 As Long
Dim n As Long
ReDim serie(np)
For n = 1 To np
serie(n) = n
Next n
n6 = np
n7 = 0
rifa:
n4 = 1
n5 = 0
Dim serietmp() As Integer
ReDim Preserve serietmp(1)
serietmp(1) = 0
For n3 = 1 To n6
If n3 <> FIB(n4) Then
n5 = n5 + 1
ReDim Preserve serietmp(n5)
serietmp(n5) = serie(n3)
Else
n7 = n7 + 1
ReDim Preserve seriefib(n7)
seriefib(n7) = serie(n3)
If n4 < n4 =" n4" n5 =" 0" n6 =" n5" n5 =" 1" n =" 3"> npar Then
n = n - 1
ReDim Preserve FIB(n)
Exit For
End If
Next n
contafib = n
End Function
End Module

Nessun commento: