Why are XOR often used in java hashCode() but another bitwise operators are used rarely? - hash

I often see code like
int hashCode(){
return a^b;
}
Why XOR?

Of all bit-operations XOR has the best bit shuffling properties.
This truth-table explains why:
A B AND
0 0 0
0 1 0
1 0 0
1 1 1
A B OR
0 0 0
0 1 1
1 0 1
1 1 1
A B XOR
0 0 0
0 1 1
1 0 1
1 1 0
As you can see for AND and OR do a poor job at mixing bits.
OR will on average produce 3/4 one-bits. AND on the other hand will produce on average 3/4 null-bits. Only XOR has an even one-bit vs. null-bit distribution. That makes it so valuable for hash-code generation.
Remember that for a hash-code you want to use as much information of the key as possible and get a good distribution of hash-values. If you use AND or OR you'll get numbers that are biased towards either numbers with lots of zeros or numbers with lots of ones.

XOR has the following advantages:
It does not depend on order of computation i.e. a^b = b^a
It does not "waste" bits. If you change even one bit in one of the components, the final value will change.
It is quick, a single cycle on even the most primitive computer.
It preserves uniform distribution. If the two pieces you combine are uniformly distributed so will the combination be. In other words, it does not tend to collapse the range of the digest into a narrower band.
More info here.

XOR operator is reversible, i.e. suppose I have a bit string as 0 0 1 and I XOR it with another bit string 1 1 1, the the output is
0 xor 1 = 1
0 1 = 1
1 1 = 0
Now I can again xor the 1st string with the result to get the 2nd string. i.e.
0 1 = 1
0 1 = 1
1 0 = 1
So, that makes the 2nd string a key. This behavior is not found with other bit operator
Please see this for more info --> Why is XOR used on Cryptography?

There is another use case: objects in which (some) fields must be compared without regarding their order. For example, if you want a pair (a, b) be always equal to the pair (b, a).
XOR has the property that a ^ b = b ^ a, so it can be used in hash function in such cases.
Examples: (full code here)
definition:
final class Connection {
public final int A;
public final int B;
// some code omitted
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Connection that = (Connection) o;
return (A == that.A && B == that.B || A == that.B && B == that.A);
}
#Override
public int hashCode() {
return A ^ B;
}
// some code omitted
}
usage:
HashSet<Connection> s = new HashSet<>();
s.add(new Connection(1, 3));
s.add(new Connection(2, 3));
s.add(new Connection(3, 2));
s.add(new Connection(1, 3));
s.add(new Connection(2, 1));
s.remove(new Connection(1, 2));
for (Connection x : s) {
System.out.println(x);
}
// output:
// Connection{A=2, B=3}
// Connection{A=1, B=3}

Related

what is mean by swift condition is if ((status & 0x3F) == 1 ){ }

if ((status & 0x3F) == 1 ){ }..
the status is variable in swift language.
what is mean about this condition, & mean and (status & 0x3F) value return
& is the bitwise AND operator. It compares the bits of the two operands and sets the corresponding bit to 1 if it is 1 in both operands, or to 0 if either or both are 0.
So this statement:
((status & 0x3F) == 1)
is combining status with 0b111111 (the binary equivalent of 0x3F and checking if the result is exactly 1. This will only be true if the last 6 bits of status are 0b000001.
In this if:
if( (dtc24_state[2] & 0x8) == 0x8 ) {
self.haldexABCDTC24State.text = status_str + " - UNKNOWN"
self.haldexABCDTC24State.textColor = text_color
active_or_stored_dtc = true
}
dct24_state is an array of values. The value of dct24_state[2] is combined with 0x8 or 0b1000 and checked against 0x8. This is checking if the 4th bit from the right is set. Nothing else matters. If the 4th bit from the right is set, the if is true and the code block is executed.
0x3F is 111111. So, it means this:
for each bit of yourNumber in binary system presentation use and method.
This way truncates the left part of the number. and the result compares with 1.
e.g.
7777 is 1111001100001 after executing and this number converts into
100001. So the result is false.
But for 7745 (1111001000001) the result is 1. The result is true.
The rule for 'and' function: 0 & 0 = 0 ; 0 & 1 = 0; 1 & 0 = 1; 1 & 1 = 1.

DP Coin Change Algorithm - Retrieve coin combinations from table

To find how many ways we have of making change for the amount 4 given the coins [1,2,3], we can create a DP algorithm that produces the following table:
table[amount][coins.count]
0 1 2 3 4
-----------
(0) 1 | 1 1 1 1 1
(1) 2 | 1 1 2 2 3
(2) 3 | 1 1 2 3 4
The last position being our answer. The answer is 4 because we have the following combinations: [1,1,1,1],[2,1],[2,2],[3,1].
My question is, is it possible to retrieve these combinations from the table I just generated? How?
For completeness, here's my algorithm
func coinChange(coins: [Int], amount: Int) -> Int {
// int[amount+1][coins]
var table = Array<Array<Int>>(repeating: Array<Int>(repeating: 0, count: coins.count), count: amount + 1)
for i in 0..<coins.count {
table[0][i] = 1
}
for i in 1...amount {
for j in 0..<coins.count {
//solutions that include coins[j]
let x = i - coins[j] >= 0 ? table[i - coins[j]][j] : 0
//solutions that don't include coins[j]
let y = j >= 1 ? table[i][j-1] : 0
table[i][j] = x + y
}
}
return table[amount][coins.count - 1];
}
Thanks!
--
Solution
Here's an ugly function that retrieves the combinations, based on #Sayakiss 's explanation:
func getSolution(_ i: Int, _ j: Int) -> [[Int]] {
if j < 0 || i < 0 {
//not a solution
return []
}
if i == 0 && j == 0 {
//valid solution. return an empty array where the coins will be appended
return [[]]
}
return getSolution(i - coins[j], j).map{var a = $0; a.append(coins[j]);return a} + getSolution(i, j - 1)
}
getSolution(amount, coins.count-1)
Output:
[[1, 3], [2, 2], [1, 1, 2], [1, 1, 1, 1]]
Sure you can. We define a new function get_solution(i,j) which means all solution for your table[i][j].
You can think it returns an array of array, for example, the output of get_solution(4,3) is [[1,1,1,1],[2,1],[2,2],[3,1]]. Then:
Case 1. Any solution from get_solution(i - coins[j], j) plus coins[j] is a solution for table[i][j].
Case 2. Any solution from get_solution(i, j - 1) is a solution for table[i][j].
You can prove Case 1 + Case 2 is all possible solution for table[i][j](note you get table[i][j] by this way).
The only problem remains is to implement get_solution(i,j) and I think it's good for you to do it by yourself.
If you still got any question, please don't hesitate to leave a comment here.

How to normalize Integer variable to positive negative or zero with bit operations

7 -> 1
0 -> 0
-7 -> -1
I've have code:
(x == 0 ? 0 : x / abs(x)) + 1
but is it possible to avoid division and make it faster?
How about
(x == 0 ? 0 : (x < 0 ? -1 : 1))
The idea was to use bit operations to avoid branching code or value conversion.
Haven't found how to do it with bit operations but apple already add this function
https://developer.apple.com/documentation/swift/int/2886673-signum
signum()
Returns -1 if this value is negative and 1 if it’s positive; otherwise, 0.
so simple) raw test shows ~x100 faster implementation

ios how to check if division remainder is integer

any of you knows how can I check if the division remainder is integer or zero?
if ( integer ( 3/2))
You should use the modulo operator like this
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}
It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
Walkthrough
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true
swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}
You can use the below code to know which type of instance it is.
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
let me know if the above was useful.
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
Swift 2.0
print(Int(Float(9) % Float(4))) // result 1

How to write the following boolean expression?

I've got three boolean values A, B and C. I need to write an IF statement which will execute if and only if no more than one of these values is True. In other words, here is the truth table:
A | B | C | Result
---+---+---+--------
0 | 0 | 0 | 1
0 | 0 | 1 | 1
0 | 1 | 0 | 1
0 | 1 | 1 | 0
1 | 0 | 0 | 1
1 | 0 | 1 | 0
1 | 1 | 0 | 0
1 | 1 | 1 | 0
What is the best way to write this? I know I can enumerate all possibilities, but that seems... too verbose. :P
Added: Just had one idea:
!(A && B) && !(B && C) && !(A && C)
This checks that no two values are set. The suggestion about sums is OK as well. Even more readable maybe...
(A?1:0) + (B?1:0) + (C?1:0) <= 1
P.S. This is for production code, so I'm going more for code readability than performance.
Added 2: Already accepted answer, but for the curious ones - it's C#. :) The question is pretty much language-agnostic though.
how about treating them as integer 1's and 0's, and checking that their sum equals 1?
EDIT:
now that we know that it's c#.net, i think the most readable solution would look somewhat like
public static class Extensions
{
public static int ToInt(this bool b)
{
return b ? 1 : 0;
}
}
the above tucked away in a class library (appcode?) where we don't have to see it, yet can easily access it (ctrl+click in r#, for instance) and then the implementation will simply be:
public bool noMoreThanOne(params bool[] bools)
{
return bools.ToList().Sum(b => b.ToInt()) <= 1;
}
...
bool check = noMoreThanOne(true, true, false, any, amount, of, bools);
You shold familiarize yourself with Karnaugh maps. Concept is most often applied to electronics but is very useful here too. It's very easy (thought Wikipedia explanation does look long -- it's thorough).
(A XOR B XOR C) OR NOT (A OR B OR C)
Edit: As pointed out by Vilx, this isn't right.
If A and B are both 1, and C is 0, A XOR B will be 0, the overall result will be 0.
How about:
NOT (A AND B) AND NOT (A AND C) AND NOT (B AND C)
If you turn the logic around, you want the condition to be false if you have any pair of booleans that are both true:
if (! ((a && b) || (a && c) || (b && c))) { ... }
For something completely different, you can put the booleans in an array and count how many true values there are:
if ((new bool[] { a, b, c }).Where(x => x).Count() <= 1) { ... }
I'd go for maximum maintainability and readability.
static bool ZeroOrOneAreTrue(params bool[] bools)
{
return NumThatAreTrue(bools) <= 1;
}
static int NumThatAreTrue(params bool[] bools)
{
return bools.Where(b => b).Count();
}
There are many answers here, but I have another one!
a ^ b ^ c ^ (a == b && b == c)
A general way of finding a minimal boolean expression for a given truth table is to use a Karnaugh map:
http://babbage.cs.qc.edu/courses/Minimize/
There are several online minimizers on the web. The one here (linked to from the article, it's in German, though) finds the following expression:
(!A && !B) || (!A && !C) || (!B && !C)
If you're going for code readability, though, I would probably go with the idea of "sum<=1". Take care that not all languages guarantee that false==0 and true==1 -- but you're probably aware of this since you've taken care of it in your own solution.
Good ol' logic:
+ = OR
. = AND
R = Abar.Bbar.Cbar + Abar.Bbar.C + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar.(Cbar + C) + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar + CBar(A XOR B)
= NOT(A OR B) OR (NOT C AND (A XOR B))
Take the hint and simplify further if you want.
And yeah, get your self familiar with Karnaugh Maps
Depends whether you want something where it's easy to understand what you're trying to do, or something that's as logically simple as can be. Other people are posting logically simple answers, so here's one where it's more clear what's going on (and what the outcome will be for different inputs):
def only1st(a, b, c):
return a and not b and not c
if only1st(a, b, c) or only1st(b, a, c) or only1st(c, a, b):
print "Yes"
else:
print "No"
I like the addition solution, but here's a hack to do that with bit fields as well.
inline bool OnlyOneBitSet(int x)
{
// removes the leftmost bit, if zero, there was only one set.
return x & (x-1) == 0;
}
// macro for int conversion
#define BOOLASINT(x) ((x)?1:0)
// turn bools a, b, c into the bit field cba
int i = (BOOLASINT(a) << 0) | BOOLASINT(b) << 1 | BOOLASINT(c) << 2;
if (OnlyOneBitSet(i)) { /* tada */ }
Code demonstration of d's solution:
int total=0;
if (A) total++;
if (B) total++;
if (C) total++;
if (total<=1) // iff no more than one is true.
{
// execute
}