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
Related
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
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
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/
I have to solve the following problem. So initially i had a bubble sort and now i modified it to make it bidirectional. The following is my solution.
public void bubbleSort() {
int temp;
int out;
int outNew = 0;
int in;
for (out = nElems - 1; out > outNew; out--) {
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
temp = a[in + 1];
a[in + 1] = a[in];
a[in] = temp;
}
}
for (int j = in - 1; j > outNew; j--) {
if (a[j] < a[j - 1]) {
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
outNew++;
}
}
When i call my bubble sort to sort few random numbers in an array i created it seems to be sorting fine. My question is rather to all you developers whether my solution is satisfying the question posted above and also what could i have done differently to make this solution more effective (if possible) . I am sorry if this is a little open question , i am usually on here looking for hints and suggestions rather than code as it helps me learn better. I appreciate all answers and am open to any suggestions.
Your first inner loop seems a bit inefficient, since your array will be partially sorted at both ends. After the first round (one time incrementing the index, one time decreasing it) the first and the last element will already be correct, hence no need to start at index 0 (and the task/exercise requires that btw).
The following ASCII art demonstrates, on which indices the algorithm should operate on at the example of a array with 9 elements (including the indices reached with in+1 and j-1; all indices between the | should be considered):
position: 0 1 2 3 4 5 6 7 8
------------------------------------------------------------
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
But what your algorithm does is:
position: 0 1 2 3 4 5 6 7 8
------------------------------------------------------------
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
You'll have to fix the the initial index of the first inner for loop.
In short, I don't think you can me more effective AND answer the question at the same time. It's pretty explicit in that you have to carry your item to the right until you find one smaller, then take that slightly smaller than the last you carried and bring it up. I don't think there's any performance gain from the regular unidirectional bubble sort but if you're going to make it bidirectional, then this is the way to do it.
How can you tell? Well since there's no performance gain/deterioration to get, the left->right code and the right->left code should be perfectly symmetrical (since they're identical in performance terms). In your case, there are so I'd say it looks good.
Thinking a bit deeper, there's probably some slight optimization to get from being bidirectional, just because you're getting an item you just looked at so you know you can bring to the left from it's initial position, skipping the right side of the array. But in the end, it's negligible and it's still O(n²) performance, no matter how you slice it.
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.