korhan
Board Regular
- Joined
- Nov 6, 2009
- Messages
- 215
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
I am trying to make my code more efficient and any help or suggestion is appreciated.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
I am trying to make my code more efficient and any help or suggestion is appreciated.
Code:
Option Explicit
Sub Test2()
Dim StartTime As Double
Dim MinutesElapsed As String
'Remember time when macro starts
StartTime = Timer
' Declare variables
Dim names() As String, textline As String
Dim chrName() As Byte
Dim i As Integer, j As Integer, x As Integer, y As Integer, intLowBnd As Integer, intUppBnd As Integer
Dim strTemp As String
Dim totalScore As Long, currentScore As Long
Open "path\Question 22 Data.txt" For Input As #1
Do Until EOF(1)
Line Input #1, textline
names = Split(textline, """" & "," & """", , vbTextCompare)
names(0) = Replace(names(0), Chr(34), "")
names(UBound(names)) = Replace(names(UBound(names)), Chr(34), "")
Loop
Close #1
intLowBnd = LBound(names)
intUppBnd = UBound(names)
' Alphabetically sort the names array
For x = intLowBnd To intUppBnd - 1
For y = x To intUppBnd
If names(y) < names(x) Then
strTemp = names(x)
names(x) = names(y)
names(y) = strTemp
End If
Next y
Next x
' Loop through the list and get the scores
For i = intLowBnd To intUppBnd
currentScore = 0
chrName = StrConv(names(i), vbFromUnicode)
For j = 0 To UBound(chrName)
currentScore = currentScore + (chrName(j) - 64)
Next j
totalScore = totalScore + (currentScore * (i + 1))
Next i
Debug.Print totalScore
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
Debug.Print "Whole process took: ", MinutesElapsed
End Sub
Last edited: