PDA

View Full Version : Palindrome in Visual Basic 2008


peter1988
Sep 29, 2009, 06:57 AM
May anyone tell me how to create a palindrome function in Visual Basic 2008, I need some help in my project...

Perito
Sep 29, 2009, 07:27 AM
If a palindrome is the same read forward and backward, then this is simple.

Simply create a string of random characters using only numerals. Once the string is half as long as you want the final string to be, add the characters to the end of the string, but in reverse order. You also can, optionally, skip the last character of the original string as it can stand alone. Here's one way to do it, but certainly not the only way.

Private Function GeneratedPalindromeValue(ByVal DesiredLength As Integer) As Integer
Dim tStr As String = ""
Dim ProcessingLength As Integer = DesiredLength \ 2 ' Note integer division
Dim tChar As String
Randomize() ' so we don't get the same string every time we run this.

For i As Integer = 0 To ProcessingLength
tChar = Rnd().ToString ' generate a "Single" and convert it to a string.
tStr += tChar.Substring(tChar.Length - 1, 1) ' grab the last numeral in the string
Next

Dim J As Integer = tStr.Length - 1 ' index to point to characters in tStr
If (DesiredLength \ 2) * 2 <> DesiredLength Then ' odd length?
J -= 1 ' odd length, don't duplicate the last character
ProcessingLength -= 1 ' so we don't duplicate the middle character
End If
For i As Integer = 0 To ProcessingLength
tStr += tStr.Substring(J, 1)
J -= 1 ' decrement j, the index.
Next

Return Integer.Parse(tStr)
End Function