Other Quiz #10 - 2000 buttons quiz

Erel

B4X founder
Staff member
Licensed User
Longtime User
As a developer you should avoid duplicating code. I sometimes see code such as:
B4X:
Sub Button1_Click
x = 1
End Sub

Sub Button2_Click
x = 2
End Sub

...
If you like to write such code then unfortunately this quiz is not for you...

In this quiz you need to add 2000 buttons to the main activity. Each button should show a random number between 1 to 100.
When the user clicks on a button, all buttons with the same number should be brought to front:

upload_2014-1-12_14-47-46.png


A good answer is an answer that correctly implements this quiz.

An excellent answer is an answer that correctly implements this quiz and doesn't iterate over all buttons each time (finding the set of buttons in O(1)).
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4J solution:

SS-2014-01-13_08.43.42.png


B4X:
Sub Process_Globals
   Private fx As JFX
   Private MainForm As Form
   Private views As Map
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   MainForm = Form1
   MainForm.Show
   views.Initialize
   For i = 1 To 2000
     Dim b As Button
     b.Initialize("b")
     b.Text = Rnd(1, 101)
     MainForm.RootPane.AddNode(b, Rnd(0, 600dip), Rnd(0, 400dip), 100dip, 100dip)
     Dim l1 As List
     If views.ContainsKey(b.Text) Then
       l1 = views.Get(b.Text)
     Else
       l1.Initialize
       views.Put(b.Text, l1)
     End If
     l1.Add(b)
   Next
End Sub

Sub b_MouseClicked (EventData As MouseEvent)
   Dim b As Button = Sender
   Dim l1 As List = views.Get(b.Text)
   For Each bb As Button In l1
     bb.RemoveNodeFromParent
     MainForm.RootPane.AddNode(bb, bb.Left, bb.Top, bb.Width, bb.Height)
   Next
End Sub
 
Upvote 0
Top