Featured

Minesweeper in Java

by 12:45 PM
Minesweeper is a video game where you are trying to clear a "board" while avoiding the hidden traps. There are individual squares which serve as these traps; all of the other squares are defined by the number of traps adjacent to that square. This means that a non-trap square can have a maximum value of eight (although this is highly unlikely). (Source). Here is an example of minesweeper wit a 2D GUI (Graphical User Interface): http://minesweeperonline.com/

This implementation utilizes 2D arrays but does not include a graphical user interface. For this java code, the "9" represents a trap or bomb while -1 represents a spot on the board which isn't visible. Therefore the original board looks like this:


This version also does not include any method to "flow" and reveal all zeroes adjacent to one another. Therefore, you need to reveal each square one at a time.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class MinesweeperGame {
    private int rows;
    private int columns;
    private int mines;
    private int board[][];
    private int visibleBoard[][];

    public MinesweeperGame(int inputRows, int inputColumns, int inputMines) { // Service Constructor
        rows = inputRows;
        columns = inputColumns;
        mines = inputMines;
        visibleBoard = new int[rows][columns];
        board = this.createBoard();
        board = populateBoard(board);
        visibleBoard();
    }

    public int playerInteract(int inputRow, int inputColumn) { // Determines the result of an interaction with the board and changes all components appropriately
        if (board[inputRow][inputColumn] == 9) {
            return 2;
        }
        else {
            visibleBoard[inputRow][inputColumn] = board[inputRow][inputColumn];
        }
        for (int i = 0; i< rows; i++) { // Checks for a win, if they haven't won yet, then they need to keep playing
            for (int j = 0; j < columns; j++) {
                if (board[i][j] != 9) {
                    if (visibleBoard[i][j] == board[i][j]) {
                        visibleBoard[i][j] = visibleBoard[i][j];
                    }
                    else {
                        return 0;
                    }
                }
            }
        }
        return 1;
    }

    public void getVisibleBoard() {
        printBoard(visibleBoard);
    } // Calls the "visible" board, i.e. what the player can see
    public void getBoard() {
        printBoard(board);
    } // Calls the master board with all of the answers

    private int[][] createBoard(){ // Helper Method to instantiate the board
        int temp[][] = new int[rows][columns];
        return temp;
    }

    private int[][] populateBoard(int inputBoard[][]) { // Helper Method to randomly place mines
        while (mines != 0) {
            int a = (int)(Math.random()*rows);
            int b = (int)(Math.random()*columns);
            if (inputBoard[a][b] == 0) {
                inputBoard[a][b] = 9;
                mines -= 1;
            }
        }

        for(int i = 0; i < rows; i++) { // This section then assigns each space of number based on the surrounding mines.
            for (int j = 0; j < columns; j++) {
                if (inputBoard[i][j] != 9) {
                    int tempMines = 0;
                    if ((j - 1) != -1) {
                        if (inputBoard[i][j - 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i - 1) != -1) {
                        if (inputBoard[i - 1][j] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i - 1) != -1 && (j - 1) != -1) {
                        if (inputBoard[i - 1][j - 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i - 1) != -1 && (j + 1) != columns) {
                        if (inputBoard[i - 1][j + 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i + 1) != rows) {
                        if (inputBoard[i + 1][j] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((j + 1) != columns) {
                        if (inputBoard[i][j + 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i + 1) != rows && (j + 1) != columns) {
                        if (inputBoard[i + 1][j + 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    if ((i + 1) != rows && (j - 1) != -1) {
                        if (inputBoard[i + 1][j - 1] == 9) {
                            tempMines += 1;
                        }
                    }
                    inputBoard[i][j] = tempMines;
                }
            }
        }
        return (inputBoard);
    }

    private void printBoard(int inputBoard[][]) { // Prints the board in a neat matrix fashion
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(inputBoard[i][j] + "   ");
            }
            System.out.println();
        }
    }

    private void visibleBoard() { // Generates a blank "visible board"
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                visibleBoard[i][j] = -1;
            }
        }
        printBoard(visibleBoard);
    }

}

Here is the driver class for the above game. This version is very customizable; the user selects the # of traps and the dimensions of the board. Furthermore, this edition does not have an option to replay the game; it automatically shuts down after a win or loss.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;

public class MinesweeperPlayer {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter three positive constants (the # of rows | the # of columns | the # of mines): ");
        int rows = sc.nextInt();
        int columns = sc.nextInt();
        int mines = sc.nextInt();
        System.out.println("Please note that mines are represented by the # 9 while -1 refers to 'hidden' spaces");
        System.out.println("");
        MinesweeperGame game = new MinesweeperGame(rows, columns, mines); // Creates the game
        System.out.println("");
        System.out.println("Let's get started!");
        int x = 0;
        while (x != -1) { // Actually plays the game
            System.out.println("");
            System.out.println("Please select a row | column to examine (zero-based indexing please): ");
            int inputRow = sc.nextInt();
            int inputColumn = sc.nextInt();
            int y = game.playerInteract(inputRow, inputColumn); // User input to select square
            if (y == 2) { // Response System: Win, Hit or Miss
                System.out.println("");
                System.out.println("You have hit a mine!");
                System.out.println("");
                game.getBoard();
                System.exit(0); // Exits after the game is complete
            }
            if (y == 1) {
                System.out.println("");
                System.out.println("You won! Congratulations");
                System.out.println("");
                game.getBoard();
                System.exit(0); // Exits after the game is complete
            }
            if (y == 0) {
                System.out.println("");
                System.out.println("Here is the board for reference. Play you next move wisely.");
                System.out.println("");
                game.getVisibleBoard(); // Continues if the game has not been completed. 
            }
        }
    }
}

Thank you to http://hilite.me/ for the source code formatting.

What is Wilkins Bill?

by 6:47 PM
Wilkins Bill, also known as the Force Bill of 1833, was passed in response to the 1832-1833 nullification crisis between the federal government and the state of South Carolina. This was a severe crisis with vice-president John C. Calhoun having resigned June 1832 in protest. The different sides were preparing for full-scale battle as this letter from Joel Roberts Poinsett on Feb. 22nd, 1833, a former U.S. Rep and former U.S. Ambassador to Mexico, states:

"I do not think therefore I over estimate the force of the Union party in the city at One thousand men. I should be much disappointed not to find this number, at least, at their rendevous in case of an alarm. The Nullifiers estimate their force in the City at 1600 men. We consider our strength equal to theirs here. In the State they report 16,000 Volunteers." - Source

He conviction later won him appointment to the position of U.S. Secretary of War under president Martin van Buren.

"It is rumoured, that if they do secede, which I verily believe they will do if the enforcem't law passes and the tariff is not modified ... I have addressed a circular to the Union members of the state convention urging them not to join that body in any act violating the constitution of the united states and not to go to the convention at all. This storm may yet pass off and not burst upon us, but we will be prepared to encounter and to resist it like men." - Source

South Carolina had earlier on passed the Ordinance of Nullification enumerating the reasons for secession (read here).

President Andrew Jackson wrote in inaugural address on March 1st, 1833:

"For myself, when I approach the sacred volume and take a solemn Oath to support and defend this constitution, I feel in the depths of my soul, that it is the highest, most sacred and most irreversible part of my obligation, to preserve the union of these states, although it may cost me my life." - Source

The day afterwards on March 2nd, 1833, Wilkins Bill was passed, named after William Wilkins, a Jacksonian ally representing Pennsylvania who proposed the bill in the senate.

William Wilkins, legislator, lawyer & judge. Source 

Later becoming Secretary of War as Poinsett, he generally supported Jacksonian principles during his varied career as a federal judge, U.S. Senator, U.S. Minister to Russia, U.S. Representative and Cabinet member. For example, during his tenure in Tyler's cabinet, he supported western expansionism.


His bill empowered the president to enforce the laws of the United States with regard to commerce and especially tariffs in the ports of South Carolina, whose leading politicians opposed the measures because they were designed to protect New England manufacturing interests (Source). There inspiration for this form of resistance came from the Virginia and Kentucky resolutions authored by certain founding fathers.

William Hendricks, a senator of Indiana, wrote at the time:

Commentary on the Tariff & Wilkins Bill. Source

"A crisis had indeed arisen, and it would have been, inconsistent with duty, to stand still, and see the revenue officers of the General Government delicacy, fall victims, to the military power of South Carolina, already organized for that purpose. That state must abandon her position, or there must be consequences the most unpleasant." - Source 


The passage of this bill essentially provided Jackson with the power to enforce the collection of the taxes regarding imports/exports, but Congress lowered the tariffs in a successful plot to avoid the implementation of the contents of this "Force" Bill.



The Lewis Dot Structure for NH3

by 4:04 PM
Created by MakeTheBrainHappy.
The Lewis Dot Structure for NH3 (Ammonia) is shown above. You could also represent the bonds as dots between the two atoms, but this may be confused with the lone pair electrons on the nitrogen. 
Each atom in the bond has a full valence shell, with nitrogen having access to eight electrons and each hydrogen having access to two (learn why hydrogen only needs two). The covalent bonds between the N and the H are similar to the ones formed between two Hs because the relatively small difference in electronegativity between carbon and hydrogen. 

Nitrogen requires a lone pair of electrons to complete the structure and provide five electrons as recommended by nitrogen's original elemental valence shell which contains the same number of electrons. It is difficult to ascertain the exact 3D structure, but it follows a general tetrahedron structure shown below. Due to electron-electron repulsion in the lone pair, the angles between the remaining hydrogens is slightly less than 109.5˚: 107.5˚. This places nitrogen into the category of "trigonal pyramidal" geometric configurations. 

Ammonia has a general tetrahedron structure in 3D space similar to methaneSource

Ammonia is related to ammonium (NH4+), whose lewis structure is shown here. Ammonia is generally a base. It is a type of nitrogenous waste especially prevalent in aquatic organisms. It is considered a hazard toward human health and can have the effects on the neural system as shown in the diagram below.

Source.
It is also one of the few compounds which can undergo hydrogen bonding due to its polar nature. Due to the strength of these hydrogen bonds, water has a relatively high melting and boiling point, although they are not as high as network covalent solids. Those are bonded by intramolecular forces which involve the actual sharing of electrons vs. partial dipole forces in hydrogen bonds. There are only three types of bonds which can hydrogen bond. These are N-H, O-H, and F-H bonds due to the large electronegativity differences between the molecules. In the H2O article, ammonia was briefly mentioned as a compound with these properties. These properties contribute to NO3s relatively high boiling point of -33.3˚C and high solubility in water. 

Sources:

Regression to the Mean

1:17 PM
Have you wondered why tall parents usually have smaller children, and vice versa? Galton discovered this and wondered why the children seemed so 'mediocre' than their parents. He then proceeded to coin this phenomenon 'regression towards mediocrity' [1].

Now named 'regression to the mean', this phenomenon is now considered an important factor to consider for valid research. When a variable that involves some randomness deviates significantly from a norm, regression to the mean states that it is likely a subsequent measurement will return a value that is closer to the expected norm.


Measurements 1 and 2 were taken from the same material and is represented by the red and blue lines, respectively.

This graph shows data for two measurements of a liquid and solid heterogeneous sample for its G'' values at different stresses. For each measurement, a minute amount of sample is taken from a container and placed into the measurement device. What is important is the massive fluctuations in the first measurement at low stresses is lessened and returns closer to its expected norm (represented by the gray dotted line) after the second measurement.

Why does this happen?

Heterogeneous mixtures can make taking a
 representative sample for testing more difficult.
Significant fluctuations from the norm can be caused by many factors such as human error, however regression to the mean is most applicable to non-systemic random errors. An example of such as error would be taking non-representative samples for testing (a sampling error). In order to get a certain measurement from a sample we need to collect a smaller representative sample from it to test. Random errors arise when taking such a sample, especially with heterogeneous mixtures. This is most likely the case for the example above; instead of taking a representative sample from this mixture in both measurements, it is likely that the sample taken from the container in measurement 1 was non-representative and contributed to unexpected deviations from the norm.




How it applies to research

Experimental research, where tests are conducted on two different experimental groups, allows researchers to accurately determine causal relationships between variables. If research was only done on one group of participants, regression to the mean would most likely produce favorable results for the researcher. Consider a clinical trial of a drug that is used to cure a disease. The researcher would gather a bunch of participants sick from such a disease, and allow the participants to take the drug. Regression to the mean would state that the most unhealthiest of the participants would likely get better as their health would get closer to the 'average human' - healthy. The researcher may then conclude that the drug is the cause of the participants getting better, but this is simply a case of regression to the mean. Testing on two representative groups - where one is given the drug in question and the other either a placebo or a competitor's drug, eliminates any biased conclusions that are based off regression to the mean.

As another example, research was done on if praise or punishment was better for pilots in terms of their quality of flight landings. When pilots made a landing which was better than average, they were praised. If they made a particularly bad landing, they were punished. Since regression of the mean states that in either case it is likely the pilot will subsequently return to a more 'average' landing quality, it was incorrectly concluded that punishment is more effective as a teaching tool than praise, since punished pilots whose previous bad landing was out of the norm improved on subsequent landings [2].


An example of the landing quality score of the pilots versus their landing number. Regression of the mean played a big part in the research performed to identify the effectiveness of praise vs. punishment for pilots as shown in this image.

Is regression to the mean applicable to everyday life?

Of course! Have you ever tried searching for a perfect online webpage to do some work (be it a good online grammar checker, plagiarism checker, useful SEO tool, etc.) and stumbled on a horribly made one out of the norm? If you're randomly trying to find another webpage, you're likely to click on a better webpage than the one before. This assumes that the indexing of the webpages involves some randomness which there is. It also assumes that the search engine isn't choosing to showing all horrible online webpages for you.

Interested in stock prices and finance? Mean reversion is based off of regression to the mean and states that sudden surges in stock prices will eventually die down and return back to the long-term average. This is based off the assumption that the short term price surge does not attract much attention media-wise and isn't announced prominently.

Even these examples don’t top how this phenomenon is the most applicable to life. 

We've all had bad days and sometimes we wonder whether or not having a bad day yields a succession of these days. When you're having a particularly bad day out of the norm, rest assured mathematically due to regression to the mean, your next day is likely to be better than before! :)

Have a nice day!



[1] Galton, F. (1886). Regression Towards Mediocrity in Hereditary Stature. The Journal of the Anthropological Institute of Great Britain and Ireland, 15, 246-263. doi:10.2307/2841583

[2] Morton, V., & Torgerson, D. J. (2003). Effect of regression to the mean on decision making in health care. BMJ (Clinical research ed.), 326(7398), 1083-4.


Images and image data belongs to KrIsMa.

L-Hospital's Rule for Indeterminate Forms

by 12:04 PM
L-Hospital's Rule should only be used when you have an indeterminate form. These are shown by the table below. The first two indeterminate forms are the most common varieties.

Source: https://math.stackexchange.com/questions/1581721/list-of-indeterminate-forms-in-mathematics
L-Hospital's Rule states that you take the derivative of the numerator and then the denominator and try to take the limit at the same value of that function. If this results in an indeterminate form, you will need to repeat the process. Here are two examples:



The second example uses L-Hospital's Rule four times because of the repeated appearance of indeterminate forms. 


Limits in Calculus

by 11:25 AM
Obj. 1: Limit Notation & Basic Definition


Limits are defined as follows: As an x-value approaches an argument, the two sides of the curve approach the same number. The example above shows the limit as the x-value approaches zero, the two sides of the curve approach zero. When taking the limit of a continuous function (such as x^2), the limit will be equal to the function value (y-value) of said function.

Obj. 2: Reviewing continuous functions. 
Correctly match up the letter number to the name of the function.

Options: Rational (1), Trigonometric (2), Logarithmic (3), Power (4), Polynomial (5), Exponential (6).

Answers can be found at the bottom of the article.

Polynomial, rational, power, exponential, logarithmic, and trigonometric functions are continuous over their respective domains. Therefore the limit of arguments in the domains will be equal to the function value.

Obj. 3: Limits and Discontinuity 

Limits can also be taken at points of discontinuity.

From left to right: y = x^2 (a continuous function), y = (x^3)/x which has a removable discontinuity at x=0 (not defined),
 y = (x^3)/x which has a jump discontinuity at x=0 (b/c this has been defined to be four arbitrarily),
 and y=1/(x^2) - discontinuity due to a vertical asymptote. 
The limit can still be taken because it looks at what value the function approaches as opposed to how the function is (or isn't) defined at that function. This concept will be revisited when we explore limits which do not exist. The main idea here is that continuity is not a requirement for the existence of a limit.

Obj. 4: Estimating Limits Graphically

Limits can be estimated graphically through human approximation (i.e. it looks to be one) or with a table where values are taken at different intervals reasonably close to the value of the limit. This is a very useful technique when the value is not defined at a certain function. The example below uses the graph of (x^3)/(x) and a table to find a limit at that argument.


Here is a practice problem. Given that there is a removable discontinuity (shown in purple) at x=.8, what is the limit as x approaches .8 of x^3 given the information in the table?


Obj. 5: Evaluating Limits Algebraically 

Source: https://www.youtube.com/watch?v=kjhng0sFBxs

The above limit laws can be used to simplify different problems or other limits when they cannot be solved through traditional direct substitution, simplification or rationalization. Substitution involves plugging in the number, simplification usually involves factoring, and rationalization involves multiplication by a conjugate. An example of the last technique is shown below.

Source: https://www.youtube.com/watch?v=rUvabvlCBo0 

Obj. 6: Formal Definition of Continuity 


A function is continuous at a specific point/argument if that argument is in the domain of the function, the limit exists and that point, and if these two values are equivalent to one another.

Example: Prove that x^2 is continuous at x=0.

Is it defined at x^2? Yes! y = 0^2 = 0


Is the limit defined at 0? Yes! Based on our previous knowledge modules, the limit of x^2 as the argument approaches zero is zero.


Are the two values equal? 0 = 0.


Obj. 7: One-Sided Limits

When taking the limit with a table, you examine the arguments from both sides of the limit to determine. You can also describe limits from just one-side of the limit. This provides two options: the left-hand limit (denoted by a - (dash) on the argument value) and the right-hand limit (denoted by a + (addition sign) on the argument value). See the example below using (x^3)/x.


Obj. 8: Nonexistent Limits


Limits do not technically exist if the limit is unbounded (i.e. goes to infinity), although these can still describe the behavior of a function. Limits also do not exist if the function oscillates around the argument or if the left and right hand limits are not equivalent. The following graphs illustrate these principles.

A.) The limit of 1/x at zero does not exist because the left and right hand limits aren't equivalent (right hand limit = + infinity), (left hand limit = - infinity).

B.) The limit of 1/x^2 at zero does not exist because it is unbounded but the statement is still correct when you are trying to describe the general behavior of the function.

C.) The limit of sin(1/x) at zero does not exist because the function begins to oscillate as you approach the value.

D.) The limit of |x|/x at zero does not exist because the left and right hand limits aren't equivalent (left hand limit = -1), (right hand limit = +1)

Obj. 9: Limits & Infinity

A limit can be described as heading towards infinity if both sides of the asymptote trend in that direction. The earlier example y= 1/x^2 showed a graph trending in the +infinity direction at x=0. Below is the graph of -1/x^2 which trends in the -infinity direction.


Limits can also be taken infinitely in order to solve for horizontal asymptotes. This harks back to previous content involving top-heavy (degree of numerator > degree of denominator), equal (degree of numerator = degree of denominator) and bottom-heavy (degree of numerator < degree of denominator) functions.

The rules still apply when the limit argument is taken to infinity (as is the case below). If the function is bottom heavy, the limit equals zero (i.e. the horizontal asymptote is x=0). If the function is top-heavy, the limit equals +infinity (i.e. the horizontal asymptote doesn't exist), and if the two degrees are equal you can solve for the value by divided both the numerator and denominator by the variable to the greatest degree. All terms less than this drop off when you take the limit to infinity. This process is exemplified by the example below.

Source: https://secure-media.collegeboard.org/digitalServices/pdf/ap/sample-questions-ap-calculus-ab-and-bc-exams.pdf

Based on this calculation, the graph of the function above should have a horizontal asymptote at y=3. Here is a representation of this and you can see that the graph does have a horizontal asymptote that it is trending to:


Obj. 10: Intermediate Value Theorem, Extreme Value Theorem, Mean Value Theorem 

Once more we will return to the topic of continuity because it an essentially condition for the three theorems mentioned above. Here are graphical explanations for these theorems.
Source: https://math.la.asu.edu/~arce/mat210_web/lessons/Ch3/3_4/3_4ol.htm
The Intermediate Value Theorem states if you have a continuous function, and define (a,f(a)) and (b,f(b)),
there must be at least one argument between a and b for all function values between f(a) and (b).
Source: https://brilliant.org/wiki/intermediate-value-theorem/
The mean value theorem is also conditional on having continuous function. After taking the slope between the points (a,f(a)) and (b,f(b)), you will know that there must be at least one point on the curve where the slope is equal to this "secant" slope.   Source: Robert Ortiz (https://commons.wikimedia.org/wiki/File:Mvt2.svg)
This discussion of slopes as mentioned in the definition of the Mean Value Theorem will begin to matter very much in the lesson on Derivatives

Answers:

First Practice (Matching Functions to Graphs): A - 5, B - 1, C - 4, D - 6, E - 3, F - 2 

Second Practice (Limit based on Table): The limit is approx. .511 or .512.

Credits:

Graphs were made with Desmos and the Symbolab Graphing Calculator. 

Deponent Forms of the Subjunctive in Latin

by 10:50 AM
Deponents are verbs existing in all four conjugations which are passive in form and active in meaning. These kinds of verbs only have three principal parts for the rules are slightly altered (as shown in the chart below).




The perfect system is very similar to the regular subjunctive formations. You use the 3rd principal part which is analogous to the 4th for both tenses. For the perfect tense you include the present active subjunctive form of the verb of being (sum, esse, fui, futurum). For the pluperfect tense you use the imperfect active form of the verb of being.


The present subjunctive is also formed in a similar. You start with the stem from the second principal part, use we fear a liar, and then add on the P.E. (passive present).


For the imperfect subjunctive you take the 2nd PP (passive infinitive) and recreate the active infinitive). Then you add on your passive P.E. (as you did with regular subjunctive mood imperfect tense verbs).

Powered by Blogger.