What is use of << I understand in array it is used for push but here I am not clear what is purpose of this in following code. Where it is being used integer.
def array_pack(a)
a.reverse.reduce(0) { |x, b| (x << 8) + b }
end
array_pack([24, 85, 0]) # will print 21784
like if I x is 8 and I write 8 << 8 it gives me response of 2048 so is it converting in bytes? or what exact is its purpose.
It is a Bitwise LEFT shift operator.
Definition:
The LEFT SHIFT operator << shifts each bit of a number to the left by n positions.
Example:
If you do 7 << 2 = 28
7 in Base 2: 0000 0111
128 64 32 16 8 4 2 1
----------------------
7: 0 0 0 0 0 1 1 1
Now shift each bit to the left by 2 positions
128 64 32 16 8 4 2 1
----------------------
28: 0 0 0 1 1 1 0 0
Why?
Bitwise operators are widely used for low-level programming on embedded systems to apply a mask (in this case to integer)
Benefits
See this SO answer: link
View Source for more details: link
As the documentation says, Integer:<< - Returns the integer shifted left "X" positions, or right if "X" is negative. In your scenario is shifts 8 positions to the left.
Here is how it works:
8.to(2) => "1000"
Now let's shift "1000" 8 positions to the left
(8 << 8).to_s(2) => "100000000000"
If you count the 0 above you will see it added 8 after "1000".
Now, let's see how it returns 2048
"100000000000".to_i(2) => 2048
I'd like to create a function where for an arbitrary integer input value (let's say unsigned 32 bit) and a given number of d digits the return value will be a d digit B base number, B being the smallest base that can be used to represent the given input on d digits.
Here is a sample input - output of what I have in mind for 3 digits:
Input Output
0 0 0 0
1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 0 0 2
9 0 1 2
10 1 0 2
11 1 1 2
12 0 2 0
13 0 2 1
14 1 2 0
15 1 2 1
16 2 0 0
17 2 0 1
18 2 1 0
19 2 1 1
20 0 2 2
21 1 2 2
22 2 0 2
23 2 1 2
24 2 2 0
25 2 2 1
26 2 2 2
27 0 0 3
28 0 1 3
29 1 0 3
30 1 1 3
.. .....
The assignment should be 1:1, for each input value there should be exactly one, unique output value. Think of it as if the function should return the nth value from the list of strangely sorted B base numbers.
Actually this is the only approach I could come up so far with - given an input value, generate all the numbers in the smallest possible B base to represent the input on d digits, then apply a custom sorting to the results ('penalizing' the higher digit values and putting them further back in the sort), and return the nth value from the sorted array. This would work, but is a spectacularly inefficient implementation - I'd like to do this without generating all the numbers up to the input value.
What would be an efficient approach for implementing this function? Any language or pseudocode is fine.
MBo's answer shows how to find the smallest base that will represent an integer number with a given number of digits.
I'm not quite sure about the ordering in your example. My answer is based on a different ordering: Create all possible n-digit numbers up to base b (e.g. all numbers up to 999 for max. base 10 and 3 digits). Sort them according to their maximum digit first. Numbers are sorted normalls within a group with the same maximum digit. This retains the characteristic that all values from 8 to 26 must be base 3, but the internal ordering is different:
8 0 0 2
9 0 1 2
10 0 2 0
11 0 2 1
12 0 2 2
13 1 0 2
14 1 1 2
15 1 2 0
16 1 2 1
17 1 2 2
18 2 0 0
19 2 0 1
20 2 0 2
21 2 1 0
22 2 1 1
23 2 1 2
24 2 2 0
25 2 2 1
26 2 2 2
When your base is two, life is easy: Just generate the appropriate binary number.
For other bases, let's look at the first digit. In the example above, five numbers start with 0, five start with 1 and nine start with 2. When the first digit is 2, the maximum digit is assured to be 2. Therefore, we can combine 2 with a 9 2-digit numbers of base 3.
When the first digit is smaller than the maximum digit in the group, we can combine it with the 9 2-digit numbers of base 3, but we must not use the 4 2-digit numbers that are ambiguous with the 4 2-digit numbers of base 2. That gives us five possibilites for the digits 0 and 1. These possibilities – 02, 12, 20, 21 and 22 – can be described as the unique numbers with two digits according to the same scheme, but with an offset:
4 0 2
5 1 2
6 2 0
7 2 1
8 2 2
That leads to a recursive solution:
for one digit, just return the number itself;
for base two, return the straightforward representation in base 2;
if the first number is the maximum digit for the determined base, combine it with a straighforward representations in that base;
otherwise combine it with a recursively determined representation of the same algorithm with one fewer digit.
Here's an example in Python. The representation is returned as list of numbers, so that you can represent 2^32 − 1 as [307, 1290, 990].
import math
def repres(x, ndigit, base):
"""Straightforward representation of x in given base"""
s = []
while ndigit:
s += [x % base]
x /= base
ndigit -= 1
return s
def encode(x, ndigit):
"""Encode according to min-base, fixed-digit order"""
if ndigit <= 1:
return [x]
base = int(x ** (1.0 / ndigit)) + 1
if base <= 2:
return repres(x, ndigit, 2)
x0 = (base - 1) ** ndigit
nprev = (base - 1) ** (ndigit - 1)
ncurr = base ** (ndigit - 1)
ndiff = ncurr - nprev
area = (x - x0) / ndiff
if area < base - 1:
xx = x0 / (base - 1) + x - x0 - area * ndiff
return [area] + encode(xx, ndigit - 1)
xx0 = x0 + (base - 1) * ndiff
return [base - 1] + repres(x - xx0, ndigit - 1, base)
for x in range(32):
r = encode(x, 3)
print x, r
Assuming that all values are positive, let's make simple math:
d-digit B-based number can hold value N if
Bd > N
so
B > N1/d
So calculate N1/d value, round it up (increment if integer), and you will get the smallest base B.
(note that numerical errors might occur)
Examples:
d=2, N=99 => 9.95 => B=10
d=2, N=100 => 10 => B=11
d=2, N=57 => 7.55 => B=8
d=2, N=33 => 5.74 => B=6
Delphi code
function GetInSmallestBase(N, d: UInt32): string;
const
Digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
Base, i: Byte;
begin
Base := Ceil(Power(N, 1/d) + 1.0E-12);
if Base > 36 then
Exit('Big number, few digits...');
SetLength(Result, d);
for i := d downto 1 do begin
Result[i] := Digits[1 + N mod Base]; //Delphi string is 1-based
N := N div Base;
end;
Result := Result + Format(' : base [%d]', [Base]);
end;
begin
Memo1.Lines.Add(GetInSmallestBase(99, 2));
Memo1.Lines.Add(GetInSmallestBase(100, 2));
Memo1.Lines.Add(GetInSmallestBase(987, 2));
Memo1.Lines.Add(GetInSmallestBase(1987, 2));
Memo1.Lines.Add(GetInSmallestBase(87654321, 6));
Memo1.Lines.Add(GetInSmallestBase(57, 2));
Memo1.Lines.Add(GetInSmallestBase(33, 2));
99 : base [10]
91 : base [11]
UR : base [32]
Big number, few digits...
H03LL7 : base [22]
71 : base [8]
53 : base [6]
This question already has answers here:
How Does Modulus Divison Work
(19 answers)
Closed 8 years ago.
What does the % symbol mean in Ruby? For example, I use the following code:
puts "Roosters #{100 - 25 * 3 % 4}"
And get the following output:
97
Where the deuce did the 97 come from? I've looked up what the modulo operator is and still have no idea what it does in this simple mathematics example.
Modulo operator.
It does division and returns the remainder. So, in your case, 75 / 4 is 18 with a remainder of 3.
25 * 3 = 75
75 % 4 = 3 (the remainder)
100 - 3 = 97
modulo - divide with remainder
divide, and take the remainder from the integer division.
10 / 3 = 3 (with remainder 1 that we discard with integer division)
10 % 3 = 1 (the part we normally discard is the part we are interested in with mod)
It is also used to create cycles. If we had a sequence of 1 to N, we could mod it by M and produce a cycle. Assume M = 3 again
for n in 0..10
m = n % 3
puts "#{n} mod 3 = #{m}"
end
0 mod 3 = 0
1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
5 mod 3 = 2
6 mod 3 = 0
7 mod 3 = 1
8 mod 3 = 2
9 mod 3 = 0
10 mod 3 = 1
I don't understand this
2.0.0p247 :616 > 5 ^ 2
=> 7
2.0.0p247 :617 > 5 ^ 1
=> 4
What 7 and 4 means in those scenarios?
I try reading here http://en.wikipedia.org/wiki/Exclusive_disjunction but cannot figure out by looking into the diagrams what is the subtract here. Sorry if this is simple math question.
It has to do with the binary representation of the values.
5 = 0101
2 = 0010
1 = 0001
Now the XOR works like this:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
so to compute 5 ^ 2, let's apply the ^ operation to each column:
0101 (this is 5)
0010 (this is 2)
----
0111 ==> which is the binary representation of 7
How did this work? In the leftmost column, we computed 0^0=0. In the second column, 1^0=1. In the third column 0^1=1, and so on.
and 5 ^ 1
0101 (this is 5)
0001 (this is 1)
----
0100 ==> which is the binary represenation of 4
I would like to know what & does in the use case:
7 & 3
=> 3
8 & 3
=> 0
Or as seen in the general use case:
Integer & Integer
=> ??
I know that array & array2 gives the intersection between the two arrays, but I am unsure of exactly what is going on here when used with integers.
& is bitwise AND which examines the two operands bit-by-bit and sets each result bit to 1 if both the corresponding input bits are 1, and 0 otherwise. You can also think of it as bit-by-bit multiplication.
111 (7)
AND 011 (3)
------------
= 011 (3)
1000 (8)
AND 0011 (3)
------------
= 0000 (0)