Find largest multiple for a number set - algorithm

An array of digits(0-9) of size N is provided as input. A set of numbers(N1,...,Nm) of size m with the numbers separated by space is also as the input. The program has to print the largest number that can be formed using the digits in the array of size N that is divisible by the numbers N1,..,Nm
Example Input/Output1:
INPUT:
160
2 3 5
OUTPUT
60
Explanation
60 is the largest number that can be formed using the digits 1,6,0 which is divisible by 2,3,5
Example Input/Output2:
Input
91028
17 5 9
Output
9180
Boundary Conditions
1<=m<=5
2<=N<=50
Can somebody explain how to approach this problem.

Partial answer:
Try all permutations of all subsets of your digits, probably starting with the largest candidates.
If your factors contain 5 the last digit must be 0or 5
If your factors contain 3 or 6 or 9 the sum of all candidate digits muts be a multiple of 3
If your factors contain 2 or 4 or 6 or 8 the last digit must be even.
And so on.

Related

Count integers up to n that contain the digits 2018 in order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Given an integer n between 0 and 10,0000,0000, count the number of integers smaller than n which contain the digits [2,0,1,8] in order.
So e.g. the number 9,230,414,587 should be counted, because removing the digits [9,3,4,4,5,7] leaves us with [2,0,1,8].
Example input and output:
n = 2018 -> count = 1
n = 20182018 -> count = 92237
My general thought is that: the maximum length of n is 10 and the worst situation is that we have to insert 6 digits into [2,0,1,8] and remove the duplicates and the numbers greater than n.
I don't see any own attempts to solve, so I'll give only clue:
You have 9-digits number (small numbers might be represented as 000002018) containing digit sequence 2,0,1,8.
Name them 'good' ones.
Let denote digit places from 1 to 9 right to left:
number 532705183
digits 5 3 2 7 0 5 1 8 3
index 9 8 7 6 5 4 3 2 1
The most left '2' digit can occupy places from 4 to 9. How many good numbers contain the first 2 at k-th place? Let make function F2(l, k) for quantity of good numbers where 2 refers to digit 2, l is number length, k is place for the most left digit.
. . . . 2 . . . .
^
|
left part k right part should contain 0 1 8 sequence
without 2's
F2(9, k) = 9^(9-k) * Sum(F0(k-1, j) for j=1..k-1)
Overall quantity of good numbers is sum of F2(9, k) for all possible k.
GoodCount = Sum(F2(9, k) for k=4..9)
Explanation:
There are 9-k places at the left. We can put any digit but 2 there, so there are 9^(9-k) possible left parts.
Now we can place 0 at the right part and count possible variants for 018 subsequences. F0(...) will of course depend on F1(...) and F1 will depend on F8(...) for shorter numbers.
So fill tables for values for F8, F0, F1 step-by-step and finally calculate result for digit 2.
Hand-made example for 4-digit numbers containing subsequence 1 8 and k = position of the first '1':
k=2: there are 81 numbers of kind xx18
k=3: there are numbers of kind x1x8 and x18x
there are 9 subnumbers like x8, 10 subnumbers 8x, so (10+9)*9=171
k=4: there are numbers of kind
1xx8 (9*9=81 such numbers),
1x8x (9*10=90 numbers),
18xx (100 numbers),
so 81+90+100=271
Overall: 81+171+271=523
This is actually a relatively small problem set. If the numbers were much bigger, I'd opt to use optimised techniques to just generate all numbers that meet your criteria (those containing the digits in that order) rather than generating all possible numbers and checking each to ensure it meets the criteria.
However, the brute force method does your 20182018 variant in about ten seconds and the full 1,000,000,000 range in a little under eight minutes.
So, unless you need it faster than that, you may find the brute-force method more than adequate:
import re
num = 1000000000 # or 20182018 or something else.
lookfor = re.compile("2.*0.*1.*8")
count = 0
for i in range(num + 1):
if lookfor.search(str(i)) is not None:
count += 1
#print(count, i) # For checking.
print(count)

Find the number of non-decreasing and non-increasing subsequences in an array

I am attempting to complete a programming challenge from Quora on HackerRank: https://www.hackerrank.com/contests/quora-haqathon/challenges/upvotes
I have designed a solution that works with some test cases, however, for many the algorithm that I am using is incorrect.
Rather than seeking a solution, I am simply asking for an explanation to how the subsequence is created and then I will implement a solution myself.
For example, with the input:
6 6
5 5 4 1 8 7
the correct output is -5, but I fail to see how -5 is the answer. The subsequence would be [5 5 4 1 8 7] and I cannot for the life of me find a means to get -5 as the output.
Problem Statement
At Quora, we have aggregate graphs that track the number of upvotes we get each day.
As we looked at patterns across windows of certain sizes, we thought about ways to track trends such as non-decreasing and non-increasing subranges as efficiently as possible.
For this problem, you are given N days of upvote count data, and a fixed window size K. For each window of K days, from left to right, find the number of non-decreasing subranges within the window minus the number of non-increasing subranges within the window.
A window of days is defined as contiguous range of days. Thus, there are exactly N−K+1 windows where this metric needs to be computed. A non-decreasing subrange is defined as a contiguous range of indices [a,b], a<b, where each element is at least as large as the previous element. A non-increasing subrange is similarly defined, except each element is at least as large as the next. There are up to K(K−1)/2 of these respective subranges within a window, so the metric is bounded by [−K(K−1)/2,K(K−1)/2].
Constraints
1≤N≤100,000 days
1≤K≤N days
Input Format
Line 1: Two integers, N and K
Line 2: N positive integers of upvote counts, each integer less than or equal to 10^9
Output Format
Line 1..: N−K+1 integers, one integer for each window's result on each line
Sample Input
5 3
1 2 3 1 1
Sample Output
3
0
-2
Explanation
For the first window of [1, 2, 3], there are 3 non-decreasing subranges and 0 non-increasing, so the answer is 3. For the second window of [2, 3, 1], there is 1 non-decreasing subrange and 1 non-increasing, so the answer is 0. For the third window of [3, 1, 1], there is 1 non-decreasing subrange and 3 non-increasing, so the answer is -2.
Given a window size of 6, and the sequence
5 5 4 1 8 7
the non-decreasing subsequences are
5 5
1 8
and the non-increasing subsequences are
5 5
5 4
4 1
8 7
5 5 4
5 4 1
5 5 4 1
So that's +2 for the non-decreasing subsequences and -7 for the non-increasing subsequences, giving -5 as the final answer.

Amount of "jumping" numbers from 101 to 10^60? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Let's say number is "ascending" if its digits are going in ascending order. Example: 1223469. Digits of "descending" number go in descending order. Example: 9844300. Numbers that are not "ascending" or "descending", are called "jumping". Numbers from 1 to 100 are not "jumping". How many "jumping" numbers are there from 101 to 10^60?
Here is an idea: instead of counting the jumping numbers, count the ascending and descending ones. Then subtract them from all the numbers.
Counting the ascending/descending ones should be easy - you can use a dynamic programming based on the number of digits left to generate, and the digit you have placed in the last position.
I'll describe how to count the ascending numbers, because that's easier. Going from that, you could also count the descending ones and then subtract the combined amount from the total amount of numbers, compensating for duplicates, as indicated by Ivan, or devise a more complex way to only count jumping numbers directly.
A different approach
Think about the numbers sorted by ending digit. We start with numbers that are 1 digit long, this will be our list
1 // Amount of numbers ending with 1
1 // Amount of numbers ending with 2
1 // Amount of numbers ending with 3
1 // Amount of numbers ending with 4
1 // Amount of numbers ending with 5
1 // Amount of numbers ending with 6
1 // Amount of numbers ending with 7
1 // Amount of numbers ending with 8
1 // Amount of numbers ending with 9
To construct numbers with two digits ending with 6, we can use all numbers ending with 6 or less
1 // Amount of numbers ending with 1 with 2 digits
2 // Amount of numbers ending with 2 with 2 digits
3 // Amount of numbers ending with 3 with 2 digits
4 // Amount of numbers ending with 4 with 2 digits
5 // Amount of numbers ending with 5 with 2 digits
6 // Amount of numbers ending with 6 with 2 digits
7 // Amount of numbers ending with 7 with 2 digits
8 // Amount of numbers ending with 8 with 2 digits
9 // Amount of numbers ending with 9 with 2 digits
Writing these side by side, can see how to calculate the new values very quickly:
y a // y, a, and x have been computed previously
x (a + x)
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
1 5 15 35
1 6 21 56
1 7 28 84
1 8 36 120
1 9 45 165
A simple Python program
Iterating over one such column, we can directly produce all values of the new column, if we always remember the last computation. The scan() function abstracts away exactly that behavior of taking one element, and do some computation with it and the last result.
def scan(f, state, it):
for x in it:
state = f(state, x)
yield state
Producing the next column is now as simple as:
new_column = list(scan(operator.add, 0, column))
To make it simple, we use single digit numbers as starting point:
first_row = [1]*9
Seeing that we always need to feed back the new row to the function, can use scan again to do just that:
def next_row(row):
return list(scan(operator.add, 0, column))
def next_row_wrapper(row, _):
return next_row(row)
>>> [list(x) for x in scan(next_row_wrapper, [1]*9, range(3))] # 3 iterations
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 6, 10, 15, 21, 28, 36, 45], [1, 4, 10, 20, 35, 56, 84, 120, 165]]
As you can see, this gives the first three row apart from the first one.
Since we want to know the sum, of all numbers, we can do just that. When we do 1 iteration, we get all ascending numbers until 10^2, so we need to do 59 iterations for all numbers until 10^60:
>>> sum(sum(x) for x in scan(lambda x, _: next_row(x), [1]*9, range(59))) + 10
56672074888L
For the descending numbers, it's quite similar:
>>> sum(sum(x) for x in scan(lambda x, _: next_row(x), [1]*10, range(59))) + 10 - 58
396704524157L<
Old approach
Think about how the numbers end:
From 10 to 99, we have two digits per number.
There are
1 that ends in 1
2 that end in 2
3 that end in 3
4 that end in 4
5 that end in 5
6 that end in 6
7 that end in 7
8 that end in 8
9 that end in 9
All of these numbers act as prefixes for numbers from 100 to 999.
An example, there are three numbers that end in 3:
13
23
33
For each of these three numbers, we can create seven ascending numbers:
133
134
135
136
137
138
139
It is easy to see, that this adds three numbers for each of the seven possible ending digits.
If we wanted to extend numbers ending on 4, the process would be similar: Currently, there are 4 numbers ending on 4. Thus, for each such number, we can create 6 new ascending numbers. That means, that there will be an additional 4 for all of the six possible ending digits.
If you have understood everything I've written here, it should be easy to generalize that and implement an algorithm to count all those numbers.
Non-jumping numbers:
69 choose 9 (ascending numbers of size ≤ 60)
+ 70 choose 10 - 60 (descending numbers of size ≤ 60)
- 60 * 9 (double count: all digits the same)
- 1 (double count: zero)
= 453376598563
(To get jumping numbers, subtract from total numbers: 1060)
Simple python program to compute the number:
# I know Python doesn't do tail call elimination, but it's a good habit.
def choose(n, k, num=1, denom=1):
return num/denom if k == 0 else choose(n-1, k-1, num*n, denom*k)
def f(digits, base=10):
return choose(digits+base-1, base-1) + choose(digits+base, base) - digits*base - 1
Ascending numbers: select 9 positions to increment the digit, starting with 0.
Descending numbers: pretend we have a digit 10 which is used to left-pad the number. Then select 10 positions to decrement the digit, starting with 10. Then remove all the choices where the 10 selected positions are consecutive and not at the end, which would correspond to digit sequences with a leading 0.
Since all numbers whose digits are all the same will be produced by both descending and ascending algorithms, we have to subtract them.
Note that all of these algorithms consider the number 0 to be written with no digits at all. Also, all numbers ≤ 100 are either ascending or descending (or both), so there's no need to worry about them.
Do you count 321 as descending or do you count 000000321 as jumping?
Hint for the answer: the number of ascending numbers with 59 digits will be something like (69 choose 10) because you have to choose which points in the number are between differing digits.

Confusion regarding genetic algorithms

My books(Artificial Intelligence A modern approach) says that Genetic algorithms begin with a set of k randomly generated states, called population. Each state is represented as a string over a finite alphabet- most commonly, a string of 0s and 1s. For eg, an 8-queens state must specify the positions of 8 queens, each in a column of 8 squares, and so requires 8 * log(2)8 = 24 bits. Alternatively the state could be represented as 8 digits, each in range from 1 to 8.
[ http://en.wikipedia.org/wiki/Eight_queens_puzzle ]
I don't understand the expression 8 * log(2)8 = 24 bits , why log2 ^ 8? And what are these 24 bits supposed to be for?
If we take first example on the wikipedia page, the solution can be encoded as [2,4,6,8,3,1,7,5] : the first digit gives the row number for the queen in column A, the second for the queen in column B and so on. Now instead of starting the row numbering at 1, we will start at 0. The solution is then encoded with [1,3,5,7,0,6,4]. Any position can be encoded such way.
We have only digits between 0 and 7, if we write them in binary 3 bit (=log2(8)) are enough :
000 -> 0
001 -> 1
...
110 -> 6
111 -> 7
A position can be encoded using 8 times 3 digits, e.g. from [1,3,5,7,2,0,6,4] we get [001,011,101,111,010,000,110,100] or more briefly 001011101111010000110100 : 24 bits.
In the other way, the bitstring 000010001011100101111110 decodes as 000.010.001.011.100.101.111.110 then [0,2,1,3,4,5,7,6] and gives [1,3,2,4,5,8,7] : queen in column A is on row 1, queen in column B is on row 3, etc.
The number of bits needed to store the possible squares (8 possibilities 0-7) is log(2)8. Note that 111 in binary is 7 in decimal. You have to specify the square for 8 columns, so you need 3 bits 8 times

Min number of operations

Given a positive integer N, we are allowed to apply any of the following operations as many times as we want in any order:
First Operation: Add 1 the Given positive integer N; If N is 7, after that operation N becomes 8. If N is 999, after that operation it becomes 1000.
Second operation: choose any occurrence of any digit and replace it by another digit. (475->479, 101 -> 111, 299 -> 199 and so on)
Third operation: add any non-zero digit to the left of the decimal representation of N: 47 -> 247, 9999 -> 49999, 2474 -> 72474 and so on).
Find the minimum number of operations that is needed for changing N to the lucky number.(Lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.)
EXAMPLES:
N=25, answer=2
N=46, answer=1
N=99, answer=2
I found this problem while I was trying various problems on LUCKY NUMBER..
I am stuck at this problem...
Please help..
The "add 1 to the number" and "add any non-zero leading digit to the number" are red herrings.
The minimum number of operations is one per digit in N which is non-lucky. You just change each of the non-4, non-7 digits to either 4 or 7.
Adding a leading digit will never help you because there's no need to make the number longer. Adding 1 seems like it could help, but it will only do two things: either it does not carry (when you add to a digit less than 9), in which case a straight replacement can do the same thing, or it carries (when you add to a 9), in which case it's just created one or more non-lucky zeros you're now going to have to "fix" with digit replacement.
Given the rules, apparently, the answer is the number of digits minus the number of 4 or 7 occurrences. So for example, N=25 you replace each digit with either 4 or 7 taking only one at a time. for 46, you take 6 and replace it with 4 or 7 thus the answer 1.
You can try continuous modulo 10 evaluation to check if the digits are 4 or 7
$x = the number
$y = 0; #number of non 4 or 7
while($x>0){
if($x % 10 != 4 && $x % 10 != 7){
$y++;
}
if($x % 10 == 0){
$y +=4;
}
$x = floor($x/10);
}
Apparently 0 is not replaceable doing some edits
only second case is important. just take a string and count how many digits are not equal to 4 and 7
Just consider the second operation.........and find the number of digits different from 4 and 7....and thats the answer.....isn't it....:)
You can try a greedy solution:
Check all digits in the number and count how many are not 4 or 7
Take the count from the above operation, and see if there's a small count when adding only 1 to the number will get you to Lucky one.
Take the min from both - that's the solution
What's the point in adding leading digits to N ? This will not get you an optimal solution.

Resources