Procedure which returns several rows conditionally - oracle

I have a procedure which will return a number as out parameter(let's call it out_parameter_result).
According to this number I need to add rows conditionally.
Pseudocode example(don't mind about conditions):
if(bitand(out_parameter_result, 1) = 1)
result.add(select 1 from dual)
if(bitand(out_parameter_result, 2) = 2)
result.add(select 2 from dual)
if(bitand(out_parameter_result, 4) = 4)
result.add(select 4 from dual)
return cursor(or resultset) which will contain 1,2,4.

Different from original, but works fine in my case.
SELECT * FROM TABLE WHERE id IN (
DECODE(bitand(v_info, 1), 1, 0, 1),
DECODE(bitand(v_info, 2), 2, 0, 2),
DECODE(bitand(v_info, 4), 4, 0, 3)

Related

Cartesian product but remove duplicates up to cyclic permutations

Given two integers n and r, I want to generate all possible combinations with the following rules:
There are n distinct numbers to choose from, 1, 2, ..., n;
Each combination should have r elements;
A combination may contain more than one of an element, for instance (1,2,2) is valid;
Order matters, i.e. (1,2,3) and (1,3,2) are considered distinct;
However, two combinations are considered equivalent if one is a cyclic permutation of the other; for instance, (1,2,3) and (2,3,1) are considered duplicates.
Examples:
n=3, r=2
11 distinct combinations
(1,1,1), (1,1,2), (1,1,3), (1,2,2), (1,2,3), (1,3,2), (1,3,3), (2,2,2), (2,2,3), (2,3,3) and (3,3,3)
n=2, r=4
6 distinct combinations
(1,1,1,1), (1,1,1,2), (1,1,2,2), (1,2,1,2), (1,2,2,2), (2,2,2,2)
What is the algorithm for it? And how to implement it in c++?
Thank you in advance for advice.
Here is a naive solution in python:
Generate all combinations from the Cartesian product of {1, 2, ...,n} with itself r times;
Only keep one representative combination for each equivalency class; drop all other combinations that are equivalent to this representative combination.
This means we must have some way to compare combinations, and for instance, only keep the smallest combination of every equivalency class.
from itertools import product
def is_representative(comb):
return all(comb[i:] + comb[:i] >= comb
for i in range(1, len(comb)))
def cartesian_product_up_to_cyclic_permutations(n, r):
return filter(is_representative,
product(range(n), repeat=r))
print(list(cartesian_product_up_to_cyclic_permutations(3, 3)))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1), (0, 1, 2), (0, 2, 1), (0, 2, 2), (1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]
print(list(cartesian_product_up_to_cyclic_permutations(2, 4)))
# [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]
You mentioned that you wanted to implement the algorithm in C++. The product function in the python code behaves just like a big for-loop that generates all the combinations in the Cartesian product. See this related question to implement Cartesian product in C++: Is it possible to execute n number of nested "loops(any)" where n is given?.

In clickhouse, how can I separate number by comma?

In clickhouse, how can I separate number by comma?
select toString(toDecimal64(roundBankers( 12321.121 , 1 ), 1 ))
and returns 12,321.1 instead of 12321.1, thanks.
Such formatting to strings from numbers is not implemented.
select formatReadableQuantity(roundBankers( 12321.121 , 1 ));
┌─formatReadableQuantity(roundBankers(12321.121, 1))─┐
│ 12.32 thousand │
└────────────────────────────────────────────────────┘
SELECT concat(toString(intDiv(roundBankers(12321.121, 1) AS x, 1000)), ',', toString(x % 1000)) AS r
┌─r─────────────────────┐
│ 12,321.10000000000036 │
└───────────────────────┘
For Integer data type, you can try
create function formatNumberReadable on cluster cluster_3S_2R as (number) -> reverse(if(number < 1000, reverse(toString(number)),
if(number between 1000 and 999999,
concat(substr(reverse(toString(number)), 1, 3), ',',
substr(reverse(toString(number)), 4, length(toString(number)))),
if(number between 1000000 and 999999999,
concat(substr(reverse(toString(number)), 1, 3), ',', substr(reverse(toString(number)), 4, 3),
',',
substr(reverse(toString(number)), 7, length(toString(number)))),
if(number between 1000000000 and 999999999999,
concat(substr(reverse(toString(number)), 1, 3), ',', substr(reverse(toString(number)), 4, 3),
',',
substr(reverse(toString(number)), 7, 3), ',',
substr(reverse(toString(number)), 10, 3)),
reverse(toString(number))
)
)
)
)
);
select formatNumberReadable(123456789);

Filling in Julia matrix with nested for loops

I have two arrays and an empty matrix, I need to perform a function such that the resulting matrix includes every combination of the two arrays.
Unfortunately I cannot run the arrays separately as they are both optional parameters for the function. I thought that the best way to do this was through nested loops but now I am unsure...
I've tried multiplying one of the matrices so that it includes the necessary duplicates, but I struggled with that as the real data is somewhat larger.
I've tried many versions of these nested loops.
a = [ 1 2 3 ]
b = [ 4 5 6 7 ]
ab = zeros(3,4)
for i = 1:length(a)
for j = 1:length(b)
ab[??] = function(x = a[??], y = b[??])
end
end
ab = [1x4 1x5 1x6 1x7, 2x4 2x5 2x6 2x7, 3x4 3x5 3x6 3x7]
Your problem can be solved by broadcasting:
julia> f(x, y) = (x,y) # trivial example
f (generic function with 1 method)
julia> f.([1 2 3]', [4 5 6 7])
3×4 Array{Tuple{Int64,Int64},2}:
(1, 4) (1, 5) (1, 6) (1, 7)
(2, 4) (2, 5) (2, 6) (2, 7)
(3, 4) (3, 5) (3, 6) (3, 7)
The prime in a' transposes a to make the shapes work out correctly.
But note that a = [ 1 2 3 ] constructs a 1×3 Array{Int64,2}, which is a matrix. For a vector (what you probably call "array"), use commas: a = [ 1, 2, 3 ] etc. If you have your data in that form, you have to transpose the other way round:
julia> f.([1,2,3], [4,5,6,7]')
3×4 Array{Tuple{Int64,Int64},2}:
(1, 4) (1, 5) (1, 6) (1, 7)
(2, 4) (2, 5) (2, 6) (2, 7)
(3, 4) (3, 5) (3, 6) (3, 7)
BTW, this is called an "outer product" (for f = *), or a generalization of it. And if f is an operator ∘, you can use dotted infix broadcasting: a' ∘. b.
Isn't that just
a'.*b
?
Oh, now I have to write some more characters to get past the minimum acceptable answer length but I don't really have anything to add, I hope the code is self-explanatory.
Also a list comprehension:
julia> a = [1,2,3];
julia> b = [4,5,6,7];
julia> ab = [(x,y) for x in a, y in b]
3×4 Array{Tuple{Int64,Int64},2}:
(1, 4) (1, 5) (1, 6) (1, 7)
(2, 4) (2, 5) (2, 6) (2, 7)
(3, 4) (3, 5) (3, 6) (3, 7)

Combinations sum depth first search solution

Given a list of positive integers and a target value, generate a solution set. For example, if the list is [10, 1, 2, 7, 6, 1, 5] and the target is 8, the solution set is...
[
[1, 7],
[1, 2, 5],
[2, 6]
[1, 1, 6]
[
I know there a multiple solutions to this, such as dp, but I am trying to get my dfs solution working and I believe I am very close, but I simply cannot get the correct result. If possible, I would like it if you didn't change my initial answer too much, if that's not possible, any solution will do.
def combinationSum(self, candidates, target):
candidates.sort()
total = []
self.helper(candidates, 0, target, [], total)
def helper(self, candidates, curr, target, temp, total):
if target == 0:
total.append(temp)
return
if target < 0:
return
for i in range(curr, len(candidates)):
# avoid duplicates
if i > curr and candidates[i] == candidates[i-1]:
continue
temp.append(candidates[i])
self.helper(candidates, i+1, target-candidates[i], temp, total)
# I'm not sure what to do here
This obviously does not give me the right result but I do think I am on the right track towards generating the solution set. I simply do not understand what I need to do after the recursive call to remove unnecessary elements.
I think this is along the lines of what you are trying to do:
def solve(target, sum, candidates, answer):
if sum == target:
print answer
return
if len(candidates) == 0 or sum > target:
return
first = candidates[0]
count = candidates.count(first);
answer.append(first)
solve(target, sum+first, candidates[1:], answer) #using the current number
answer.pop()
solve(target, sum, candidates[count:], answer) #skipping the current number and any duplicates
if __name__ == "__main__":
candidates = [10, 1, 2, 7, 6, 1, 5]
candidates.sort();
solve(8, 0, candidates, [])
The key point is that solve has two recursive calls.
The first recursive call uses the first number in the candidates list. So it
appends the first number to the answer
adds the first number to the sum
removes only the first number from the candidates list that is
passed to the next level
The second recursive call doesn't use the first number in the candidates list. And since it doesn't use the first number, it also doesn't use any duplicates of the first number. That's the reason for the count variable. candidates.count(first) is the number of entries in the list that are equal to first. So in the recursive call candidates[count:] removes the first element and any duplicates. (This assumes that the list is sorted, which should be done once before calling solve).
Here's one possible solution using recursion – I chose a tuple to represent the combinations, but you could've used list for those too
def combinationSum (l, target, sum = 0, comb = ()):
# base case: empty input [l]
if not l:
return []
# inductive case: [l] has at least one element
else:
# [x] is the first sub-problem
# [xs] is the rest of the sub-problems
x, *xs = l
# [x] plus [sum] is bigger than [target]
if x + sum > target:
return \
combinationSum (xs, target, sum, comb)
# [x] plus [sum] is smaller than [target]
elif x + sum < target:
return \
combinationSum (xs, target, sum + x, (x, *comb)) + \
combinationSum (xs, target, sum, comb)
# [x] plus [sum] is equal to [target]
else:
return \
[ (x, *comb) ] + \
combinationSum (xs, target, sum + x, (x, *comb)) + \
combinationSum (xs, target, sum, comb)
data = [10, 1, 2, 7, 6, 1, 5]
print (combinationSum (data, 8))
# [(5, 2, 1), (7, 1), (1, 6, 1), (6, 2), (5, 1, 2), (1, 7)]
If you want combinationSum to allow for duplicate values, you only have to change one part. Note, the program considers eg (5, 1, 1, 1) a solution 3 times because the 1 appears in 3 unique positions. If you only wanted (5, 1, 1, 1) to appear once, you'd have to consider a different approach.
...
elif x + sum < target:
return \
combinationSum (xs, target, sum + x, (x, *comb)) + \
combinationSum (l , target, sum + x, (x, *comb)) + \
combinationSum (xs, target, sum, comb)
...
print (combinationSum (data, 8))
# [ (1, 1, 1, 1, 1, 1, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (2, 1, 1, 1, 1, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (1, 2, 1, 1, 1, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (2, 2, 1, 1, 1, 1)
# , (1, 1, 2, 1, 1, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (1, 2, 2, 1, 1, 1)
# , (1, 1, 1, 2, 1, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (5, 1, 1, 1)
# , (2, 2, 2, 1, 1)
# , (1, 1, 2, 2, 1, 1)
# , (1, 1, 1, 1, 2, 1, 1)
# , (6, 1, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (5, 1, 1, 1)
# , (1, 2, 2, 2, 1)
# , (1, 1, 1, 2, 2, 1)
# , (1, 1, 1, 1, 1, 2, 1)
# , (5, 2, 1)
# , (7, 1)
# , (1, 6, 1)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (5, 1, 1, 1)
# , (2, 2, 2, 2)
# , (1, 1, 2, 2, 2)
# , (1, 1, 1, 1, 2, 2)
# , (6, 2)
# , (1, 1, 1, 1, 1, 1, 2)
# , (5, 1, 2)
# , (1, 7)
# , (1, 1, 6)
# , (1, 1, 1, 1, 1, 1, 1, 1)
# , (5, 1, 1, 1)]
# ]

Counting number of days, given a collection of day ranges?

Say I have the following ranges, in some list:
{ (1, 4), (6, 8), (2, 5), (1, 3) }
(1, 4) represents days 1, 2, 3, 4. (6, 8) represents days 6, 7, 8, and so on.
The goal is to find the total number of days that are listed in the collection of ranges -- for instance, in the above example, the answer would be 8, because days 1, 2, 3, 4, 6, 7, 8, and 5 are contained within the ranges.
This problem can be solved trivially by iterating through the days in each range and putting them in a HashSet, then returning the size of the HashSet. But is there any way to do it in O(n) time with respect to the number of range pairs? How about in O(n) time and with constant space? Thanks.
Sort the ranges in ascending order by their lower limits. You can probably do this in linear time since you're dealing with integers.
The rest is easy. Loop through the ranges once keeping track of numDays (initialized to zero) and largestDay (initialized to -INF). On reaching each interval (a, b):
if b > largestDay then
numDays <- numDays + b-max(a - 1, largestDay)
largestDay <- max(largestDay, b)
else nothing.
So, after sorting we have (1,4), (1,3), (2,5), (6,8)
(1,4): numDays <- 0 + (4 - max(1 - 1, -INF)) = 4, largestDay <- max(-INF, 4) = 4
(1,3): b < largestDay, so no change.
(2,5): numDays <- 4 + (5 - max(2 - 1, 4)) = 5, largestDay <- 5
(6,8): numDays <- 5 + (8 - max(6-1, 5)) = 8, largestDay <- 8
The complexity of the following algorithm is O(n log n) where n is the number of ranges.
Sort the ranges (a, b) lexicographically by increasing a then by decreasing b.
Before: { (1, 4), (6, 8), (2, 5), (1, 3) }
After: { (1, 4), (1, 3), (2, 5), (6, 8) }
Collapse the sorted sequence of ranges into a potentially-shorter sequence of ranges, repeatedly merging consecutive (a, b) and (c, d) into (a, max(b, d)) if b >= c.
Before: { (1, 4), (1, 3), (2, 5), (6, 8) }
{ (1, 4), (2, 5), (6, 8) }
After: { (1, 5), (6, 8) }
Map the sequence of ranges to their sizes.
Before: { (1, 5), (6, 8) }
After: { 5, 3 }
Sum the sizes to arrive at the total number of days.
8

Resources