What is the meaning of "exclusive" and "inclusive" when describing number ranges? - algorithm

Simple question but, I see exclusive and inclusive when referring to number ranges.
For example, this is a line from an algorithms book:
The following function prints the powers of 2 from 1 through n (inclusive).
What is meant by this? What makes a number range inclusive or exclusive?

In Computer Science, inclusive/exclusive doesn't apply to algorithms, but to a number range (more specifically, to the endpoint of the range):
1 through 10 (inclusive)
1 2 3 4 5 6 7 8 9 10
1 through 10 (exclusive)
1 2 3 4 5 6 7 8 9
In mathematics, the 2 ranges above would be:
[1, 10]
[1, 10)
You can remember it easily:
Inclusive - Including the last number
Exclusive - Excluding the last number

The following function prints the powers of 2 from 1 through n (inclusive).
This means that the function will compute 2^i where i = 1, 2, ..., n, in other words, i can have values from 1 up to and including the value n. i.e n is Included in Inclusive
If, on the other hand, your book had said:
The following function prints the powers of 2 from 1 through n (exclusive).
This would mean that i = 1, 2, ..., n-1, i.e. i can take values up to n-1, but not including, n, which means i = n-1 is the highest value it could have.i.e n is excluded in exclusive.

In simple terms, inclusive means within and the number n, while exclusive means within and without the number n.
Note: that each argument should be marked its "clusivity"/ "participation"
# 1 (inclusive) through 5 (inclusive)
1 <= x <= 5 == [1, 2, 3, 4, 5]
# 1 (inclusive) through 5 (exclusive)
1 <= x < 5 == [1, 2, 3, 4]
# 1 (exclusive) through 5 (inclusive)
1 < x <= 5 == [2, 3, 4, 5]
# 1 (exclusive) through 5 (exclusive)
1 < x < 5 == [2, 3, 4]

The value of n inclusive 2 and 5 [2,5]
including both the numbes in case exclusive only the first is included
programming terms n>=2 && n<=5
The value of of n exlcusive of 2 and 5 [2,5)
n>=2 && n<5

Related

Kth element in transformed array

I came across this question in recent interview :
Given an array A of length N, we are supposed to answer Q queries. Query form is as follows :
Given x and k, we need to make another array B of same length such that B[i] = A[i] ^ x where ^ is XOR operator. Sort an array B in descending order and return B[k].
Input format :
First line contains interger N
Second line contains N integers denoting array A
Third line contains Q i.e. number of queries
Next Q lines contains space-separated integers x and k
Output format :
Print respective B[k] value each on new line for Q queries.
e.g.
for input :
5
1 2 3 4 5
2
2 3
0 1
output will be :
3
5
For first query,
A = [1, 2, 3, 4, 5]
For query x = 2 and k = 3, B = [1^2, 2^2, 3^2, 4^2, 5^2] = [3, 0, 1, 6, 7]. Sorting in descending order B = [7, 6, 3, 1, 0]. So, B[3] = 3.
For second query,
A and B will be same as x = 0. So, B[1] = 5
I have no idea how to solve such problems. Thanks in advance.
This is solvable in O(N + Q). For simplicity I assume you are dealing with positive or unsigned values only, but you can probably adjust this algorithm also for negative numbers.
First you build a binary tree. The left edge stands for a bit that is 0, the right edge for a bit that is 1. In each node you store how many numbers are in this bucket. This can be done in O(N), because the number of bits is constant.
Because this is a little bit hard to explain, I'm going to show how the tree looks like for 3-bit numbers [0, 1, 4, 5, 7] i.e. [000, 001, 100, 101, 111]
*
/ \
2 3 2 numbers have first bit 0 and 3 numbers first bit 1
/ \ / \
2 0 2 1 of the 2 numbers with first bit 0, have 2 numbers 2nd bit 0, ...
/ \ / \ / \
1 1 1 1 0 1 of the 2 numbers with 1st and 2nd bit 0, has 1 number 3rd bit 0, ...
To answer a single query you go down the tree by using the bits of x. At each node you have 4 possibilities, looking at bit b of x and building answer a, which is initially 0:
b = 0 and k < the value stored in the left child of the current node (the 0-bit branch): current node becomes left child, a = 2 * a (shifting left by 1)
b = 0 and k >= the value stored in the left child: current node becomes right child, k = k - value of left child, a = 2 * a + 1
b = 1 and k < the value stored in the right child (the 1-bit branch, because of the xor operation everything is flipped): current node becomes right child, a = 2 * a
b = 1 and k >= the value stored in the right child: current node becomes left child, k = k - value of right child, a = 2 * a + 1
This is O(1), again because the number of bits is constant. Therefore the overall complexity is O(N + Q).
Example: [0, 1, 4, 5, 7] i.e. [000, 001, 100, 101, 111], k = 3, x = 3 i.e. 011
First bit is 0 and k >= 2, therefore we go right, k = k - 2 = 3 - 2 = 1 and a = 2 * a + 1 = 2 * 0 + 1 = 1.
Second bit is 1 and k >= 1, therefore we go left (inverted because the bit is 1), k = k - 1 = 0, a = 2 * a + 1 = 3
Third bit is 1 and k < 1, so the solution is a = 2 * a + 0 = 6
Control: [000, 001, 100, 101, 111] xor 011 = [011, 010, 111, 110, 100] i.e. [3, 2, 7, 6, 4] and in order [2, 3, 4, 6, 7], so indeed the number at index 3 is 6 and the solution (always talking about 0-based indexing here).

Implementation: Algorithm for a special distribution Problem

We are given a number x, and a set of n coins with denominations v1, v2, …, vn.
The coins are to be divided between Alice and Bob, with the restriction that each person's coins must add up to at least x.
For example, if x = 1, n = 2, and v1 = v2 = 2, then there are two possible distributions: one where Alice gets coin #1 and Bob gets coin #2, and one with the reverse. (These distributions are considered distinct even though both coins have the same denomination.)
I'm interested in counting the possible distributions. I'm pretty sure this can be done in O(nx) time and O(n+x) space using dynamic programming; but I don't see how.
Count the ways for one person to get just less than x, double it and subtract from the doubled total number of ways to divide the collection in two, (Stirling number of the second kind {n, 2}).
For example,
{2, 3, 3, 5}, x = 5
i matrix
0 2: 1
1 3: 1 (adding to 2 is too much)
2 3: 2
3 N/A (≥ x)
3 ways for one person to get
less than 5.
Total ways to partition a set
of 4 items in 2 is {4, 2} = 7
2 * 7 - 2 * 3 = 8
The Python code below uses MBo's routine. If you like this answer, please consider up-voting that answer.
# Stirling Algorithm
# Cod3d by EXTR3ME
# https://extr3metech.wordpress.com
def stirling(n,k):
n1=n
k1=k
if n<=0:
return 1
elif k<=0:
return 0
elif (n==0 and k==0):
return -1
elif n!=0 and n==k:
return 1
elif n<k:
return 0
else:
temp1=stirling(n1-1,k1)
temp1=k1*temp1
return (k1*(stirling(n1-1,k1)))+stirling(n1-1,k1-1)
def f(coins, x):
a = [1] + (x-1) * [0]
# Code by MBo
# https://stackoverflow.com/a/53418438/2034787
for c in coins:
for i in xrange(x - 1, c - 1, -1):
if a[i - c] > 0:
a[i] = a[i] + a[i - c]
return 2 * (stirling(len(coins), 2) - sum(a) + 1)
print f([2,3,3,5], 5) # 8
print f([1,2,3,4,4], 5) # 16
If sum of all coins is S, then the first person can get x..S-x of money.
Make array A of length S-x+1 and fill it with numbers of variants of changing A[i] with given coins (like kind of Coin Change problem).
To provide uniqueness (don't count C1+C2 and C2+C1 as two variants), fill array in reverse direction
A[0] = 1
for C in Coins:
for i = S-x downto C:
if A[i - C] > 0:
A[i] = A[i] + A[i - C]
//we can compose value i as i-C and C
then sum A entries in range x..S-x
Example for coins 2, 3, 3, 5 and x=5.
S = 13, S-x = 8
Array state after using coins in order:
0 1 2 3 4 5 6 7 8 //idx
1 1
1 1 1 1
1 1 2 2 1 1
1 1 2 3 1 1 3
So there are 8 variants to distribute these coins. Quick check (3' denotes the second coin 3):
2 3 3' 5
2 3' 3 5
2 3 3' 5
2 5 3 3'
3 3' 2 5
3 5 2 3'
3' 5 2 3
5 2 3 3'
You can also solve it in O(A * x^2) time and memory adding memoization to this dp:
solve(A, pos, sum1, sum2):
if (pos == A.length) return sum1 == x && sum2 == x
return solve(A, pos + 1, min(sum1 + A[pos], x), sum2) +
solve(A, pos + 1, sum1, min(sum2 + A[pos], x))
print(solve(A, 0, 0, 0))
So depending if x^2 < sum or not you could use this or the answer provided by #Mbo (in terms of time complexity). If you care more about space, this is better only when A * x^2 < sum - x

Last digit of a large number (Ruby) how to deal with NaN?

Here's my code:
def last_digit(n1, n2)
array = (n1.to_i ** n2.to_i).to_s.split("")
array[-1].to_i
end
TEST: The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6
I'm trying to return the last digit of a last number and I'm sure this correct but when I run tests 2 return as failing.
I think it's due to the numbers being too large, how do I get this code to remain accurate no matter how large it gets.
And also how do I deal with NaN, I've searched and struggled to find anything useful.
Thanks for your help.
There's an effective algorithm which assumes that only the last digit of a number being powered matters. Please, try it out on your tests and feel free to correct any flaw in this implementation that you'll find by running them
def digit_of_power(digit, n)
digit = digit % 10
case digit
when 0, 1, 5, 6 then digit
else
digit_of_square = digit * digit
if n.even?
digit_of_power(digit_of_square, n / 2)
else
digit * digit_of_power(digit_of_square, (n - 1) / 2) % 10
end
end
end
This is my solution
def last_digit(n1, n2)
return 1 if n2 == 0
return 0 if n1 == 0
exp = (n2 % 4 == 0) ? 4 : n2 % 4
return (n1**exp) % 10
end
You might want to read this article (finding the last digit of a power) for a more detailed explanation of the solution to this math problem.
Take a look at the following table:
You can see that the maximum length for cycle repetition is 4.
For instance:
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
16 * 2 = 32
32 * 2 = 64
64 * 2 = 128
128 * 2 = 256
256 * 2 = 512
The last digit in 32 is 2 ( as it is in 512), meaning that after multiplying the digit by 4, it will repeat itself.
The algorithm follows this logic:
You reduce the exponent, knowing that if it is divisible by 4, its new value is 4 because multiplying it 4 times gives you the last digit according to the table above. Otherwise, its value is n2 % 4.
As a final step you do this n1^exp % 10 because you only need the last number.
Note:
I tested it successfully with large numbers.
n1 = 38710248912497124917933333333284108412048102948908149081409204712406
n2 = 226628148126342643123641923461846128214626
By the way, I realize I am late in responding to your question. I just think it might be helpful for someone else someday.
Code
ENDINGS = [[0,0,0,0], [1,1,1,1], [2,4,8,6], [3,9,7,1], [4,6,4,6],
[5,5,5,5], [6,6,6,6], [7,9,3,1], [8,4,2,6], [9,1,9,1]]
def last_digit_of_power(digit, power)
return 1 if power.zero?
ENDINGS[digit][(power-1) % 4]
end
Examples
Let's try it for power equal to 5 and then 6.
(5..6).each do |power|
puts "\npow = #{power}"
(0..9).each {|digit| puts "#{digit}: #{last_digit_of_power(digit, power)}"}
end
pow = 5
0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
pow = 6
0: 0
1: 1
2: 4
3: 9
4: 6
5: 5
6: 6
7: 9
8: 4
9: 1
Explanation
This uses the same algorithm as employed by #Igor, but I've implemented it differently. It is known (and can be easily demonstrated) that the last digit of each digit 0-9 taken to increasing powers cycles among at most 4 digits. Consider the digit 3, for example. Since
[1,2,3,4,5].map { |power| 3**power }
#=> [3, 9, 27, 81, 243]
the last digits of 3 taken to each of those 5 powers is [3, 9, 7, 1, 3]. Since the last digit of 3**5 is the same as the last digit of 3**1, we infer than the last digit of 3**6 will be the same as the last digit of 3**(6-4) (3**2), which is 9, and so on.
Now suppose we wished to calculate the last digit of 3**15. We see that it will be the same as the last digit of 3**(15-4) (3**11), which in turn will equal the last digit of 3**7 and then the last digit 3**3, but we already know the last of these, which is 7. It follows that the last digit of 3**power is
[3, 9, 7, 1][(power-1) % 4]
ENDINGS provides the last digits for powers 1-4 for each of the digits 0-9. Note the cycle length is 1 for 0, 1, 5 and 6, is 2 for 4 and 9 and is 4 for 2, 3, 7 and 8. It's most convenient, however, to use a cycle length of 4 for all 10 digits.
ENDINGS[digit] equals the four endings of digit taken to the powers of 1, 2, 3 and 4. The last digit of the digit digit taken to the power power therefore equals
ENDINGS[digit][(power-1) % 4]

algorithmic puzzle for calculating the number of combinations of numbers sum to a fixed result

This is a puzzle i think of since last night. I have come up with a solution but it's not efficient so I want to see if there is better idea.
The puzzle is this:
given positive integers N and T, you will need to have:
for i in [1, T], A[i] from { -1, 0, 1 }, such that SUM(A) == N
additionally, the prefix sum of A shall be [0, N], while when the prefix sum PSUM[A, t] == N, it's necessary to have for i in [t + 1, T], A[i] == 0
here prefix sum PSUM is defined to be: PSUM[A, t] = SUM(A[i] for i in [1, t])
the puzzle asks how many such A's exist given fixed N and T
for example, when N = 2, T = 4, following As work:
1 1 0 0
1 -1 1 1
0 1 1 0
but following don't:
-1 1 1 1 # prefix sum -1
1 1 -1 1 # non-0 following a prefix sum == N
1 1 1 -1 # prefix sum > N
following python code can verify such rule, when given N as expect and an instance of A as seq(some people may feel easier reading code than reading literal description):
def verify(expect, seq):
s = 0
for j, i in enumerate(seq):
s += i
if s < 0:
return False
if s == expect:
break
else:
return s == expect
for k in range(j + 1, len(seq)):
if seq[k] != 0:
return False
return True
I have coded up my solution, but it's too slow. Following is mine:
I decompose the problem into two parts, a part without -1 in it(only {0, 1} and a part with -1.
so if SOLVE(N, T) is the correct answer, I define a function SOLVE'(N, T, B), where a positive B allows me to extend prefix sum to be in the interval of [-B, N] instead of [0, N]
so in fact SOLVE(N, T) == SOLVE'(N, T, 0).
so I soon realized the solution is actually:
have the prefix of A to be some valid {0, 1} combination with positive length l, and with o 1s in it
at position l + 1, I start to add 1 or more -1s and use B to track the number. the maximum will be B + o or depend on the number of slots remaining in A, whichever is less.
recursively call SOLVE'(N, T, B)
in the previous N = 2, T = 4 example, in one of the search case, I will do:
let the prefix of A be [1], then we have A = [1, -, -, -].
start add -1. here i will add only one: A = [1, -1, -, -].
recursive call SOLVE', here i will call SOLVE'(2, 2, 0) to solve the last two spots. here it will return [1, 1] only. then one of the combinations yields [1, -1, 1, 1].
but this algorithm is too slow.
I am wondering how can I optimize it or any different way to look at this problem that can boost the performance up?(I will just need the idea, not impl)
EDIT:
some sample will be:
T N RESOLVE(N, T)
3 2 3
4 2 7
5 2 15
6 2 31
7 2 63
8 2 127
9 2 255
10 2 511
11 2 1023
12 2 2047
13 2 4095
3 3 1
4 3 4
5 3 12
6 3 32
7 3 81
8 3 200
9 3 488
10 3 1184
11 3 2865
12 3 6924
13 3 16724
4 4 1
5 4 5
6 4 18
an exponential time solution will be following in general(in python):
import itertools
choices = [-1, 0, 1]
print len([l for l in itertools.product(*([choices] * t)) if verify(n, l)])
An observation: assuming that n is at least 1, every solution to your stated problem ends in something of the form [1, 0, ..., 0]: i.e., a single 1 followed by zero or more 0s. The portion of the solution prior to that point is a walk that lies entirely in [0, n-1], starts at 0, ends at n-1, and takes fewer than t steps.
Therefore you can reduce your original problem to a slightly simpler one, namely that of determining how many t-step walks there are in [0, n] that start at 0 and end at n (where each step can be 0, +1 or -1, as before).
The following code solves the simpler problem. It uses the lru_cache decorator to cache intermediate results; this is in the standard library in Python 3, or there's a recipe you can download for Python 2.
from functools import lru_cache
#lru_cache()
def walks(k, n, t):
"""
Return the number of length-t walks in [0, n]
that start at 0 and end at k. Each step
in the walk adds -1, 0 or 1 to the current total.
Inputs should satisfy 0 <= k <= n and 0 <= t.
"""
if t == 0:
# If no steps allowed, we can only get to 0,
# and then only in one way.
return k == 0
else:
# Count the walks ending in 0.
total = walks(k, n, t-1)
if 0 < k:
# ... plus the walks ending in 1.
total += walks(k-1, n, t-1)
if k < n:
# ... plus the walks ending in -1.
total += walks(k+1, n, t-1)
return total
Now we can use this function to solve your problem.
def solve(n, t):
"""
Find number of solutions to the original problem.
"""
# All solutions stick at n once they get there.
# Therefore it's enough to find all walks
# that lie in [0, n-1] and take us to n-1 in
# fewer than t steps.
return sum(walks(n-1, n-1, i) for i in range(t))
Result and timings on my machine for solve(10, 100):
In [1]: solve(10, 100)
Out[1]: 250639233987229485923025924628548154758061157
In [2]: %timeit solve(10, 100)
1000 loops, best of 3: 964 µs per loop

Arithmetic operation on sequence on integers

I have N integers numbers: 1,2,3...N
The task is to use +,-,*,/ to make expression 0.
For example -1*2+3+4-5=0
How can I do it?
May be some code on C/C++ ?
If N % 4 == 0, for every four consecutive integers a, b, c, d, take a - b - c + d
If N % 4 == 1, use 1 * 2 to start, then proceed as before. (i.e., 1*2 - 3 - 4 + 5 + 6 - 8 - 8 + 9 ...)
If N % 4 == 2, start with 1 - 2 + 3 * 4 - 5 - 6, then proceed as in the N % 4 == 0 example.
If N % 4 == 3, start with 1 + 2 - 3, then proceed as in the N%4 == 0 example.
All of these find a way to get zero out of the first few integers, leaving a multiple of four integers to work on, then take advantage of the fact that the pattern a - b - c + d = 0 for any four consecutive integers.
This is essentially SAT, or do you know that the numbers are a sequence (e.g. 2 1 8 is forbidden). What about negative numbers?
If the sequence is not too large, i would recommend to simply bootforce it. A greedy solution would be to reduce the problem by finding subsets which can be evaluated to zero.

Resources