Saturday, May 21, 2011

The Prisoner’s Dilemma – An Exercise in Inheritance

The prisoner's dilemma is a fundamental problem in game theory that demonstrates why two people might not cooperate even if it is in both their best interests to do so. It was originally framed by Merrill Flood and Melvin Dresher working at RAND in 1950. Albert W. Tucker formalized the game with prison sentence payoffs and gave it the "prisoner's dilemma" name (Poundstone, 1992).

A classic example of the prisoner's dilemma (PD) is presented as follows:

Two suspects are arrested by the police. The police have insufficient evidence for a conviction, and, having separated the prisoners, visit each of them to offer the same deal. If one testifies for the prosecution against the other (defects) and the other remains silent (cooperates), the defector goes free and the silent accomplice receives the full one-year sentence. If both remain silent, both prisoners are sentenced to only one month in jail for a minor charge. If each betrays the other, each receives a three-month sentence. Each prisoner must choose to betray the other or to remain silent. Each one is assured that the other would not know about the betrayal before the end of the investigation. How should the prisoners act?

If we assume that each player cares only about minimizing his or her own time in jail, then the prisoner's dilemma forms a non-zero-sum game in which two players may each either cooperate with or defect from (betray) the other player. In this game, as in most game theory, the only concern of each individual player (prisoner) is maximizing his or her own payoff, without any concern for the other player's payoff. The unique equilibrium for this game is a Pareto-suboptimal solution, that is, rational choice leads the two players to both play defect, even though each player's individual reward would be greater if they both played cooperatively.

In the classic form of this game, cooperating is strictly dominated by defecting, so that the only possible equilibrium for the game is for all players to defect. No matter what the other player does, one player will always gain a greater payoff by playing defect. Since in any situation playing defect is more beneficial than cooperating, all rational players will play defect, all things being equal.

In the iterated prisoner's dilemma, the game is played repeatedly. Thus each player has an opportunity to punish the other player for previous non-cooperative play. If the number of steps is known by both players in advance, economic theory says that the two players should defect again and again, no matter how many times the game is played. However, this analysis fails to predict the behavior of human players in a real iterated prisoners dilemma situation, and it also fails to predict the optimum algorithm when computer programs play in a tournament. Only when the players play an indefinite or random number of times can cooperation be an equilibrium, technically a subgame perfect equilibrium meaning that both players defecting always remains an equilibrium and there are many other equilibrium outcomes. In this case, the incentive to defect can be overcome by the threat of punishment.

In casual usage, the label "prisoner's dilemma" may be applied to situations not strictly matching the formal criteria of the classic or iterative games, for instance, those in which two entities could gain important benefits from cooperating or suffer from the failure to do so, but find it merely difficult or expensive, not necessarily impossible, to coordinate their activities to achieve cooperation.

Strategy for the classic prisoner's dilemma





In "win-lose" terminology the table looks like this:



Imagine you are player A. If player B decides to stay silent about committing the crime then you are better off confessing, because then you will get off free. Similarly, if player B confesses then you will be better off confessing, since then you get a sentence of 3 months rather than a sentence of 1 year. From this point of view, regardless of what player B does, as player A you are better off confessing. One says that confessing (defecting) is the dominant strategy.

As Prisoner A, you can accurately say, "No matter what Prisoner B does, I personally am better off confessing than staying silent. Therefore, for my own sake, I should confess." However, if the other player acts similarly then you both confess and both get a worse sentence than you would have gotten by both staying silent. That is, the seemingly rational self-interested decisions lead to worse sentences—hence the seeming dilemma. In game theory, this demonstrates that in a non-zero-sum game a Nash equilibrium need not be a Pareto optimum.

Although they are not permitted to communicate, if the prisoners trust each other then they can both rationally choose to remain silent, lessening the penalty for both of them.



Sumber:
Book: Billy Hollis, 1999, Visual Basic 6: Design, Specification and Objects, Prentice-Hall Series on Microsoft Technologies
http://en.wikipedia.org/wiki/Prisoner's_dilemma
http://www.iterated-prisoners-dilemma.net/
http://www.lifl.fr/IPD/ipd.html.en

Wednesday, May 4, 2011

Controls Collection in VB6

The Controls Collection is a built-in collection belonging to a form and is maintained by Visual Basic. The Controls Collection contains references to all the controls on that form. Each member of the collection points to a different object on that form—for example, a TextBox, ComboBox, ListView, and so on.

Each form in a project has its own Controls Collection that you can use to navigate through the different controls on a form. You can refer to each control within the collection as follows:

Form.Controls(index)

where Form is the form name, and Index is an integer value referring to the desired control. Since the Controls Collection is zero-based, Index values range from 0 up through a number that is one less than the total number of controls on the form. If you have 10 controls on a form, the Index values for the Controls Collection would range from 0 through 9.

You will usually use in a Controls Collection when you need to process all the controls or the majority of the controls on a given form. You can loop through a Controls Collection either with a For Next loop, as in Prog 1, or with a For Each loop, as inProg 2.

Prog 1
LOOPING THROUGH A CONTROLS COLLECTION WITH A FOR NEXT LOOP
For I = 0 To Form1.Controls.Count - 1
' process Form1.Controls(I)
Next

Prog 2
LOOPING THROUGH A CONTROLS COLLECTION WITH A
FOR EACH LOOP
For Each obj In Form1. Controls
' process obj
Next

A common use of the Controls Collection is to clear all the controls on a form. If the user wants to reset all the fields on a data entry form, you can code a Clear button with code such as that found in Prog 3

Prog 3
CODE TO RESET ALL FIELDS ON A DATA ENTRY FORM

Private Sub cmdClear_Click()
Dim objControl As Control
Dim sTemp As String
For Each objControl In Me.Controls
If TypeOf objControl Is TextBox Then
' clear the text
objControl.Text = ""
ElseIf TypeOf objControl Is ComboBox Then
' reset the listindex
objControl.ListIndex = -1
ElseIf TypeOf objControl Is Label Then
' leave labels as is
ElseIf TypeOf objControl Is CommandButton Then
' leave commandbuttons as is
ElseIf TypeOf objControl Is MaskEdBox Then
' clear the masked edit control
sTemp = objControl.Mask
objControl.Mask = ""
objControl.Text = ""
objControl.Mask = sTemp
Else
' leave any other control alone
End If
Next
End Sub

This code in the Listing loops through all the controls on a form and clears each control based on its type. To clear a TextBox control, for example, you would set the Text property to a 0-length string. To clear a CheckBox, you would set the value property to vbUnchecked.

Notice that the code in the Listing uses an If statement to determine the type of control being cleared. You must make sure you know the type of control you reference to avoid runtime errors. Errors occur if you try to reference a property of a control that is not a valid property. If the first control on a form is a TextBox, you can clear that control by using:

Me.Controls(0).Text = ""

If, on the other hand, the first control is a CheckBox that does not have a Text property, with the same code, you will get a runtime error from Visual Basic. The Clear button code example avoids this problem by checking for specific control types within the Controls Collection. The syntax for the If statement is as follows:

If TypeOf objectname Is objecttype Then
' code
EndIf

where objectname is the object or control (that is TextBox, ComboBox, and so forth) on which you are working and objecttype is the class of the object. Using this If structure before you reference a control through the Controls Collection will help you avoid runtime errors.

Forms Collection pada VB6

This section discusses the use of VB's Forms Collection. Topics covered include:
  • using methods and properties of the collection,
  • using specific items within the Forms Collection (referencing individual forms),
  • looping through the collection,
  • verifying loaded forms,
  • unloading forms from the collection.
In Visual Basic, a collection is just a group of objects. If you have more than one form in a project, you would have a Forms Collection that you can use to easily manipulate all forms or just one specific form.The Forms Collection is a built-in or intrinsic collection of VB. Another example of a collection built into VB is the Controls Collection that will return all the controls contained on the specified form.

The Forms Collection contains the loaded forms of all VB form types. MDI Parent forms, MDI Child forms, and non-MDI forms are all included in the collection, along with any forms created at runtime.

The Forms Collection only contains the forms that are currently loaded in memory. If a project contains multiple forms and only the Startup form has been loaded, the collection will only have one item. To be included in the Forms Collection, all forms must be loaded. They do not have to be shown onscreen, only loaded.

If a form is the unloaded from memory, that form is no longer part of the Forms Collection. The collection will reduce its count by one, and that form will no longer be available in the collection.


Methods and Properties of the Forms Collection

Most VB collections have various methods or properties that will return information regarding the collection of objects. The Forms Collection has only one property, Count. This property gives the total number of forms currently loaded by the application. To find the total number of forms in the project, just use code such as the following:

iFormCount = Forms.Count

To test the Forms.Count property in VB, use a single form and place one command button on the form. Open the code window for the command button and type the code shown in Listing 4.14.

PROGRAMMING WITH FORMS.COUNT PROPERTY

Sub Command1_Click()
Msgbox "The Forms Collection has " & _
Forms.Count & _
" forms currently", _
vbInformation, "Forms Count"
End Sub

This code will show a message box with a string that contains the number of forms in the collection. Remember that only loaded forms are in the collection. Any form that has not been loaded or that has been unloaded will not be part of the collection.

Using specific items within the Forms Collection

Each object in the collection can also be referred to by its specific ordinal number. This is an item number automatically assigned as the new items are added to the collection.

When referring to the ordinal number of a form, you must always remember that the Forms Collection is 0-based. The first item in the collection will always have the ordinal value of 0. The following lines demonstrate using the item value:

Forms(0).Caption
Forms(1).Name
Forms(2).Width

This code assumes that a VB project has three forms and that all forms have been loaded into memory. The first line will return the Caption of the very first item (item 0) in the collection. The second line will return the Name property of Form(1). The third line will return the value of the last form's width.

These code examples show how easy referencing specific items in the collection can be. This can be an alternative method to using the specific form names in a given project. With the Forms Collection, you also do not have to know the name of a given form to control it. This will assist in manipulating forms generated at runtime.

Looping Through the Forms Collection

Another way to use the Forms Collection is with various looping techniques. By using For...Next, For...Each, or Do...While statements, the programmer can loop through the collection to affect all the forms, search for specific forms, and search for specific properties or even values. This will assist in searching for information without having to program every form name individually.

A simple example would be to retrieve each form's Caption, as shown below.

LOOPING THROUGH THE FORMS COLLECTION WITH FOR...NEXT

Dim iLoop as Integer
For iLoop = 0 to Forms.Count - 1
MsgBox Forms(iLoop).Caption
Next iLoop

This code declares an integer variable for looping and then sets up the For...Next statement. Notice iLoop = 0. You must start at 0 because collections are 0-based. Because you will not always know the amount of forms in the collection, you can take the Forms.Count and subtract 1 from the total. You must remove 1 because the Count starts at 1 and the Collection starts at 0. When this sample code is
run, a message box displays with the Caption property of every form in the collection.

An alternative to the For... Next loop would be the For...Each loop, which does not depend on an integer counter (see Listing 4.16).

LOOPING THROUGH THE FORMS COLLECTION WITH FOR...EACH

Dim frmCurr as Form
For each frmCurr in Forms
MsgBox FrmCurr.Caption
Next frmCurr

This is probably preferable to the For...Next loop because you don't have to keep track of position in the collection.

Using the Forms Collection to Verify Whether a Form Is Loaded

When a form is referenced in code, it automatically loads the form into memory. An advantage of the Forms Collection is that it contains only forms that have been loaded into memory. This enables the programmer to test for a specific form by looping through the collection and testing the Name property of every item in the collection.

An example of this code is found in Listing program below.

VERIFYING WHETHER A PARTICULAR FORM IS LOADED

Sub Command1_Click()
Dim frmCurr as Form
For each frmCurr in Forms
If frmCurr.Name = "Form3" Then
MsgBox "Form3 has been loaded"
End If
Next frmCurr
End Sub

This code declares a form variable for looping and then sets up the For...Each statement. Inside the For...Each statement is an If test. With this code you are looking through each item in the collection and testing the property frmCurr.Name. This allows frmCurr to represent every form that is loaded in the collection. If the Name property is equal to Form3, a message box displays informing us that Form3 has been loaded into memory.

This code sample requires a project with at least three forms. The default form names are expected, and the Form_Load event is responsible for loading all forms into memory. Remember that if the forms are not loaded at the moment the code runs, they will not be included in the collection.

Using the Forms Collection to Unload All Forms

Another common use of the Forms Collection is to unload all forms. Although the End statement would provide a faster, simpler way to terminate the application, it can have unwanted effects because a call to End will immediately terminate the application without allowing any further events (such as Unload events) to run. Looping through the Forms Collection to unload all members might seem like a more complicated way to do the task, but it allows normal processing of Unload and other events.

The code of Listing 4.18 shows one way to control the loop. First, you must determine the total number of elements in the collection then reduce that number by one to accommodate for that fact that the collection is 0-based. The loop unloads collection members in reverse order from the highest-numbered member to the lowest. This is due to the fact that, after each unload of a collection member, the number of members in the collection decreases by one.

UNLOADING ALL FORMS WITH A DESCENDING FOR...NEXT LOOP

Sub cmdClose_Click()
Dim iLoop As Integer
Dim iHighestForm as integer
iHighestForm = Forms.Count — 1
For iLoop = iHighestForm To 0 Step — 1
Unload Forms(iLoop)
Next iLoop
End Sub

A more elegant way to unload all forms would be with a For...Each loop, as in the example of Listing program below.

UNLOADING ALL FORMS WITH A FOR...EACH LOOP

Sub cmdClose_Click()
Dim frmCurr as Form
For each frmCurr in Forms
Unload frmCurr
Next frmCurr
End Sub

Both of the above methods assume that at least one form has been loaded in the collection and that a command button named cmdClose is on one of the loaded forms. After run, all forms should be unloaded, and the project will terminate if no other forms are in memory.