Have programmers developed an intelligence database of firms that one should avoid working for and firms that one should try to work for? Is it a good idea to work on a project as an independent contractor first? Sort of test out an employer before deciding to become an employee? Many firms do that for potential employees.
Nathaniel10 34 Junior Poster
Nathaniel10 34 Junior Poster
Thanks for the quick reply.
It seems to me that being in a union protected you and the work environment. That is what unions are for. But the rate of unionization is much lower in 2015 than in, say, 1985. I would guess that there are only a handful of unionized workplaces in the tech industry.
If a programmer cannot find a union workplace, then he/she is subject to the whims of the boss. In my experience, a worker cannot choose who the boss is, only who the boss isn't (by resigning). Do you have any suggestions as to how to read a potential IT boss during the interview process to get an idea of what it will be like to work under that person?
Nathaniel10 34 Junior Poster
Last week the New York Times semed to skewer Amazon over the stress it places on its workers. I read today that Dustin Mosokvitz confirms such high stress work environments and confesses that his health deteriorated while at Facebook as a result. I don't work in IT but I hope to eventually. However, I absolutely DO NOT want to work in that type of environment. I have already done that in my first field of study and do not intend to repeat those experiences.
My questions for those who work or have worked in IT is: Are these articles truly an accurate description of life in IT? Are there any opportunities for IT work that is not so subject to what Moskovitz called 'unrealistic expectations'? Are there specialties within IT, (say security research?), where the work environment might not be so high intensity? Thanks in advance.
Nathaniel10 34 Junior Poster
OK. I am stuck.
I have no code to show, but I will describe my predicament with pseudo-code.
I am able to arrive at the amount of wheat and widgets that each country produces in its own country. I use arbitrary prices of wheat and widgets in each country. I can set arbitrary international prices for wheat and widgets which will be the prices for imports and exports. I can set an international price of wheat that is higher than the price of wheat in Alphastan but lower than that in Betastan. Alphstan will import wheat at the lower international price and Betstan will export wheat at the higher price. The opposite for widgets so that Alphastan will export widgets and Betastan will import widgets.
I can make the international price a scalar. I think I need to access the Alphastan and Betastan objects simultaneously because the amount of wheat that Alphastan imports must equal the amount of wheat that Betastan exports. That is impossible the way I have currently structured the Country class.
variable international price of wheat;
variable international price of widgets;
value of total production = domestic price of wheat times amount wheat produced +
domestic price of widgets times amount of widgets produced;
value of total consumption = international price of wheat times (amount of wheat produced +
amount of wheat imported (or minus international price times amount of wheat exported)) +
international price of widgets times (amount of widgets produced + amount of widgets imported …
Nathaniel10 34 Junior Poster
I think the instantiation of countries works better as follows:
class View {
public function __construct() {}
public function printOutput($z) {
echo "The country of " . $z -> getName() . " produced " . $z -> getWheat() . " bushels of wheat, and " . $z -> getWidgets() . " widgets.<br />";
}
public function printOppcost($z) {
echo "The opportunity cost of producing a widget in " . $z -> getName() . " is " . abs($z -> getOppcost()) . " bushels of wheat.<br />";
}
public function worldTotals($z) {
$totalLabor = 0;
$totalWheat = 0;
$totalWidgets = 0;
foreach ($z as $key => $g) {
$totalLabor += $g -> getLabor();
$totalWheat += $g -> getWheat();
$totalWidgets += $g -> getWidgets();
}
echo "The total quantity of labor in the world is " . $totalLabor . " worker-years.<br />";
echo "The world production of wheat is " . $totalWheat. " bushels, and the world production of widgets is " . $totalWidgets . " units.<br />";
}
}
$country[0] = new Country('Alphastan', 100, 200, 0, 0, 0.75, 0.4, 1.25, 0.73, 0.50, 0);
$country[0] -> output($country[0]);
$country[0] -> slope($country[0]);
$country[1] = new Country('Betastan', 200, 500, 0, 0, 0.60, 0.30, 1.50, 0.55, 0.40, 0);
$country[1] -> output($country[1]);
$country[1] -> slope($country[1]);
$v = new View();
$v -> printOutput($country[0]);
$v -> printOutput($country[1]);
$v -> printOppcost($country[0]);
$v -> printOppcost($country[1]);
$v -> worldTotals($country);
So far, having the countries as a vector, permits the computation of world values by looping over the rows of the vector …
Nathaniel10 34 Junior Poster
In a prior version, the Country class was abstract and I extended it for individual countries. I found that I was repeating the same class for each country.
Pritaeas, I am trying to grasp what you are suggesting. I would NOT be instantiating countries in the World class, as I do with my current version, correct? Each country would be a property of whatever is instantiated in the World class. What exactly gets instantiated? What is the object? What do you mean by "Your methods will return a data object with the information you need."?
Your getEndowments() function gives me an idea. I should be able to determine total Labor endowments in the world using 'foreach' to loop through the countries. The same for world production of wheat and widgets. As it stands now, these variables (world labor, world wheat, world widgets) would be scalars that are not associated with any object, correct?
Nathaniel10 34 Junior Poster
In my continuing quest to improve my understanding of OPP in PHP, I have developed another project. It is closer to my field and a real life project I hope to develop, than my previous post using geometric shapes.
This draft program is the simplest version. I want to increase the complexity of this example and that requires more a complex class structure. I don't know how to do that. Here is the draft program.
class Country {
private $name = 'default name';
private $land; // The endowment of land in the country.
private $labor; // The endowment of labor in the country.
private $wheat;
private $widgets;
private $allocLand; // The proportion of land in a country that is allocated to the production of wheat.
private $allocLabor; // The proportion of labor in a country that is allocated to the production of wheat.
private $techfactor; // A factor-neutal technology coefficient for the production function.
private $wheatpower; // The power coefficient on land in the production of wheat. The function has constant returns to scale.
private $widgetpower; // The power coefficient on land in the production of widgets. The function has constant returns to scale.
private $oppcost; // The opportunity cost, in terms of wheat, of producing one additional widget.
public function __construct($name, $land, $labor, $wheat, $widgets, $allocLand, $allocLabor, $techfactor, $wheatpower, $widgetpower, $oppcost) {
$this -> name = $name;
$this -> land = $land;
$this -> labor = $labor;
$this -> wheat = $wheat;
$this -> widgets = $widgets;
$this -> …
Nathaniel10 34 Junior Poster
@Jkon,
In your example you use many times arrays when actually you are describing an object , for example the chars method of the Hexahedron.
This makes no sense to me. As I understand it, an object is an instance of a class. Instantiation occurs with the statement $objectName = new className;
. I do not use the method chars() nor the related variable $char as an instance of the Model class. I use $char as a data structure. To my knowledge, objects are not variables and variables are not objects. Correct me if I am wrong.
First of all you have no reason to create triads of Model View Controller classes.
I think I said that when I wrote that the Shape class became redundant in the MVC framework of this example. I would not have learned that nor, more importantly, understood why, if I had not gone through the exercice of adapting the MVC concept to my Shape example. It sounds like you, and Diafol earlier, are referring to Hierarchical MVC. The tutorial in this site shows that one can have super- and subclasses for the Model, View, and Controller with inheritances between the parents and children. I found it easier to understand an abstract Shape super-class with concrete sub-classes of 4-sided solids, 6-sided solids, 8-sided solids, and ellipsoid solids, than the potential HMVC representation of such a situation.
I have come accross PHP examples which use 'echo' to display HTML code or store HTML …
Nathaniel10 34 Junior Poster
@Jkon,
Nathanaiel I continue to see in your example things that are defiantly not PHP OOP , but are mix of PHP functional with procedural.
I don't know what that means. What is functional PHP versus procedural PHP?
Even if this thread is only about OOP are you happy that a method dimensions($dim) (that is not declare public because you think it dirty OOP as well) do several things that don't belong to a single method (it computes and it output as well)
I am not sure of what this means either. The dimensions() function in the View class is not declared public because I overlooked that. My understanding is that when visibility is not declared it is public. What is "dirty" OOP?
The dimensions() function in the View class outputs the input form. I don't see where it is computing anything. Please explain.
Nathaniel10 34 Junior Poster
Well, thanks to everyone who posted replies to my questions, research on the topic, and trail and error experimentation, I was able to apply the MVC concept to my Shape example and get respectable results. I am posting the program below. I included code that I commented out to show how dramatically different (in my eyes) this version is from earlier ones. (I do get an undefined index error on the initial loading of the program.)
class Model {
public function __construct() {
}
}
abstract class Shape {
// abstract public function getVolume($length, $width, $height);
// public function getWeight() {
// return * $this -> getVolume($length, $width, $height);
// }
}
class Hexahedron extends Shape {
const density = '2.5';
// public $length;
// public $width;
// public $height;
public function dims() {
return $dim = array("length", "width", "height");
}
public function names() {
return $name = array("perimeter", "area", "volume", "weight");
}
public function chars($length, $width, $height) {
$char[0] = 4 * ($length + $width + $height);
$char[1] = 2 * ($length * $width + $length * $height + $height * $width);
$char[2] = $length * $width * $height;
$char[3] = self::density * $length * $width * $height;
return $char;
}
// public function __construct($length, $width, $height) {
// $this -> setLength($length);
// $this -> setWidth($width);
// $this -> setHeight($height);
// }
// public function setLength($length) {
// $this -> length = $length;
// }
// public function setWidth($width) {
// $this -> width = $width;
// }
// …
Nathaniel10 34 Junior Poster
Thanks, diafol. I will review your suggested code to understand as much of it as I can.
Nathaniel10 34 Junior Poster
After some more research, I found a good example of implementing an input form in MVC. I was able to successfully modify the "The Beatles" example from yesterday to include an input form. It is below. The code isn't pretty but it works.
class Model {
public $names;
function __construct() { }
function names() {
return $names = array("Johnny", "Paul", "George", "Ringo");
}
function updateNames($name0, $name1, $name2, $name3) {
return $this ->names = array($name0, $name1, $name2, $name3);
}
}
class View {
function __construct() {}
function formNames() {
echo "<form method=post name=\"form1\" action=\"mvcpractice4.php\"></ br><div class=\"row\"></ br>";
for ($i = 0; $i < 4; $i++) {
echo "<label for=\"length\">Enter first name: </label></ br>
<input style=\"font-size:12pt\" type=\"text\" id=\"length\" name=\"name".$i."\" value=\"\" size=\"15\"/></ br>
<br style=\"clear:left\"/></ br>";
}
echo "</div></ br><input style=\"font-size:12pt\" type=submit name=submit value=\"Compute\" ></ br>
<input type=hidden name=submitted value=\"true\" >";
}
function viewNames($names) {
echo "<table><th>Some Group</th>";
for ($i = 0; $i < 4; $i++) {
echo "<tr><td>".$names[$i]."</td></tr>";
}
echo "</table>";
}
}
class Controller {
private $p;
function __construct() {
$this -> p = new Model();
}
public function submitNames() {
if (!isset($_POST['submitted']))
return;
if (isset($_POST['name0']) && isset($_POST['name1']) && isset($_POST['name2']) && isset($_POST['name3'])) {
$this -> p -> updateNames($_POST['name0'], $_POST['name1'], $_POST['name2'], $_POST['name3']);
}
}
function uploadNames() {
$v = new View();
$v -> formNames();
}
function loadNames() {
$v = new View();
$v -> viewNames($this -> p -> names);
}
}
$cp = new Controller();
$cp -> uploadNames();
$cp -> submitNames();
$cp -> loadNames();
I want to apply the MVC …
Nathaniel10 34 Junior Poster
I found and reviewed several examples of MVC but really only one was sufficiently clear and simple for me to reasonably understand. I played around with it to see if I could re-create things. I also consolidated it into one file.
class Model {
function __construct() { }
function names() {
return $names = array("John", "Paul", "George", "Ringo", "Lennon", "McCartney", "Harrison", "Starr");
}
}
class View {
function __construct() {}
function viewNames($names) {
echo "<table><th>The Beatles</th>";
for ($i = 0; $i < 4; $i++) {
echo "<tr><td>".$names[$i]."</td><td>".$names[$i+4]."</td></tr>";
}
echo "</table>";
}
}
class Controller {
private $p;
function __construct() {
$this -> p = new Model();
}
function loadNames() {
$v = new View();
$v -> viewNames($this -> p -> names());
}
}
$cp = new Controller();
$cp -> loadNames();
I have a decent understanding of the Model and View classes. The Model class processes data, in this case given in the array. The View class formats inputs and outputs, in this case only output.
The Controller class is less intuitive to me. It seems an instance of the Model class is being created in the Controller class. I suppose it is to be able to access the data in the Model class. Then the function in the Controller class creates an instance of the View class. I supose to be able to transfer the data it accessed from the Model class to the View class.
The last two lines create an instance of the Controller class and essentially …
Nathaniel10 34 Junior Poster
Thank you for the very informative replies.
I am getting that abstract classes need to contain all the common elements of all the child classes. Abstract methods are methods that are declared (given a name) but not defined (have no body or return statement), meaning they don't actually do anything. I did an experiment. I found that if an abstract method is declared in an abstract parent class, it must be defined in the child class or a fatal error results. To resolve the error, the (concrete) child class must either be made abstract as well or the abstract method inherited from the abstract parent must be defined, i.e. given something to do.
I take from this that whatever is contained in an abstract parent class must be repeated and defined in every (concrete) child class. I presume that this is what Pritaeas means by the abstract class is like a blueprint and what Jkon means when he said that if every ancestor has a getVolume() method, then it should be declared in the abstract parent class.
I did some research on the Model-View-Controller concept. It is very new to me. I first learned PHP from a book written by Larry Ullman. The focus was on using PHP with MySQL. Multiple files were used for headers, footers, and connecting to and accessing the database. The MVC concept was completely absent. I am surprised I am hearing of this only in 2015 as it was first developed and proposed in 1979. …
Nathaniel10 34 Junior Poster
@diafol,
Thank you for your reply. I did some brief research on abstract classes. I agree with you. The way I have made this practice example evolve, the 'Shape' class has the characteristics of an asbtract class.
I did not get a good feel for why a class should be made abstract. What are the benefits to a program from making a class abstract? Only one of the six tutorials I read specifically addressed this issue. It said that preventing instantiation in and grouping all common properties and methods into the abstract class improves organization and functionality of the entire program. It is most beneficial in large complex programs.
For my example, I can see how forcing the instantiation of particular geometric shapes to occur in child classes specific to those shapes makes the organization of the program clearer. It allows the distribution of properties and methods unique to certain shapes to be incuded in only those child classes. For example, the constant pi is not needed in any shape with only straight lines, so it can be put in the Ellipsoid class and omitted from the Hexahedron class.
The tutorials I read also mentioned abstract methods but did not explain what they were or how they are used, at least in a way that I could understand. What are abstract methods and how are they used? Is the getWeigth() function in Shape a candidate for an abstract method?
Thanks in advance.
Nathaniel10 34 Junior Poster
OK. After some experimentation, the following code for inheritance works.
class Shape {
const density = '2.5';
public function getWeight() {
return self::density * $this -> getVolume();
}
}
[snip]
$rectangle0 = new Hexahedron($length, $width, $height);
$rectangle0 -> setLength("$length");
$rectangle0 -> setWidth("$width");
$rectangle0 -> setHeight("$height");
?>
<?php echo $rectangle0 -> getWeight() ?>
However, I am not clear as to why the code works. I understand that the child class Hexahedron is inheriting the properties (density) and methods (getWeight()) of the parent class Shape. I don't understand how the parent class (Shape) is accessing the getVolume() function from the child class (Hexahedron). Is it because the function is public? Is it possible for inheritance to "go backwards" from child to parent?
As I am writing this I am still experimenting. I made the getVolume() function private. I received an error message: Fatal error: Call to private method Hexahedron::getVolume() from context 'Shape' in C:\Local\phpoop\practice2.php on line 28. So I guess I answered my own question. Parent classes can access public properties and methods from child classes. I hope someone much more knowledgeable than me can confirm this for me.
Another experiment. I made the getWeight() function in the parent class, Shape, private. I received the following error message: Fatal error: Call to private method Shape::getWeight() from context '' in C:\Local\phpoop\practice2.php on line 126. So. Does this mean that child classes cannot inherit or access private properties and methods from parent classes? Again, I hope someone much more knowledgeable than me can …
Nathaniel10 34 Junior Poster
This is an addendum to my post earlier today.
1)
There are closing brace brackets missing from the two constructors, lines 40 and 76.
2)
There is an extra 'public' on line 53.
3)
Lines 105 and 111 should be $rectangle0 = new Hexahedron($length, $width, $height);
and $sphere1 = new Ellipsoid($x_radius, $y_radius, $z_radius);
, respectively.
Nathaniel10 34 Junior Poster
Thanks very much for the detailed reply, Jkon. Though I understand the logic of the multi-file program, the mechanics of the RectangleController file are beyond me at this time.
I used many of your suggestions in my next practice iteration. I learned something! If one does not specify the visibility of a property, then one must identify it as a property by using the keyword 'var'. The 'var' keyword is optional if one precedes a property with 'private', 'public', or 'protected'.
I tried to learn about inheritance. I am having a serious problem. When I include the function call lines of the parent class, (currently commented out), I get an error saying that there is an unexpected scope resolution operator. I am lost. Please help. Here is the current PHP code.
<?php
$length = array_key_exists('length', $_POST) ? $_POST['length'] : null;
$width = array_key_exists('width', $_POST) ? $_POST['width'] : null;
$height = array_key_exists('height', $_POST) ? $_POST['height'] : null;
$x_radius = array_key_exists('x_radius', $_POST) ? $_POST['x_radius'] : null;
$y_radius = array_key_exists('y_radius', $_POST) ? $_POST['y_radius'] : null;
$z_radius = array_key_exists('z_radius', $_POST) ? $_POST['z_radius'] : null;
if ($length == "") {$length = 0;}
if ($width == "") {$width = 0;}
if ($height == "") {$height = 0;}
if ($x_radius == "") {$x_radius = 0;}
if ($y_radius == "") {$y_radius = 0;}
if ($z_radius == "") {$z_radius = 0;}
?>
<?php
class Shape {
const density = '2.5';
// function getWeight() {
// return $this -> Shape::density * getVolume();
// }
}
class Hexahedron extends Shape …
Nathaniel10 34 Junior Poster
Thanks very much for your replies.
@pixel,
I am asking the forum to help me teach myself PHP OOP. In so doing, others will also be helped in teaching themselves PHP OOP.
@Jkon,
Your comments are very enlightening. I first learned about classes and OOP in C++. The book I used and the examples and tutorials I followed did not at all give the impression that there a lot of developer/programmer 'discretion' in OOP. There seemed to be an emphasis on best practices to which everyone was expected to adhere.
I plan to explore visibility issues later when programs are sufficeintly complex for visibility to matter.
I removed the keyword var and received an error. A function was expected rather than a variable. Restoring var removed the errror. I am running PHP 5.5.24 on XAMPP 5.6.8.
I capitalize in the function name because I follow the camel hump convention. Many tutorials followed this convention, while others used the underscore convention. I capitalized the variable in the setter functions because that is what the example I followed did. I used the double quotation marks on the fucntion argument for the same reason. I put spaces around the arrow operator because I found it easier for me to read.
One of the reasons I wanted to learn OOP in PHP rather than continue with C++ was the ease of integrating it with HTML. I have been using PHP with HTML for projects involving databases (MySQL) and extensive computations. I have seen CodeAcademy …
Nathaniel10 34 Junior Poster
I want to increase my knowledge of PHP by learning about classes. I wrote the following very simple test program. It works. But I would like to know improve it. I plan on writing more complex test programs and that won't be the time to iron out smaller issues. Thanks in advance.
<?php
$length = array_key_exists('length', $_POST) ? $_POST['length'] : null;
$width = array_key_exists('width', $_POST) ? $_POST['width'] : null;
if ($length == "") $length = 0;
if ($width == "") $width = 0;
?>
<?php
class Shape {
var $length;
var $width;
function setLength($Length) {
$this -> length = $Length;
}
function setWidth($Width) {
$this -> width = $Width;
}
function getPerimeter() {
return 2 * ($this -> length + $this -> width);
}
function getArea() {
return $this -> length * $this -> width;
}
}
$rectangle0 = new Shape;
$rectangle0 -> setLength("$length");
$rectangle0 -> setWidth("$width");
?>
<p> </p>
<p> </p>
<form method=post name="form1" action="practice1.php">
<div class="row">
<label for="winnings">Enter length: </label>
<input style="font-size:12pt" type="text" id="length" name="length" value="<?php if (isset($_POST['length'])) {echo $_POST['length'];} ?>" size="15"/>
<br style="clear:left"/>
<label for="losses">Enter width: </label>
<input style="font-size:12pt" type="text" id="width" name="width" value="<?php if (isset($_POST['width'])) {echo $_POST['width'];} ?>" size="15"/>
<br style="clear:left"/>
</div>
<p> </p>
<p> </p>
<input style="font-size:12pt" type=submit name=submit value="Compute" >
<input type=hidden name=submitted value="true" >
<p> </p>
<p> </p>
<div class="row">
<label for="tax" id="tax" style="font-size:13pt">The perimeter of the rectangle is:</label>
<input style="font-size:12pt" type=text id="perimeter" name="perimeter" value="<?php echo $rectangle0 -> getPerimeter() ?>" size=10 maxlength=10></td>
<br style="clear:left"/><br />
<label for="deficiency" id="deficiency" style="font-size:13pt">The area of the rectangle is:</label>
<input style="font-size:12pt" type=text id="area" …
Nathaniel10 34 Junior Poster
Hello All,
Thank you for responding to my question. I had to set it aside for a few weeks because oher things in life intervened. I am learning program part-time. This is not ideal becuase you really need to be immersed in it, but my current circumstances do not permit a heavy time committment.
I recently found a solution to my problem. My old computer had the php.ini file set to suppress error reporting. XAMMP has a default of setting for error reporting to include E_NOTICE. My code was wrong, or at least weaker than ideal, but PHP didn't report the weaknesses. I was using variables before verifying that they existed.
In XAMMP the weaknesses are being reported. As it is better practice to report errors, I needed to improve my code. I found two receommendations; one using isset() and the other using array_key_exists(). I chose the array method. So my prior code of:
$phpvariable = $_POST['htmlformvariable'];
is now:
$phpvariable = array_key_exists('htmlformvariable', $_POST) ? $_POST['htmlformvariable'] : NULL;
And I have no more notices.
I also discovered there is a lot of misinformation and misunderstanding in the cyberspace regarding PHP best practices. One must be very persistent and diligent in order to find what one needs.
Nathaniel10 34 Junior Poster
Hello All,
My old computer crashed. I installed XAMMP on my new computer. My old PHP files don't run. I learned that the reason is that register_globals feature has been deprecated and is now permanently Off by default. My old files were written in a 'register_globals=On' environment. I understand that one results is that the superglobals, such as $_POST[], no longer carry HTML form variables into the PHP area. I need to update the code of my old files to accomodate this change.
I reviewed prior threads related to the 'Undefined Index error' that is given when trying to use $_POST[] in PHP 5.3 and higher. But found only two over the past 5 or 6 weeks. One did not generate any replies, and the other generated only one reply that was incorrect.
In Internet searches, I have seen suggestions of using FILTER_INPUT() with functions called INPUT_GET or INPUT_POST. I have not been able to grasp how to use them to carry HTML form data to PHP variable for some type of processing.
How can I process form data without using the old superglobals? How can I update my old files with a minimum of re-writing?
Thanks in Advance.
Nathaniel
Nathaniel10 34 Junior Poster
Hi pikpik,
Thanks for your reply. I needed something far simpler than what you suggested. I found that you are correct in using a global variable. I was able to achieve what I wanted with the following code.
alreadyAdded = 1;
function addRow() {
if (alreadyAdded == 1) {
Dynamic HTML code ...
alreadyAdded++;
}
}
After the original input is changed, the count variable is increased, and the function does not execute again until the page is reloaded. I don't think this is an elegant solution - the use of global variables is supposed to be avoided - but it works and it is simple.
Nathaniel10 34 Junior Poster
I have a form with several inputs. One has a sub-input based on the condition of the original input. An example is:
<input onChange="javascript:addRow()"/>
The JS function works.
function addRow() {
Dynamic HTML code ...
}
However, if the original input is modified a second time, the JS function executes again and adds the dynamic code a second time. I don't want that. If the user needs to change the original input a second time I want to the function to fail to execute on that second or subsequent time.
Does anyone have experience with how to ensure that a JS function is executed only once per page load?
The straightforward methods of using a boolean are not working for me.
function addRow() {
if (alreadyAdded == 'true') {
Dynamic HTML code ...
}}
Thanks in advance.
Nathaniel10 34 Junior Poster
@cereal, you are correct.
It seems that in nesting the functions, I commented out a needed line. That caused the error in the result. With the that line restored, the nested min/max functions work fine.
Sorry for the false alarm.
Corollary: Do not code when you are tired.
Nathaniel10 34 Junior Poster
I have a problem that includes finding the maximums and minimums of certain variables in sequence. I want to nest the max() and min() functions as follows.
$variable5 = min(max(($variable1 - $variable0), 0), $variable3);
The PHP manual says/suggests that this type of nesting is possible. However, the code doesn't run correctly. It only runs correctly when I split up the nesting as follows.
$variable2 = max(($variable1 - $variable0), 0);
$variable5 = min(variable2, $variable3);
I have not been able to find any other examples of what I want to do. Does anyone have experience with this? Can you offer any suggestions? It is a rather long program so I would prefer to write code that is as succinct and concise as possible. (ie. 1 line of compact code rather than 2 lines of code with an extra variable.)
Thanks in advance.
Nathaniel10 34 Junior Poster
OK. I figured out the other half off my layout problem. The error was in lines 22 and 26 of the code I posted above. Silly me forgot that the setAttribute function acts like inline styling, and that inline styling supercedes the style sheet styling. My CSS wasn't working because my JS code was overiding it. I deleted the setAttributes on lines 22 and 26. The program then worked as I wanted.
I am marking this thread as solved.
Nathaniel10 34 Junior Poster
Well, it didn't take long to figure out half of the layout problem! It wasn't the JS program, it was the HTML. The JS layout is set to align center. The HTML is also set to align center but wasn't doing that. The HTML was aligning left. When I set the JS to align left, the layout matched perfectly.
So, I need to review the CSS and other formatting to see why my table is not aligning center. Another issue might be that the layout changes from center to left after the JS is executed. There is a movement of the input areas of the form.
Still, thanks to everyone for your input.
Nathaniel10 34 Junior Poster
Thanks, Taywin.
After some additional experimenting, I solved my second problem. My first tests were in a small .html program. When I put the results of those tests into the draft full .php program, the php code for prepopulating the form becomes invisible.
Now, the desired new HTML code is added where and when I want it - only the layout/alignment remains to be solved.
In the full .php program, I am using CSS and div tags to layout the pages. I use table formatting only within the form that the user is to fill out and submit. I agree with you, Taywin, that I need to make the code added by the JS program responsive to the layout design embodied by my style sheet. I am not sure how to do that and will experiment some more.
Radha, I deleted the body and table variables from the JS function and it still works. However, when I remove the table body (tbody) variable it stops working.
Nathaniel10 34 Junior Poster
Hi Radha,
Thanks for your prompt reply. I read Viral's examples and found them pretty helpful. Unfortunately, he uses 'innerHTML' in his code. As we know, that is proprietary to MS, so it only works in IE. I need for my code to work in Firefox, Chrome, and others, so I can't use 'innerHTML'.
While any help is very much appreciated, useful suggestions need to be 100% W3C standards compliant.
Nathaniel10 34 Junior Poster
I have a script in which I would like new code to appear based on the response to a question. I am using 'onChange' to trigger the event.
The difficulties I am having are that:
1) The format of the form changes after the event. I would like the new question to be identical the other questions in the form. The text is not center aligned and the input box is smaller and not aligned.
2) I am using PHP to process the form and I prepopulate the fields if the form has already been submitted. The code for population is visible text when it shouldn't be.
Here is the code for a test program.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Dom Test</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="generator" content="HAPedit 3.1">
</head>
<script language="javascript" type="text/javascript">
function addRow() {
var bdy = document.getElementsByTagName("body")[0];
var tbl = document.getElementsByTagName("table")[0];
var tblbdy = document.getElementsByTagName("tbody")[0];
var tblrow = document.getElementsByTagName("tr")[3];
row = document.createElement("tr"); row.setAttribute("height", "50");
cell1 = document.createElement("td"); cell1.setAttribute("width", "350"); cell1.setAttribute("align", "center");
text1 = document.createTextNode("Estimated Exempt Interest Income: ");
cell1.appendChild(text1);
cell2 = document.createElement("td"); cell2.setAttribute("width", "350"); cell2.setAttribute("align", "center");
cell3 = document.createElement("input");
cell3.setAttribute("style", "font-size:12pt");
cell3.setAttribute("size", "15");
cell3.setAttribute("type", "text");
cell3.setAttribute("name", "exempt");
cell3.setAttribute("value", "<?php if (isset($_POST['exempt'])) {echo $_POST['exempt'];} ?>");
cell2.appendChild(cell3);
row.appendChild(cell1);
row.appendChild(cell2);
tblbdy.appendChild(row);
tbl.appendChild(tblbdy);
bdy.appendChild(tbl);
tbl.setAttribute("align", "center");
}
</script>
<body>
<p> </p>
<form method=post name="taxform1" >
<table width=600 align="center">
<tr colspan="2"><td>
<p><span style="font-family:times new roman; font-size:18pt; color:black; text-align:center">Income Tax Calculator for Complex Returns</span></p>
</td></tr>
<tr><td><p> </p></td></tr>
<tr>
<td>Estimated Social Security Income: …
Nathaniel10 34 Junior Poster
I was able to get started on the doubly linked list. I completed the function to add a node at the top of the list and to display it from the bottom upward. The code so far is below.
#include "../../std_lib_facilities.h"
class Student {
public:
string name;
double gpa;
Student *next;
Student *prev;
/*
Student(const string& aName, double aGPA, Student* aNext = NULL) : {
name(aName), gpa(aGPA), next(aNext) //use this, it's called an 'initialization list'.
}
static Student* Create(const string& aName, double aGPA, Student* aNext) {
Student* result = new Student;
result->name = aName;
result->gpa = aGPA;
result->next = aNext;
return result;
};
*/
};
class SList {
private:
Student *head;
Student *tail;
public:
SList() {
head = NULL;
tail = NULL;
};
Student* AddFirst(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = NULL;
newStudent->prev = NULL;
if (head == NULL) {
head = tail = newStudent;
} else {
newStudent->next = head;
head->prev = newStudent;
head = newStudent;
}
return newStudent;
};
...
void Display() const {
int c = 0;
Student *Display_ptr = tail;
while (Display_ptr) {
cout << Display_ptr->name << " " << Display_ptr->gpa << endl;
c++;
Display_ptr = Display_ptr->prev;
}
if (c == 0) {cout << "\nThere are no students on the list to display." << endl;}
};
The above code compiles and runs correctly, displying students in the correct reverse order. It was more challenging than I expected, mostly because I don't really see …
Nathaniel10 34 Junior Poster
Thank you very much for your advice and help with this thread, Mike. For the past week I have not been able to code much. Things got busy with my job and life in general. I am teaching myself C++ part-time.
I have Stroustrup's book "Programming Principles and Practice Using C++". Its Chapter 5 deals with the error handling issues you raised. Your example is very staightforward. I found Stroustrup's examples of "try, catch, throw" to be fairly complicated and involved creating new classes for each type of error to be caught and exception to be thrown.
In hindsight, your suggestion to have a class for the students is obvious. A class for the nodes, a class for the data contained in the nodes, and a class for the list makes all the sense in the world. But there are not many (free) examples of linked lists that show your approach. I am appreciating more and more why IT managers complain of the lack of good programmers.
I tried to correct a memory error (unhandled exception) in the Delete function. I eventually found that the following code except for the line before delete Find_ptr
. When I comment it out, the list member gets deleted as desired. Otherwise, I get a memory error. My experiments suggested that the original code was trying to delete the node after the desired one as well, so I moved the delete command outside of the for loop. I am not sure it is correct but …
Nathaniel10 34 Junior Poster
Raptr,
Thank you very much for the flattering words. I cannot take much credit though because it was Mike_2000_17 who explained it so very clearly that I could really understand what was going on in a linked list.
You are right about return type for the delete function. I did not realize that the construction of Student* [function name()]
implied that a return value was expected. Changing it to void [function name()]
did eliminate the need for a return statement.
You are also right about line 75 above. I tried to delete the first node of the list and got a memory error. I had not tested the program thoroughly before posting it. When Previous_ptr is NULL it means that we are dealing with the first node in the list. When we delete that node, we want the head node or root node to point to the address of the, formerly, second node in the list. So the right hand side of that equation should be Find_ptr->next
. I am having trouble with the left hand side. I think the LHS should be the variable head
but that still gives me a memory error. I can't see how to set the root pointer equal to the address of the new first node in the list. I tried Find_ptr->head
but I get a compile error that head
is not a member of the class Student
.
Nathaniel10 34 Junior Poster
I re-wrote the delete function using a different example. That function now compiles and runs correctly. My almost final code for this singly linked list is as follows. Constructive comments are eagerly welcomed.
#include "../../std_lib_facilities.h"
class Student {
public:
string name;
double gpa;
Student *next;
};
class SList {
private:
Student *head;
public:
SList() {
head = NULL;
};
Student* AddFirst(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = head;
head = newStudent;
return newStudent;
};
Student* AddLast(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = NULL;
if (!head) {
head = newStudent;
} else {
Student *Student_ptr = head;
while (Student_ptr->next) {
Student_ptr = Student_ptr->next;
}
Student_ptr->next = newStudent;
}
return newStudent;
};
Student* AddAfter(const string& aName, double aGPA, int k) {
Student* newStudent = new Student;
Student* Student_ptr = head;
for (int i = 0; i < k; i++) {
Student_ptr = Student_ptr->next;
if (Student_ptr == NULL) {
cout << "\nThere are less than " << k << " students in the list." << endl;
}
}
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = Student_ptr->next;
Student_ptr->next = newStudent;
return newStudent;
};
Student* Delete(const string& aName) {
Student* Previous_ptr = NULL;
Student* Find_ptr = head;
for (Find_ptr = head; Find_ptr != NULL; Previous_ptr = Find_ptr, Find_ptr = Find_ptr->next) {
if (Find_ptr->name == aName) {
if (Previous_ptr == NULL) {
Find_ptr = Find_ptr->next;
} else {
Previous_ptr->next = Find_ptr->next; …
Nathaniel10 34 Junior Poster
Well. I have tried to add a delete function to remove a node from my linked list. It is not working. I recognize that the parts of the function are: 1) input the student name to be deleted, 2) traverse the list searching for the name, 3) if the name is found, then delete the node and change the pointer value of the prior node, 4) if the name is not found, then give a message to the effect. I haven't been able to successfully do that. My code is below. It complies and runs but outputs that the student name is not found when it should be found and deleted. Please show me what the delete function should look like. (In the main function, I have used several if statements rather than a switch statement. There was an error in my switch statement that I did not want to search for right now. My focus is on the delete function.)
#include "../../std_lib_facilities.h"
class Student {
public:
string name;
double gpa;
Student *next;
};
class SList {
private:
Student *head;
public:
SList() {
head = NULL;
};
Student* AddFirst(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = head;
head = newStudent;
return newStudent;
};
Student* AddLast(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = NULL;
if (!head) {
head = newStudent;
} else {
Student *Student_ptr = head;
while (Student_ptr->next) …
Nathaniel10 34 Junior Poster
Mike,
Thank you very much for the explanation of the format of the for loop statement. I had never learned about the two semi-colon rule.
I have not had time to update the program with your corrections. I am trying to include a function to delete a specific node. I will try to have something by tomorrow.
Nathaniel10 34 Junior Poster
I have added to the program. Below is the latest code. However, I need some more help
with it.
#include "../../std_lib_facilities.h"
class Student {
public:
string name;
double gpa;
Student *next;
};
class SList {
private:
Student *head;
public:
SList() {
head = NULL;
};
Student* AddFirst(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = head;
head = newStudent;
return newStudent;
};
Student* AddLast(const string& aName, double aGPA) {
Student* newStudent = new Student;
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = NULL;
if (!head) {
head = newStudent;
} else {
Student *Student_ptr = head;
while (Student_ptr->next) {
Student_ptr = Student_ptr->next;
}
Student_ptr->next = newStudent;
}
return newStudent;
};
Student* AddAfter(const string& aName, double aGPA, int k) {
Student* newStudent = new Student;
Student* Student_ptr;
for (int i = 0; Student_ptr = head; i < k; i++) {
Student_ptr = Student_ptr->next;
if (Student_ptr == NULL) {
cout << "\nThere are less than " << k << " students in the list." << endl;
return;
}
}
newStudent->name = aName;
newStudent->gpa = aGPA;
newStudent->next = Student_ptr->next;
Student_ptr->next = new Student;
return newStudent;
};
void Display() const {
Student *Display_ptr = head;
while (Display_ptr) {
cout << Display_ptr->name << " " << Display_ptr->gpa << endl;
Display_ptr = Display_ptr->next;
}
};
void Count() const {
int c = 0;
Student *Count_ptr = head;
while (Count_ptr) {
c++;
Count_ptr = Count_ptr->next;
}
cout << "\nThere are " << c << " students …
Nathaniel10 34 Junior Poster
Mike,
Thank you VERY, VERY, VERY MUCH!!!!!! Not only for the 2 errors in my program, but especially for your re-write of my program! You did something that completely blew my mind! You created TWO classes!!! You have one class for the nodes, that has objects for the data values and the pointer value to the next node. Then you have a class for the list itself, that has objects and functions for traversing the list, adding nodes, deleting nodes, and displaying nodes.
In hindsight, that is completely logical. But that was not occurring to me, not would it have occurred to me for a long time. Only a handful of examples I read did that and I did not understand them at the time. Your post was a quantum leap for my understanding of linked lists. That type of post reveals that you are a serious doctoral candidate in a field that heavily uses computer programming!
Nathaniel10 34 Junior Poster
I worked with another program. Its code is below.
#include "../../std_lib_facilities.h"
class Student {
public:
string name;
double gpa;
Student *next;
};
int main()
{
Student *head;
Student *newStudent;
Student *Student_ptr;
Student *Display_ptr;
head = NULL;
string S_name;
double S_gpa;
for (int i = 0 ; i < 3; i++) {
cout << "Enter Student's name." << endl;
cin >> S_name;
cout << "Enter Student's grade point average." << endl;
cin >> S_gpa;
newStudent = new Student;
newStudent->name = S_name;
newStudent->gpa = S_gpa;
newStudent->next = NULL;
if (!head) {
head = newStudent;
} else {
Student_ptr = head;
while (Student_ptr->next) {
Student_ptr = Student_ptr->next;
Student_ptr->next = newStudent;
}
}
}
Display_ptr = head;
while (Display_ptr->next) {
cout << Display_ptr->name << " " << Display_ptr->gpa << endl;
Display_ptr = Display_ptr->next;
}
keep_window_open();
return 0;
}
So. I fully understand that the data values for each node are the student's name and gpa. The address of the next node is held in the "next" variable. I understand that "head" is the pointer value to the first data node. The variable "newStudent" creates a new node. The variable "Student_ptr" traverses the list and points to the curent node at which a new student will be added to the list. The variable "Display_ptr" traverses the list and points to the current node whose data values will be printed.
This program compiles but does not run correctly. It correctly adds 3 students to the list but it does not display any. I tried to …
Nathaniel10 34 Junior Poster
I have searched for and read through over 50 examples of linked lists. I can barely make heads or tails out of them. Some are in C, some are in Java, some use templates, most only discuss theory and display flowcharts but have few explained examples. I need serious help!
Below is the one example that I can half way understand well enough to even start asking questions about linked lists.
#include "../../std_lib_facilities.h"
struct Node {
int num;
Node *link;
} *p;
int main()
{
Node *root;
root = new Node;
root->num = 5;
root->link = p;
p = root;
Node *q;
for (q = p; q != NULL; q = q->link) {
cout << q->num << endl;
}
keep_window_open();
return 0;
}
Why is "struct" being used instead of "class" to introduce the linked list nodes? Is it a preference for not having to declare the lines public if "class" is used?
I understand that "num" is the data value held in the node and that "link" is the pointer to the next node. What is "p"? The author explained that "link" points to "p" and that "p" points to the next node. I don't follow that logic. What is the need to create a pointer that is outside the list node?
I understand the creation of the pointer "root" and setting its value equal to a new list node. I understand the setting of the data value for the new node to 5. I understand that the …
Nathaniel10 34 Junior Poster
Thanks for your comments, Mike.
I took a look at ring buffers but that topic is too advanced for me right now. I will get back to it.
I am frustrated with the indentation thing. I continually find that the copy/paste procedure to post my code changes the indentation. I can't correct it all the time.
I am working on a linked list problem right now. I will incorporate classes into it so I can avoid using global variables.
I am learning from Stroustrup's book, (PPP C++), and he provides the header I am using from his website. I appreciate your point. I plan to concentrate on headers when I start working on multi-source file projects.
Nathaniel10 34 Junior Poster
start() is declared/defined with return type int, but the return value in main() is ignored.
You are right! I had initially made start() void and then changed it to return a value in a prior iteration of the program. I forgot to change it back to void after I made further modifications.
Thanks for pointing that out. I need to keep better track of the changes I make to a program as it evolves to its final version.
Nathaniel10 34 Junior Poster
I am teaching myself C++ and wrote a program that does the queue data structure. It runs corectly. I would like some feedback on how I can improve the program to make it run faster, use fewer lines of code, or be clearer to someone else. I haven't added my comments to the program so that is one area. For now, I want to concentrate on improving efficiency. Thanks in advance.
#include "../../std_lib_facilities.h"
int top;
int act;
string s;
string names [6] = {"James", "John", "Jerrold", "Jennifer", "", ""};
int start() {
cout << "Enter the desired activity.\n" << "1 for listing the queue items.\n" << "2 for adding an item to the queue.\n" << "3 for removing an item from the queue.\n" << "4 to exit the program.\n" << endl;
cin >> act;
while (act != 1 && act != 2 && act!= 3 && act != 4) {
cout << "Please enter a choice 1 through 4.\n" << endl;
cin >> act;
}
return act;
}
void list_items() {
for (int i = 0; i < 6; i++) {
cout << i + 1 <<", " << names[i] << endl;
}
start();
}
void add_item() {
if (names [5] != "") {cout << "The queue is full.\n" << endl;}
else {
cout << "Enter the name to add to the queue.\n" << endl;
cin >> s;
int i = 0, top = 0;
while (names [i] != "") {
top = i + 1;
i++;
}
names [top] …
Nathaniel10 34 Junior Poster
Lerner, your suggestion worked after some trial and error. Here is my updated code. It does everything it is supposed to do. Unfortunately, it also does some things it is NOT supposed to do. Still, I consider the program a success and I am on to queues. Will probably post about that soon.
#include "../../std_lib_facilities.h"
int top;
int act;
string s;
string names [6] = {"James", "John", "Jerrold", "Jennifer", "", ""};
void start() {
cout << "Enter the desired activity.n" << "1 for listing the stack items.n" << "2 for adding an item to the stack.n" << "3 for removing an item from the stack.n" << "4 to exit the program.n" << endl;
cin >> act;
while (act != 1 && act != 2 && act!= 3 && act != 4) {
cout << "Please enter a choice 1 through 4.n" << endl;
cin >> act;
}
}
void list_items() {
for (int i = 0; i < 6; i++) {
cout << i + 1 <<", " << names[i] << endl;
}
start();
}
void add_item() {
if (names [5] != "") {cout << "The stack is full.n" << endl;}
else {
cout << "Enter the name to add to the stack.n" << endl;
cin >> s;
int i = 0;
while (names [i] != "") {
top = i;
i++;
}
names [top + 1] = s;
cout << "The name " << s << " has been successfully added to the stack.n" << endl;
}
start();
} …
Nathaniel10 34 Junior Poster
I have partly solved problem 2. The output window was closing immediately because the command to keep the window open, keep_window_open()
, was not being applied. When I added it to each function, they worked correctly. However, I would like the program to prompt for further activities, list the stack again, add another item or remove another item. I need to call the start()
function again after each the activity functions have completed their tasks. I am having difficulty doing that.
Nathaniel10 34 Junior Poster
I am teaching myself C++ and amd now trying to simple programs related to data structures. I wrote this code for a simple stack. It is not working. I am frustrated and tired so I cannot think through the issue.
There are two main problems with which I need help.
1.
While my code compiles and runs, there are two warnings:
Loaded 'C:\WINDOWS\system32\ntdll.dll', Cannot find or open the PDB file
Loaded 'C:\WINDOWS\system32\kernel32.dll', Cannot find or open the PDB file
I don't know what those warnings mean. I am using MS VC++ 2010 Express.
2.
The code does not run correctly. Option 1, (list the stack), causes the program to immediately stop and the output window to close. Option 3, (remove an item), does the same thing. Option 2, (add an item), correctly asks for a name to add but closes the output window after the name is input. Only option 4, exit the program, works correctly.
Here is my code. Thanks in advance.
#include "../../std_lib_facilities.h"
int top;
int act;
string s;
string names [6] = {"James", "John", "Jerrold", "Jennifer", "", ""};
void list_items() {
for (int i = 0; i < 6; i++) {
cout << i + 1 <<", " << names[i] << endl;
}
}
void add_item() {
if (names [5] != "") {cout << "The stack is full.\n" << endl;}
else {
cout << "Enter the name to add to the stack.\n" << endl;
cin >> s;
int i = 0;
while (names …
Nathaniel10 34 Junior Poster
You now have understood the situation. You still misunderstand the question.
No, the question is not how many songs must be played to guarantee that there will be a repeat. The answer to that is obviously 1000. That is not the question. The question is how many songs need to be played, on average, such that the played songs contain a repeat. The answer is 38.
This question requires a very basic understanding of probability and is an excellent programming question, as a simple loop lends itself very well to answering this question.
Not according to the probability textbooks I read that give a more than very basic understanding of probability.
On the first draw of a song, the probability of repeating P(repeat) is 0.
On the second draw of a song, the probability of repeating given no prior repeat, P(repeat|no prior repeat), is 1/1000.
On the third draw of a song, the probability of repeating given no prior repeat, P(repeat|no prior repeat), is 2/1000.
On the fourth draw of a song, the probability of repeating given no prior repeat, P(repeat|no prior repeat), is 3/1000.
And so on.
These are conditional probabilities and are computed using the formula: P(A|B) = P(A and B) / P(B). A precise solution requires re-expressing the above conditional probabilities using that formula in order to get the unconditional probability of P(repeat). I don't want to get into that level of detail.
A less precise solution uses the logic …
Nathaniel10 34 Junior Poster
This is an incorrect assessment of the problem. You have assessed the problem in which a specific song is repeated. This is the same as PJH's suggestion above of picked song 9 to be the repeated song. The question does not concern a specific song to be repeated. The question is about repeating any song.
Are you saying that the 2 groups are 1) played songs and 2) unplayed songs, so that after 2 different songs are selected the probabilities for the third selection is 2/1000 for group 1 and 998/1000 for group 2? And for the fourth song selection, given no repeat for the third selection, the probabilities are 3/1000 for group 1 and 997/1000 for group 2? Et cetera?
If so, then I did misunderstand the problem. It changes the complexity of the probability expression, but doesn't change the fundamental analysis. It is no longer a binomial probability problem. It is a combinations problem. With each selection, for there to be no repeat of a song, there must be 0 selections from the number of songs in group 1 (there is only 1 way to do that) and 1 selection from the remaining unplayed songs in group 2 (there are as many ways to do that as there are remaining unplayed songs). That is a joint probability. That joint probability expression needs to be iterated over the number of selections. The number of iterations it takes for the joint probability of continuing to select only unplayed songs …
Nathaniel10 34 Junior Poster
I'm late on this but here is my $0.02 anyway. Moschops is right that this is the same as the Birthday Problem.
However, this is NOT a C++ problem, or even a computer programming problem. It is a probability problem. The probability solution involves dividing the 1000 songs into 2 groups. In the first group is the song to be repeated, and the second group has all the other songs. Every time the song player selects a song it can either choose from the first group with probability 1/1000 or the second group with probability 999/1000. The specific problem seems to be to find the number of songs the player selects before it chooses from the first group twice.
This defines the binomial probability. The exact solution to this type of problem is Prob(first group selections equal to 2) = [n!/2!(n-2)!] times (1/1000) raised to power 2 times (999/1000) raised to power (n-2). Find the n that makes the left hand side equal to 1.0.
I think the prof should have assigned how to program the solution rather than find the solution.