Saturday, July 18, 2009

techInterview.org - Joel on Software - array manipulation question - VB solution

This question was asked on the techInterview.org list on Joel on Software:

http://discuss.techinterview.org/default.asp?interview.11.768781.6

array manipulation

Given an array with some repeating numbers. Like 12,6,5,12,6.
output should be printed as 12,12,6,6,5; i.e, all occurences of the no. should come together and nos. should come in the order given in the array. Suggest a optimal solution to this. sanjay kasat

---
Here's my VB solution.

Here's a VB solution, using a Dictionary. Essentially this is a hash solution.

Module Module1

' data structure for recording counts
Public Class Node
Private m_count As Integer = 0
Private m_value As Integer

Public Sub New(ByVal x As Integer)
m_value = x
m_count = 0
End Sub

Public Shadows Function toString()
Return m_value.ToString()
End Function

Public Property count() As Integer
Get
Return m_count
End Get
Set(ByVal value As Integer)
m_count = value
End Set
End Property

Public Property val() As Integer
Get
Return m_value
End Get
Set(ByVal value As Integer)
m_value = value
End Set
End Property
End Class

' to record ordering
Dim m_list As List(Of Node) = Nothing

' to record counts
Dim m_hash As Dictionary(Of Integer, Node) = Nothing

'''
''' Initialize data structures for a new run
'''

Private Sub init()
m_list = New List(Of Node)
m_hash = New Dictionary(Of Integer, Node)
End Sub

'''
''' Add a new element from the input list
'''

Private Sub add(ByVal x As Integer)
Dim p As Node
Try
p = m_hash(x)
p.count = p.count + 1
Catch ex As Exception
p = New Node(x)
p.count = 1
m_list.Add(p)
m_hash(x) = p
End Try
End Sub

Public Sub outputResults()
For Each x In m_list
For i = 0 To x.count - 1
Console.Write(x.val & " ")
Next
Next
Console.WriteLine()
End Sub

Public Sub test1()
Dim x As New List(Of Integer)
x.Add(12)
x.Add(13)
x.Add(12)
x.Add(2)
x.Add(12)
x.Add(2)
x.Add(12)
x.Add(14)
init()
For Each y In x
add(y)
Next
outputResults()
End Sub

Sub Main()
test1()
Console.ReadLine()
End Sub

End Module

No comments:

Post a Comment