Number of Zeros after a non Zero number - qliksense

Guys I have a business case where I need to count the number of Zeros after a non Zero number in a column with transaction values in qliksense. For example,
1,000 = 3 10,000 = 4 10,500 = 2 11,510 = 1
23,415 = 0
I have tried various codes but nothing has worked so far.
Can anyone help?

Convert Value to Text,
Find position of last occurrence of 1-9 using FindOneOf,
Take part of the string after position using Mid (we need to add 1 to get after),
Check length of our 0 only string using Len
Here is the code:
Len(Mid(Text(Value), FindOneOf(Text(Value), '123456789', -1)+1))

One (dummy) way is to first find the last possition of any non-zero number in the string. Then to find the max possition of these and use the result to substring the main value and count the rest.
For example: if we have 11510
we'll find the last possition of each non-zero numer
Num LastPostion
1 4
2 0
3 0
4 0
5 3
6 0
7 0
8 0
9 0
Then we have to find the max value. In our case this is 4.
After that we'll use mid() and len() functions
mid(11510, 4 + 1) - this will return 0
and we'll get the length (len(mid(11510, 4 + 1))). This will result in 1
The result of the script below will be:
RawData:
Load * Inline [
Value
1000
10000
10500
11510
23415
];
join
Load
Value,
RangeMax(One, Two, Three, Four, Five, Six, Seven, Eight, Nine) as MaxNonZero
;
Load
Value,
Index(Value, '1', -1) as One,
Index(Value, '2', -1) as Two,
Index(Value, '3', -1) as Three,
Index(Value, '4', -1) as Four,
Index(Value, '5', -1) as Five,
Index(Value, '6', -1) as Six,
Index(Value, '7', -1) as Seven,
Index(Value, '8', -1) as Eight,
Index(Value, '9', -1) as Nine
Resident
RawData
;
NoConcatenate
Data:
Load
Value,
len(mid(Value, MaxNonZero + 1)) as NumberOfZeros
Resident
RawData
;
Drop Table RawData;

Related

How to round integer number using precision in flutter

I am trying to make the Y axis intervals of linechart dynamic in flutter. Here the MaxVal will get the maximum value of the Y axis.
int interval = (maxVal/6).toInt();
int length = interval.toString().length.toInt();
So here I have divided the maxVal with 6 so I will get the interval and I will find out the length. Next I need to round the interval according to the length. But I couldn't see any option to add precision for in flutter.
The Expected Output
If maxVal = 10000 then
interval will 1666
then length will 4. Then
I expected rounded value will be 2000
I'm assuming that you're asking to round a (non-negative) integer to its most significant base-10 digit. A general way to round non-negative integers is to add half of the unit you want to round to and to then truncate. For example, if you want to round a non-negative integer to the nearest 1000, you can add 1000/2 = 500, and then discard the hundreds, tens, and ones digits. An easy way to discard those digits is to perform an integer division by 1000 and then to multiply by 1000 again.
The trickiest part is determining what unit you want to round to since that's variable. If you want the most significant base-10 digit, you will need to determine the number of digits. In theory you can compute that with logarithms, but it's usually risky to depend on exact results with floating-point arithmetic, you'd have to deal with 0 as a special case, and it's harder to be confident of correctness. It's simpler and less error-prone to just find the length of the number's string representation. Once we find the number of digits, we can determine which unit to round to computing a corresponding power of 10.
import 'dart:math';
/// Rounds [n] to the nearest multiple of [multiple].
int roundToMultiple(int n, int multiple) {
assert(n >= 0);
assert(multiple > 0);
return (n + (multiple ~/ 2)) ~/ multiple * multiple;
}
/// Rounds [n] to its most significant digit.
int roundToMostSignificantDigit(int n) {
assert(n >= 0);
var numDigits = n.toString().length;
var magnitude = pow(10, numDigits - 1) as int;
return roundToMultiple(n, magnitude);
}
void main() {
var inputs = [
0,
1,
5,
9,
10,
11,
16,
19,
20,
21,
49,
50,
51,
99,
100,
469,
833,
1666,
];
for (var n in inputs) {
var rounded = roundToMostSignificantDigit(n);
print('$n => $rounded');
}
}
which prints:
0 => 0
1 => 1
5 => 5
9 => 9
10 => 10
11 => 10
16 => 20
19 => 20
20 => 20
21 => 20
49 => 50
50 => 50
51 => 50
99 => 100
100 => 100
469 => 500
833 => 800
1666 => 2000
(The above code should be tweakable to handle negative numbers too if desired, but first you would need to define whether negative numbers should be rounded toward 0 or toward negative infinity.)

Python: add zeroes in single digit numbers without using .zfill

Im currently using micropython and it does not have the .zfill method.
What Im trying to get is to get the YYMMDDhhmmss of the UTC.
The time that it gives me for example is
t = (2019, 10, 11, 3, 40, 8, 686538, None)
I'm able to access the ones that I need by using t[:6]. Now the problem is with the single digit numbers, the 3 and 8. I was able to get it to show 1910113408, but I need to get 19101034008 I would need to get the zeroes before those 2. I used
t = "".join(map(str,t))
t = t[2:]
So my idea was to iterate over t and then check if the number is less than 10. If it is. I will add zeroes in front of it, replacing the number . And this is what I came up with.
t = (2019, 1, 1, 2, 40, 0)
t = list(t)
for i in t:
if t[i] < 10:
t[i] = 0+t[i]
t[i] = t[i]
print(t)
However, this gives me IndexError: list index out of range
Please help, I'm pretty new to coding/python.
When you use
for i in t:
i is not index, each item.
>>> for i in t:
... print(i)
...
2019
10
11
3
40
8
686538
None
If you want to use index, do like following:
>>> for i, v in enumerate(t):
... print("{} is {}".format(i,v))
...
0 is 2019
1 is 10
2 is 11
3 is 3
4 is 40
5 is 8
6 is 686538
7 is None
another way to create '191011034008'
>>> t = (2019, 10, 11, 3, 40, 8, 686538, None)
>>> "".join(map(lambda x: "%02d" % x, t[:6]))
'20191011034008'
>>> "".join(map(lambda x: "%02d" % x, t[:6]))[2:]
'191011034008'
note that:
%02d add leading zero when argument is lower than 10 otherwise (greater or equal 10) use itself. So year is still 4digit string.
This lambda does not expect that argument is None.
I tested this code at https://micropython.org/unicorn/
edited :
str.format method version:
"".join(map(lambda x: "{:02d}".format(x), t[:6]))[2:]
or
"".join(map(lambda x: "{0:02d}".format(x), t[:6]))[2:]
second example's 0 is parameter index.
You can use parameter index if you want to specify it (ex: position mismatch between format-string and params, want to write same parameter multiple times...and so on) .
>>> print("arg 0: {0}, arg 2: {2}, arg 1: {1}, arg 0 again: {0}".format(1, 11, 111))
arg 0: 1, arg 2: 111, arg 1: 11, arg 0 again: 1
I'd recommend you to use Python's string formatting syntax.
>> t = (2019, 10, 11, 3, 40, 8, 686538, None)
>> r = ("%d%02d%02d%02d%02d%02d" % t[:-2])[2:]
>> print(r)
191011034008
Let's see what's going on here:
%d means "display a number"
%2d means "display a number, at least 2 digits"
%02d means "display a number, at least 2 digits, pad with zeroes"
so we're feeding all the relevant numbers, padding them as needed, and cut the "20" out of "2019".

PostGIS: intersections of set of collinear line segments, with counts

I have a set of collinear line segments (may be mutually disjoint, contained, or overlapping).
I want to make a new set of line segments where the segments are disjoint or touching (not overlapping), and each line segment has a count of the original line segments that cover it.
For example, suppose the original set is (drawn non-collinearly for illustration):
A----------------------B
C---------------------------D
E-----F
G-------------H
I-------J
the desired new set would be:
A-------C---E-----F-----B-----------D G-------------H-------J
1 2 3 2 1 1 1
(only the point coordinates matter, the new set does not share point objects with the old set)
How can I achieve this with PostGIS?
Related question: suppose I start with a table of line segments, not all collinear, how do I write the entire query that groups the collinear segments together and then applies the solution to my first question?
Thanks for any help!
Setup (for later queries):
create table lines (
id serial primary key,
label text not null,
line_data geometry(linestring) not null
);
insert into lines(label, line_data)
values ('A-B', ST_MakeLine(ST_MakePoint(-3, -6), ST_MakePoint( 1, 2))),
('D-C', ST_MakeLine(ST_MakePoint( 2, 4), ST_MakePoint(-2, -4))),
('E-F', ST_MakeLine(ST_MakePoint(-1, -2), ST_MakePoint( 0, 0))),
('G-H', ST_MakeLine(ST_MakePoint( 3, 6), ST_MakePoint( 4, 8))),
('I-J', ST_MakeLine(ST_MakePoint( 4, 8), ST_MakePoint( 5, 10))),
('P-L', ST_MakeLine(ST_MakePoint( 1, 0), ST_MakePoint( 2, 2))),
('X-Y', ST_MakeLine(ST_MakePoint( 2, 2), ST_MakePoint( 0, 4)));
Notes:
I purposely switched your D and C points to demonstrate a need for vector negation
The P-L line is parallel with your example lines (but not collinear)
The X-Y line has nothing to do with the others
the solutions below obviously won't work, when you have linestrings that have more than 2 points and those are not on the same line (so when a single linestring is not straight).
The ST_Union aggregate function can split your collinear linestrings. You'll just need to calculate how many lines are containing those.
However, grouping by collinearity is not that simple. I did not find any out-of-the-box solution for this, but you can calculate it (this will not calculate counts yet):
select string_agg(label, ','), ST_AsText(ST_Multi(ST_Union(line_data)))
from lines
group by (
select case
when ST_SRID(s) <> ST_SRID(e) then row(ST_SRID(s), s, null)
when ST_X(s) = ST_X(e) then row(ST_SRID(s), ST_SetSRID(ST_MakePoint(ST_X(s), 1.0), ST_SRID(s)), null)
when ST_Y(s) = ST_Y(e) then row(ST_SRID(s), ST_SetSRID(ST_MakePoint(1.0, ST_Y(e)), ST_SRID(s)), null)
else (
select row(
ST_SRID(s),
(select case
when ST_Y(rv) < 0
then ST_SetSRID(ST_MakePoint(-ST_X(rv), -ST_Y(rv)), ST_SRID(s))
else rv
end), -- normalized vector (negated when necessary, but same for all parallel lines)
(ST_X(e) * ST_Y(s) - ST_X(s) * ST_Y(e)) / (ST_X(e) - ST_X(s)) -- solution of the linear equaltion, where x=0
)
from coalesce(1.0 / nullif(ST_Distance(s, e), 0), 0) dmi, -- distance's multiplicative inverse
ST_TransScale(e, -ST_X(s), -ST_Y(s), dmi, dmi) rv -- raw vector (translated and scaled)
)
end
from ST_StartPoint(line_data) s,
ST_EndPoint(line_data) e
)
will produce:
X-Y | MULTILINESTRING((2 2,0 4))
P-L | MULTILINESTRING((1 0,2 2))
E-F,A-B,I-J,G-H,D-C | MULTILINESTRING((-3 -6,-2 -4),(-2 -4,-1 -2),(-1 -2,0 0),(0 0,1 2),(2 4,1 2),(3 6,4 8),(4 8,5 10))
To calculate counts, JOIN your original data again, where the splitted lines are contained by (ST_Contains) your original lines:
select ST_AsText(splitted_line), count(line_data)
from (select ST_Multi(ST_Union(line_data)) ml
from lines
group by (
select case
when ST_SRID(s) <> ST_SRID(e) then row(ST_SRID(s), s, null)
when ST_X(s) = ST_X(e) then row(ST_SRID(s), ST_SetSRID(ST_MakePoint(ST_X(s), 1.0), ST_SRID(s)), null)
when ST_Y(s) = ST_Y(e) then row(ST_SRID(s), ST_SetSRID(ST_MakePoint(1.0, ST_Y(e)), ST_SRID(s)), null)
else (
select row(
ST_SRID(s),
(select case
when ST_Y(rv) < 0
then ST_SetSRID(ST_MakePoint(-ST_X(rv), -ST_Y(rv)), ST_SRID(s))
else rv
end), -- normalized vector (negated when necessary, but same for all parallel lines)
(ST_X(e) * ST_Y(s) - ST_X(s) * ST_Y(e)) / (ST_X(e) - ST_X(s)) -- solution of the linear equaltion, where x=0
)
from coalesce(1.0 / nullif(ST_Distance(s, e), 0), 0) dmi, -- distance's multiplicative inverse
ST_TransScale(e, -ST_X(s), -ST_Y(s), dmi, dmi) rv -- raw vector (translated and scaled)
)
end
from ST_StartPoint(line_data) s,
ST_EndPoint(line_data) e)) al,
generate_series(1, ST_NumGeometries(ml)) i,
ST_GeometryN(ml, i) splitted_line
left join lines on ST_Contains(line_data, splitted_line)
group by splitted_line
will return:
LINESTRING(-3 -6,-2 -4) | 1
LINESTRING(-2 -4,-1 -2) | 2
LINESTRING(-1 -2,0 0) | 3
LINESTRING(0 0,1 2) | 2
LINESTRING(2 2,0 4) | 1
LINESTRING(1 0,2 2) | 1
LINESTRING(2 4,1 2) | 1
LINESTRING(3 6,4 8) | 1
LINESTRING(4 8,5 10) | 1

Matlab: convert cell of char to cell of vector of doubles

I would like to convert a <1 x 8 cell> of chars
'111001' '00' '111000' '01' '1111' '10' '11101' '110'
to a <1 x 8 cell> of <1 x (length bitcode)> doubles
[111001] [00] [111000] [01] [1111] [10] [11101] [110]
How can I do this?
here's a one liner solution:
a=num2cell(str2double(s))
s = {'111001', '00', '111000', '01', '1111', '10', '11101', '110'};
d = cellfun(#(c_) c_ - '0', s, 'UniformOutput', false);
'01234' - '0' will give 1 by 5 double matrix [0, 1, 2, 3, 4] because '01234' is actually char(['0', '1', '2', '3', '4']), and minus operation between characters will give the operation between their ASCII codes.
Try this:
s = {'111001','00','111000','01','1111','10','11101','110'}
num = str2num(str2mat(s));
Try using str2num to convert char arrays (strings) to numbers.
If you want to interpret the numbers as binary (base 2) numbers, try using bin2dec.

Facebook interview: find out the order that gives max sum by selecting boxes with number in a ring, when the two next to it is destroyed

Didn't find any similar question about this.
This is a final round Facebook question:
You are given a ring of boxes. Each box has a non-negative number on it, can be duplicate.
Write a function/algorithm that will tell you the order at which you select the boxes, that will give you the max sum.
The catch is, if you select a box, it is taken off the ring, and so are the two boxes next to it (to the right and the left of the one you selected).
so if I have a ring of
{10 3 8 12}
If I select 12, 8 and 10 will be destroyed and you are left with 3.
The max will be selecting 8 first then 10, or 10 first then 8.
I tried re-assign the boxes their value by take its own value and then subtracts the two next to is as the cost.
So the old ring is {10 3 8 12}
the new ring is {-5, -15, -7, -6}, and I will pick the highest.
However, this definitely doesn't work if you have { 10, 19, 10, 0}, you should take the two 10s, but the algorithm will take the 19 and 0.
Help please?
It is most likely dynamic programming, but I don't know how.
The ring can be any size.
Here's some python that solves the problem:
def sublist(i,l):
if i == 0:
return l[2:-1]
elif i == len(l)-1:
return l[1:-2]
else:
return l[0:i-1] + l[i+2:]
def val(l):
if len(l) <= 3:
return max(l)
else:
return max([v+val(m) for v,m in [(l[u],sublist(u,l)) for u in range(len(l))]])
def print_indices(l):
print("Total:",val(l))
while l:
vals = [v+val(m) for v,m in [(l[u],sublist(u,l)) for u in range(len(l)) if sublist(u,l)]]
if vals:
i = vals.index(max(vals))
else:
i = l.index(max(l))
print('choice:',l[i],'index:',i,'new list:',sublist(i,l))
l = sublist(i,l)
print_indices([10,3,8,12])
print_indices([10,19,10,0])
Output:
Total: 18
choice: 10 index: 0 new list: [8]
choice: 8 index: 0 new list: []
Total: 20
choice: 10 index: 0 new list: [10]
choice: 10 index: 0 new list: []
No doubt it could be optimized a bit. The key bit is val(), which calculates the total value of a given ring. The rest is just bookkeeping.