Passing several arguments to single parameterized method with "|"? - java

I did some android stuff and found strange java code snippet.
I checked following with j2se and it gives commented results(without "prints").
Java code snippet looked like following:
class A{
public static void main(String[] args) {
method(1 | 2); //prints 3
method(1 | 2 | 3); //prints 3
method(1 | 2 | 3 | 4);//prints 7
}
public static void method(int value) {
System.out.println(value);
}
}
My question is what is happening here?

Bitwise OR
1 | 2 = '01' | '10' = 11 = 3
1 | 2 | 3 = '01' | '10' | '11' = 11 = 3
1 | 2 | 3 | 4 = '01' | '10' | '11' | '100' = 111 = 7

The | is a bitwise-OR operator.
It's applying an OR to the numeric values. Easier to see in binary:
1 | 2 | 3 | 4
1 is 0...00000001
2 is 0...00000010
3 is 0...00000011
4 is 0...00000100
OR: 0...00000111 bitwise OR of all values
0...00000111 = 7
It's not passing "multiple values", it's an arithmetic expression that evaluates to a single value.
However, it's frequently used to pass e.g. sets of "boolean" flags, where each flag is represented by a bit. For example:
static final int FLAG_CRISPY = 1; // 00000001 binary
static final int FLAG_SMOKED = 2; // 00000010 binary
static final int FLAG_ENDLESS = 4; // 00000100 binary
Then you may have a method:
void makeBacon (int flags) {
if ((flags & FLAG_CRISPY) != 0) // bitwise AND to check for flag
... flag is set
if ((flags & FLAG_SMOKED) != 0) // bitwise AND to check for flag
... flag is set
if ((flags & FLAG_ENDLESS) != 0) // bitwise AND to check for flag
... flag is set
}
And you can call it like:
makeBacon(FLAG_SMOKED | FLAG_ENDLESS);
Defining flags like this is convenient because you can modify the set of flags as the program evolves without having to make any changes to the method interface. It's also sometimes useful to be able to encapsulate a large set of options in a single int (e.g. when storing data to a binary file or sending over a network).
The official tutorial on bitwise and bit-shift operators has more information about other related operators (e.g. AND, XOR, left shift, right shift).

Related

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

why my up function changes input out of its block in 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

What does this sign exactly mean? |=

|=
I'm curious to learn about this operator,
I've seen this notation used while setting flags in Java.
for example:
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Does it perform some kind of bit manipulation?
What does this mark exactly do?
Are there any other well known signs similar to this?
It is equivalent to
notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;
where | is bitwise OR operator which OR the two variables bit-by-bit.
It is well known by itself. There are also +=, -=, *=, /=, %=, &=, ^=.
This syntax is also available in C/C++ and other languages. It is a bitwise OR and the same as:
notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;
and similar to other operators like addition, subtraction, etc. For example:
i += 5;
is the same as:
i = i + 5;
(1) Does it perform some kind of bit manipulation?
If you use | with numeric operands then yes, it will be bitwise OR, if you use it on boolean operands it will be logical (non-short-circuit) OR. Example
Logical OR: lets say that 1 represents true and 0 false
+---+---+-------+
| p | q | (p|q) |
+---+---+-------+
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
+---+---+-------+
Bitwise OR will perform similar operation as boolean but will use corresponding bits
decimal binary
6 = 00110
3 = 00011
OR -------------
00111
(2) What does this mark exactly do?
x |= y is the same as x = x | y so it will calculate x | y and store it in x.
(3) Are there any other well known signs similar to this?
Yes, every arithmetic, bitwise or bit shift operator can be used this way: += -= *= /= %= &= ^= |= <<= >>= >>>=
Here are some additional informations about usage of |= in
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Lets say that we have five properties.
Property1
Property2
Property3
Property4
Property5
We can use last five bits of number to represents situations where we have (1) or don't have (0) some property.
...00xxxxx
│││││
││││└─ flag for Property1
│││└── flag for Property2
││└─── flag for Property3
│└──── flag for Property4
└───── flag for Property5
Now, lets say that we want to use only properties 1, 2 and 4. To do this we have to set bits indexed with 0, 1 and 3 to value 1 like
...0001101
│││││
││││└─ (1) has Property1
│││└── (0) no Property2
││└─── (1) has Property3
│└──── (1) has Property4
└───── (0) no Property5
In other words we have to produce number 13 (= **1***8 + **1***4 + **0***2 + **1***1). We can do this with | OR bitwise operator 8|4|1 because
8 = ...001000
4 = ...000100
1 = ...000001
OR -------------
13 = ...001101
But to avoid magic numbers we can create constants that will represents our properties in bit world. So we can create
public class MyProperties {
//...
public static final int PROPERTY_1 = 0b0000_0001; // = 1
public static final int PROPERTY_2 = 0b0000_0010; // = 2
public static final int PROPERTY_3 = 0b0000_0100; // = 4
public static final int PROPERTY_4 = 0b0000_1000; // = 8
public static final int PROPERTY_5 = 0b0001_0000; // = 16
//...
//rest of code: methods, constructors, other fields
}
and use it later like
int context = Properties.PROPERTY_1|Properties.PROPERTY_2|Properties.PROPERTY_4
which is more readable than int context = 8|4|1.
Now if we want to change our context and lets say add PROPERTY_3 we can use
context = context | Properties.PROPERTY_3;
or shorter version based on compound assignments operators
context |= Properties.PROPERTY_3;
which will do this calculations
context = 000...00001101
PROPERTY_3 = 000...00000010
OR ------------------------
000...00001111
(main difference between adding value of PROPERTY_3 to context and using bitwise OR | is that when context will already have PROPERTY_3 set to 1 then OR will no effect it).
Now if you take a look here idea of using single bits as flags for properties was used in Notification class, where FLAG_AUTO_CANCEL constant has value 16 (0x010 in hexadecimal, 0b0001_0000 in binary).
Does it perform some kind of bit manipulation?
Yes. It "OR"s the right-hand-side operand into the left-hand-side one.
What does this mark exactly do?
It's an assignment coupled with an OR.
Are there any other well known signs such as this?
There are plenty: +=, -=, *=, /=, %=, &=, and so on. Collectively, they are called compound assignment operators. They are described in section 15.26.2 of the Java Language Specification.
It is called bitwise or operator. For example,
5 = 0000 0101
2 = 0000 0010
5 | 2 = 0000 0111
= 14
So, this concept is used when a same option can use multiple values.
As an example, consider a variable flags equal to one.
int flags = 1;
Now, if a flag value of 4 is added to it with bitwise or,
flags |= 4; // 0
You can determine whether 4 was applied on flags with the bitwise and.
if (flags & 4 == 4) // returns true
If that flag has been applied on the flags, bitwise and returns flag. In this way we can use bitwise and & bitwise or.
Hope this helps.

What does the pipe character do in a Java method call?

I've seen the pipe character used in method calls in Java programs.
For example:
public class Testing1 {
public int print(int i1, int i2){
return i1 + i2;
}
public static void main(String[] args){
Testing1 t1 = new Testing1();
int t3 = t1.print(4, 3 | 2);
System.out.println(t3);
}
}
When I run this, I simply get 7.
Can someone explain what the pipe does in the method call and how to use it properly?
The pipe in 3 | 2 is the bitwise inclusive OR operator, which returns 3 in your case (11 | 10 == 11 in binary).
it's a bitwise OR.
The bitwise representation of numbers is like this:
|2^2|2^1|2^0|
| 4 | 2 | 1 |
the bitwise representation of 3 is:
|2^2|2^1|2^0|
| 4 | 2 | 1 |
| - | X | X | => 3
the bitwise representation of 2 is:
|2^2|2^1|2^0|
| 4 | 2 | 1 |
| - | X | - | => 2
The bitwise OR will return 3 because when using OR at least one bit must be "occupied". Since the first and second bit are occupied (3 | 2) will return 3.
Finally, the addition 4 + 3 = 7.
The | operator performs a bitwise OR on the operands:
3 | 2 ---> 0011 (3 in binary)
OR 0010 (2 in binary)
---------
0011 (3 in binary)
Here's the pattern:
0 OR 0: 0
0 OR 1: 1
1 OR 0: 1
1 OR 1: 1
Using |:
if(someCondition | anotherCondition)
{
/* this will execute as long as at least one
condition is true */
}
Note that this is similar to the short-circuit OR (||) commonly used in if statements:
if(someCondition || anotherCondition)
{
/* this will also execute as long as at least one
condition is true */
}
(except that || does not enforce the need to continue checking other conditions once a true expression has been found.)

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