why my up function changes input out of its block in Java - java

i wrote a function to change an input matrix and return the changed matrix in java.
but when i want use input matrix after calling this function, i see that my input matrix has been changed.
My Up Function:
char[][] up(char[][] state, int[] empty){
int ie = empty[0];
int je = empty[1];
if(tools.checkMoves(state,1,ie,je)){
state[ie][je] = state[ie-1][je];
state[ie-1][je] = '0';
}else{
System.out.println("Move not allowed");
}
return state;
}
print matrix then call function and again print matrix
System.out.println(gameGenerator.printGame(nextState));
System.out.println(gameGenerator.printGame(moves.up(nextState,tools.getEmpty(nextState))));
System.out.println(gameGenerator.printGame(nextState));
Answer is:
1.print input matrix
-------------
| 1 | 2 | 3 |
| 5 | 7 | 6 |
| 4 | | 8 |
-------------
2.print matrix returned from function
-------------
| 1 | 2 | 3 |
| 5 | | 6 |
| 4 | 7 | 8 |
-------------
3.print input matrix after calling up function and it's CHANGED!
-------------
| 1 | 2 | 3 |
| 5 | | 6 |
| 4 | 7 | 8 |
-------------
please help ! Thanks all

You are modifying your input matrix in those two lines:
state[ie][je] = state[ie-1][je];
state[ie-1][je] = '0';
Java is an object-oriented language. When you pass an object to a method, you pass its reference. The reference is copied but not the object itself. When you modify the object inside the method, it is still modified after the method (which is normal since it is the same object).
If you don't want your method to create any side effect, you have create a copy of the matrix at the beginning of your method and modify the copy.
Additional note:
You may wonder why when the input is a primitive type, then the value is still the same outside the method, like this:
public void modify(int i){
i = 5;
}
That's because Java is pass by value, which means that the value of i is copied when the method is called, so only the copy is modified. As I wrote above, objects references are also passed by value, which means that the reference is copied. (to explain it roughly, you copy the value of the pointer to the object).
If you'd like a more detailed explanation, you can read this : http://www.javadude.com/articles/passbyvalue.htm

Related

How does this array variable reference act?

I was wondering how something like this would work.
int[] a = {5, 3, 4};
int[] b = {3, 4, 5};
a = b;
Does this mean that a will now reference b.
So if I do a[0] it will be 3?
Also if this is the case what happens to the items in the old array?
Does this mean that a will now reference b. So if I do a[0] it will be 3?
Sort of. a doesn't reference b (the variable), it references the same array that b refers to. There's no connection between a and b, it's just that they both refer to the same array (after the a = b assignment).
Also if this is the case what happens to the items in the old array?
The old array is eligible for garbage collection, since nothing refers to it anymore. Since it's an array of primitive values, the items are part of the array, so GC'ing the array inherently means the items are GC'd.
In memory, initially you had:
+−−−−−−−−−+
a:Ref33423−−−>| (Array) |
+−−−−−−−−−+
| 5 |
| 3 |
| 4 |
+−−−−−−−−−+
+−−−−−−−−−+
b:Ref54687−−−>| (Array) |
+−−−−−−−−−+
| 3 |
| 4 |
| 5 |
+−−−−−−−−−+
Then after the a = b;, you have:
+−−−−−−−−−+
| (Array) |
+−−−−−−−−−+
| 5 |
| 3 |
| 4 |
+−−−−−−−−−+
a:Ref54687−−+
|
| +−−−−−−−−−+
+−>| (Array) |
| +−−−−−−−−−+
| | 3 |
b:Ref54687−−+ | 4 |
| 5 |
+−−−−−−−−−+
...and eventually GC will remove that orphaned array:
a:Ref54687−−+
|
| +−−−−−−−−−+
+−>| (Array) |
| +−−−−−−−−−+
| | 3 |
b:Ref54687−−+ | 4 |
| 5 |
+−−−−−−−−−+
I should note that if it had been an array of objects, the array and each object the array referred to would potentially have different lifespans, GC'ing the array doesn't necessarily mean the objects in it are GC'd (it depends on whether anything else has references to them).
Does this mean that a will now reference b. So if I do a[0] it will be 3?
Yes, you can think a and b as remote controllers of two TVs. a=b means a is pointing where b is pointing. So a[0] will be 3.
Also if this is the case what happens to the items in the old array?
As there are currently no references to the first array, they're are going to be garbage collected.
Yes, now a will refer b and a[0] will be 3.
Also, now there will be no reference to the old array so it will be eligible for Garbage Collection.
int[] a = {5, 3, 4};
int[] b = {3, 4, 5};
System.out.println(a[0]);//5
a=b;
System.out.println(a[0]);//3

Resolving a stack with 2 recursive calls

I'm trying to refresh my skills in recursion and so far everything has gone well. However, I have never seen a problem where a string is the value of two recursive calls. Does the first recursive call ignore the rest of the statement? Is the 2nd recursive call still taken into account when it is resolved? I tried tracing it under the assumption that like a return statement, the first recursive call would break the loop. Therefore, I was under the impression that the rest of the code in the if statement would not be taken into account.
public class Example {
public static String encrypt(String word) {
int pos = word.length() / 2;
if (pos >= 1)
word = encrypt(word.substring(pos)) + encrypt(word.substring(0,pos));
return word;
}
public static void main(String []args){
System.out.println(encrypt("SECRET"));
}
}
While my expected output was "TETRET", the actual output was supposed to be "TERCES." Anyone mind explaining where my tracing or logic went wrong?
I tried tracing it under the assumption that like a return statement, the first recursive call would break the loop.
This is incorrect. Both will be evaluated.
word = encrypt(word.substring(pos)) + encrypt(word.substring(0,pos));
The first recursive call will get pushed onto the stack, and the second will be saved on the stack to be evaluated once the first call has been returned to the call stack. Here's a visual representation:
1
/ \
2 5
/ \
3 4
This is assuming 3, 4, and 5 reach the base case and thus do not continue the recursion
The word is returned in reverse order. I am unsure what you were trying to do instead. Here is a partial trace of your code, using "ABCDEF" instead of "SECRET", showing how it works :
+=================================+====================+===========================================+==============+==========================================+==============+
| word (initial call) | pos (initial call) | word (call 2) | pos (call 2) | word (call 3) | pos (call 3) |
+=================================+====================+===========================================+==============+==========================================+==============+
| "ABCDEF" | 3 | | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| encrypt("DEF") + encrypt("ABC") | | "DEF" | 1 | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | encrypt("EF") + encrypt ("D") | | "EF" | 1 |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | encrypt("F") + encrypt("E") | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | (call 4 returns "F", call 5 returns "E") | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | "FE" | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | (call 3 returns "FE", call 6 returns "D") | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | "FED" | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
Here is the order in which the calls are made and "resolved" (by resolved, I mean that the return statement of the function is executed) :
encrypt("ABCDEF")
encrypt("DEF")
encrypt("EF")
encrypt("F")
resolution of encrypt("F") // returns "F"
encrypt("E")
resolution of encrypt("E") // returns "E"
resolution of encrypt("EF") // returns "FE"
encrypt("D")
resolution of encrypt("D") // returns "D"
resolution of encrypt("DEF") // returns "FED"
encrypt("ABC")
(...)
Of course the same logic applies to encrypt "ABC" as it did to encrypt "DEF", so if you understand this part you should understand the rest.
If you place the print statement as I have shown, you can see how the returned word and pos are altered. Then just backtracking off the stack, the word is reconstructed in reverse order.
public class Example {
public static String encrypt(String word) {
int pos = word.length() / 2;
System.out.println(word + " " + pos);
if (pos >= 1) {
word = encrypt(word.substring(pos)) + encrypt(word.substring(0, pos));
}
return word;
}
public static void main(String[] args) {
System.out.println(encrypt("SECRET"));
}
}
Produces the following output:
SECRET 3
RET 1
ET 1
T 0
E 0
R 0
SEC 1
EC 1
C 0
E 0
S 0
TERCES

Representing Minesweeper Constraints in Sat4J/CNF

I'm trying to implement a minesweeper solver using a SAT solver (sat4j) and I have a simple understanding of how they work. But one thing I can't figure out is how to represent the x+y+Z+....=2 for mines, since SAT solvers use Boolean input. Something such as in the table below:
| a | b | c | d | e |
| f | 2 | g | 3 | h |
| i | j | k | l | m |
You could write a+b+c+f+g+i+j+k = 2 and c+d+e+g+h+k+l+m= 3.
if by a+b+c+f+g+i+j+k = 2 you mean that the surrounding cells contain exactly two mines, then your letters really are Boolean variables, and that constraint is called a cardinality constraint.
This is supported out of the box by Sat4j.
You may find some hints here:
https://sat4j.gitbooks.io/case-studies/content/

How to print a 2D array with varying sized cells?

I have a 2-D array where each cell is a Set.
In each set is a different size, say for example, ranging from 0 to 5.
I want to print out the 2-D array in a format such that it's easily readable.
Example
HashSet<String>[][] schedule = (HashSet<String>[][]) new HashSet[3][5];
schedule[0][0].add("A");
schedule[0][0].add("B");
schedule[0][0].add("C");
schedule[0][2].add("D");
schedule[0][2].add("E");
schedule[1][0].add("F");
schedule[1][1].add("G");
schedule.print();
will produce
-----------------
| A | | D | | |
| B | | E | | |
| C | | | | |
-----------------
| F | G | | | |
-----------------
| | | | | |
-----------------
obviously without the '-' and '|', but you get the point.
The only viable solution I can think of is creating and remembering the iterator for each column (so remembering 5 iterators at the same time) and iterating through each column, outputting one element at a time until there are no more elements in any of the iterators.
One problem is that in the case of G, it expands the second column even though there are not any values in the first row, second column. I can get around this by buffering each column with tabs.
Obviously this hack does not scale with additional columns, so I was wondering if there were any cute tricks that I might have forgotten.
Thanks!
With a few modifications to the code (you forgot to instantiate the positions in the array!), you can definitely print out the jagged sets.
Hint: Make use of the iterator() method that's provided with the HashSet. An iterator moves over a collection of objects, returning one at a time, then pausing until it's invoked again, or there's nothing left to iterate over. You can find more information about iterators in general at Wikipedia's Iterator article.
Using this, you can gather up the results in each HashSet inside of a String (in any way you desire), and print them out at the end.
Code Snippet:
Iterator first = schedule[0][0].iterator();
Iterator second = schedule[0][2].iterator();
// And so forth
String firstResult = "";
String secondResult = "";
// And so forth
while (first.hasNext()) {
firstResult += first.next() + "\t";
if (!first.hasNext()) {
firstResult += "\n";
}
}
while (second.hasNext()) {
secondResult += second.next() + "\t";
if (!second.hasNext()) {
secondResult += "\n";
}
}
// And so forth
System.out.print(firstResult + secondResult + someResult + anotherResult);
Filling in the blanks is an exercise for the reader.
With this, the result is as follows:
A B C
D E
F
G

How do I get the median/mode/range of a column in SQL using Java?

I have to get the median, mode and range of test scores from one column in a table but I am unsure how to go about doing that. When you connect to the database using java, you are normally returned a ResultSet that you can make a table or something out of but how do you get particular numbers or digits? Is there an SQL command to get the median/mode/range or will I have to calculate this myself, and how do you pull out numbers from the table in order to be able to calculate the mode/median/range?
Thanks.
This must be doable in pure SQL. Range is easy with MIN() and MAX() functions. For the remnant, I am no statistics expert, so I can't tell from head, but I found a link which may be of use: http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-chp-13-sect-2.html
13.2 Calculating Descriptive Statistics
13.2.1 Problem
You want to characterize a dataset by computing general descriptive or summary statistics.
13.2.2 Solution
Many common descriptive statistics, such as mean and standard deviation, can be obtained by applying aggregate functions to your data. Others, such as median or mode, can be calculated based on counting queries.
13.2.3 Discussion
Suppose you have a table testscore containing observations representing subject ID, age, sex, and test score:
mysql> SELECT subject, age, sex, score FROM testscore ORDER BY subject;
+---------+-----+-----+-------+
| subject | age | sex | score |
+---------+-----+-----+-------+
| 1 | 5 | M | 5 |
| 2 | 5 | M | 4 |
| 3 | 5 | F | 6 |
| 4 | 5 | F | 7 |
| 5 | 6 | M | 8 |
| 6 | 6 | M | 9 |
| 7 | 6 | F | 4 |
| 8 | 6 | F | 6 |
| 9 | 7 | M | 8 |
| 10 | 7 | M | 6 |
| 11 | 7 | F | 9 |
| 12 | 7 | F | 7 |
| 13 | 8 | M | 9 |
| 14 | 8 | M | 6 |
| 15 | 8 | F | 7 |
| 16 | 8 | F | 10 |
| 17 | 9 | M | 9 |
| 18 | 9 | M | 7 |
| 19 | 9 | F | 10 |
| 20 | 9 | F | 9 |
+---------+-----+-----+-------+
A good first step in analyzing a set of observations is to generate some descriptive statistics that summarize their general characteristics as a whole. Common statistical values of this kind include:
The number of observations, their sum, and their range (minimum and maximum)
Measures of central tendency, such as mean, median, and mode
Measures of variation, such as standard deviation or variance
Aside from the median and mode, all of these can be calculated easily by invoking aggregate functions:
mysql> SELECT COUNT(score) AS n,
-> SUM(score) AS sum,
-> MIN(score) AS minimum,
-> MAX(score) AS maximum,
-> AVG(score) AS mean,
-> STD(score) AS 'std. dev.'
-> FROM testscore;
+----+------+---------+---------+--------+-----------+
| n | sum | minimum | maximum | mean | std. dev. |
+----+------+---------+---------+--------+-----------+
| 20 | 146 | 4 | 10 | 7.3000 | 1.7916 |
+----+------+---------+---------+--------+-----------+
The aggregate functions as used in this query count only non-NULL observations. If you use NULL to represent missing values,you may want to perform an additional characterization to assess the extent to which values are missing. (See Recipe 13.5.)
Variance is not shown in the query, and MySQL has no function for calculating it. However, variance is just the square of the standard deviation, so it's easily computed like this:
STD(score) * STD(score)
STDDEV( ) is a synonym for STD( ).
Standard deviation can be used to identify outliers—values that are uncharacteristically far from the mean. For example, to select values that lie more than three standard deviations from the mean, you can do something like this:
SELECT #mean := AVG(score), #std := STD(score) FROM testscore;
SELECT score FROM testscore WHERE ABS(score-#mean) > #std * 3;
For a set of n values, the standard deviation produced by STD( ) is based on n degrees of freedom. This is equivalent to computing the standard deviation "by hand" as follows (#ss represents the sum of squares):
mysql> SELECT
-> #n := COUNT(score),
-> #sum := SUM(score),
-> #ss := SUM(score*score)
-> FROM testscore;
mysql> SELECT #var := ((#n * #ss) - (#sum * #sum)) / (#n * #n);
mysql> SELECT SQRT(#var);
+------------+
| SQRT(#var) |
+------------+
| 1.791647 |
+------------+
To calculate a standard deviation based on n-1 degrees of freedom instead, do it like this:
mysql> SELECT
-> #n := COUNT(score),
-> #sum := SUM(score),
-> #ss := SUM(score*score)
-> FROM testscore;
mysql> SELECT #var := ((#n * #ss) - (#sum * #sum)) / (#n * (#n - 1));
mysql> SELECT SQRT(#var);
+------------+
| SQRT(#var) |
+------------+
| 1.838191 |
+------------+
Or, more simply, like this:
mysql> SELECT #n := COUNT(score) FROM testscore;
mysql> SELECT STD(score)*SQRT(#n/(#n-1)) FROM testscore;
+----------------------------+
| STD(score)*SQRT(#n/(#n-1)) |
+----------------------------+
| 1.838191 |
+----------------------------+
MySQL has no built-in function for computing the mode or median of a set of values, but you can compute them yourself. The mode is the value that occurs most frequently. To determine what it is, count each value and see which one is most common:
mysql> SELECT score, COUNT(score) AS count
-> FROM testscore GROUP BY score ORDER BY count DESC;
+-------+-------+
| score | count |
+-------+-------+
| 9 | 5 |
| 6 | 4 |
| 7 | 4 |
| 4 | 2 |
| 8 | 2 |
| 10 | 2 |
| 5 | 1 |
+-------+-------+
In this case, 9 is the modal score value.
The median of a set of ordered values can be calculated like this:
If the number of values is odd, the median is the middle value.
If the number of values is even, the median is the average of the two middle values.
Note that the definition of median given here isn't fully general; it doesn't address what to do if there's duplication of the middle values in the dataset.
Based on that definition, use the following procedure to determine the median of a set of observations stored in the database:
Issue a query to count the number of observations. From the count, you can determine whether the median calculation requires one or two values, and what their indexes are within the ordered set of observations.
Issue a query that includes an ORDER BY clause to sort the observations, and a LIMIT clause to pull out the middle value or values.
Take the average of the selected value or values.
For example, if a table t contains a score column with 37 values (an odd number), you need to select a single value, using a query like this:
SELECT score FROM t ORDER BY 1 LIMIT 18,1
If the column contains 38 values (an even number), the query becomes:
SELECT score FROM t ORDER BY 1 LIMIT 18,2
Then you can select the value or values returned by the query and compute the median from their average.
The following Perl function implements a median calculation. It takes a database handle and the names of the table and column that contain the set of observations, then generates the query that retrieves the relevant values, and returns their average:
sub median
{
my ($dbh, $tbl_name, $col_name) = #_;
my ($count, $limit);
$count = $dbh->selectrow_array ("SELECT COUNT($col_name) FROM $tbl_name");
return undef unless $count > 0;
if ($count % 2 == 1) # odd number of values; select middle value
{
$limit = sprintf ("LIMIT %d,1", ($count-1)/2);
}
else # even number of values; select middle two values
{
$limit = sprintf ("LIMIT %d,2", $count/2 - 1);
}
my $sth = $dbh->prepare (
"SELECT $col_name FROM $tbl_name ORDER BY 1 $limit");
$sth->execute ( );
my ($n, $sum) = (0, 0);
while (my $ref = $sth->fetchrow_arrayref ( ))
{
++$n;
$sum += $ref->[0];
}
return ($sum / $n);
}
The preceding technique works for a set of values stored in the database. If you happen to have already fetched an ordered set of values into an array #val, you can compute the median like this instead:
if (#val == 0) # if array is empty, median is undefined
{
$median = undef;
}
elsif (#val % 2 == 1) # if array size is odd, median is middle number
{
$median = $val[(#val-1)/2];
}
else # array size is even; median is average
{ # of two middle numbers
$median = ($val[#val/2 - 1] + $val[#val/2]) / 2;
}
The code works for arrays that have an initial subscript of 0; for languages that used 1-based array indexes, adjust the algorithm accordingly.
I calculate the Trimmed/Truncated mean in SQL Server like this:
with tempResultSet as (
select Score,
ntile(20) over(order by Score) as n,
count(*) over() as x
from #TestScores
)
select avg(cast(Score as float))
from tempResultSet
where (x >= 20 and n between 2 and 19)
or (x < 20 and n between 2 and x - 1)
this removes the upper and lower 10% of your set and get the average of 'Score'
You don't tell us what database you are using so I assume that you want a solution that will work across standard SQL DBMS's.
You can use SQL to calculate range (using the aggregate functions MIN/MAX) and the mean (using AVG) in a simple aggregate.
Standard SQL doesn't support Median so what you need to do is get SQL to sort the output and go through the items till you find the 'middle' one.
Mode is not supported but note that you can use COUNT() and GROUP BY to get SQL to create a frequency listing (how many times each data point appears), the entry with the highest count is the mode.

Categories