Numbers between a and b without their permutations - c++

I've written a similar question which was closed I would like to ask not the code but an efficiency tip. I haven't coded but if I can't find any good hint in here I'll go and code straightforward. My question:
Suppose you have a function listNums that take a as lower bound and b as upper bound.
For example a=120 and b=400
I want to print numbers between these numbers with one rule. 120's permutations are 102,210,201 etc. Since I've got 120 I would like to skip printing 201 or 210.
Reason: The upper limit can go up to 1020 and reducing the permutations would help the running time.
Again just asking for efficiency tips.

I am not sure how you are handling 0s (eg: after outputting 1 do you skip 10, 100 etc since technically 1=01=001..).
The trick is to select a number such that all its digits are in increasing order (from left to right).
You can do it recursively. AT every recursion add a digit and make sure it is equal to or higher than the one you recently added.
EDIT: If the generated number is less than the lower limit then permute it in such a way that it is greater than or equal to the lower limit. If A1A2A3..Ak is your number and it is lower than limit), then incrementally check if any of A2A1A3...Ak, A3A1A2...Ak, ... , AkA1A2...Ak-1 are within limit. If need arises, repeat this step to with keeping Ak as first digit and finding a combination of A1A2..Ak-1.
Eg: Assume we are selecting 3 digits and lower limit is 99. If the combination is 012, then the lowest permutation that is higher than 99 is 102.

When the lower bound is 0, an answer is given by the set of numbers with non-decreasing digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 33, 34, 35, 36, 37, 38, 39, 44, 45, 46, 47, 48, 49, 55, 56, 57, 58, 59, 66, 67, 68, 69, 77, 78, 79, 88, 89, 99, 111, 112...) that fall in the requested range.
This sequence is easily formed by incrementing an integer, and when there is a carry, replicate the digit instead of carrying. Exemple: 73 is followed by 73+1 = 74 (no carry); 79 is followed by 79+1 = 80 (carry), so 88 instead; 22356999 is followed by 22356999+1 = 22357000, hence 22357777.
# Python code
A= 0 # CAUTION: this version only works for A == 0 !
B= 1000
N= A
while N < B:
# Detect zeroes at the end
S= str(N)
P= S.find('0')
if P > 0:
# Replicate the last nonzero digit
S= S[:P] + ((len(S) - P) * S[P-1])
N= eval(S)
# Next candidate
print N
N+= 1
Dealing with a nonzero lower bound is a lot more tricky.

Related

Controlling Mutation in 39bit string as a candidate solution in genetic algorithm

I am working on an optimization problem. I have X number of ambulance locations, where X ranges from 1-39.
There are 43 numbers [Ambulance Locations] to choose from (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39) , we choose 3 of them since I have 3 ambulances.
I can only put my ambulance in three locations among 1-39 locations (Restriction). Assume that I want to put my Ambulance on the 5th, 19th, and 31 positions. -- Chromosome 1= [000010000000000000100000000000100000000]. In the above presentation, I am turning on 5-bit, 19-bit, and 31-bit.
Is it possible to flip a bit close to the original solution? For example, keeping 2 bits on in the original position and randomly changing the 3rd bit close to 2bits. It is important for me to keep 3bits on among 39bits. I want to make a control mutation with the aim to produce a small change.
My goal is to make small changes since each bit represents a location. The purpose of mutation is to make small changes and see evaluate results. Therefore, a code should do something like this. As for CS1: (111000000000000000000000000000000000000), I want something like (011010000000000000000000000000000000000), or (011001000000000000000000000000000000000), or (010110000000000000000000000000000000000) or (101010000000000000000000000000000000000), or (00101100000000000000000000000000000000), etc
To achieve mutation, what can be a good way to randomly change present positions to other positions keeping the range only between 1-39 locations (Restriction)?
you could use numpy and do something like
import numpy
s = "1110000000000000000000000000"
def mutate(s):
arr = numpy.array(list(s))
mask = arr == "1"
indices_of_ones = numpy.argwhere(mask).flatten()
pick_one_1_index = numpy.random.choice(indices_of_ones)
potential_swaps = numpy.argwhere(~mask).flatten()
distances = numpy.abs(pick_one_1_index - potential_swaps)
probabilities = (1/distances) # higher probabilities the less distance from its original position
# probabilities = (1/(distances*2)) # even higher probabilities the less distance from its original position
pick_one_0_index = numpy.random.choice(potential_swaps,p=probabilities/probabilities.sum())
arr[pick_one_1_index] = '0'
arr[pick_one_0_index] = '1'
return "".join(arr)
there is likely a more optimal solution
alternatively you can add a scalar or power to the distances to penalize more for distance...
if you wanted to test different multipliers or powers for the probabilities
you could use something like
def score_solution(s1,s2):
ix1 = set([i for i,v in enumerate(s1) if v == "1"])
ix2 = set([i for i,v in enumerate(s2) if v == "1"])
a,b = ix1 ^ ix2
return numpy.abs(a-b)
def get_solution_score_quantiles(sample_size=100,quantiles = [0.25,0.5,0.75]):
scores = []
for i in range(10):
s1 = mutate(s)
scores.append(score_solution(s,s1))
return numpy.quantile(scores,quantiles)
print(get_solution_score_quantiles(50))

Lists and Indexing

Suppose I have a list of 17 objects, out of these 17 objects some have a certain property say P1. I separate them and say they are n in number where n < 17. Out of these n objects some have another property say P2. I separate them and say they are m in number where m < n. Out of these m objects some have another property say P3. I separate them and say they are k in number where k < m. I want to print these k objects only.
I was thinking of a long way that is I separate n, m and k objects all from 17 objects according to their respective property and then look for common index, the index that appear in all of three calculations.
Either I need to derive this common index or I do what I have written in the first paragraph that is to filter through and through according to the three properties.
Example:
list_1 = [17, 23, 15, 37, 43, 52, 57, 93, 55, 85, 11, 13, 7, 22, 24]
list_odd = [17, 23, 15, 37, 43, 57, 93, 55, 85, 11, 13, 7] #P1 is a number is odd
list_odd_div3 = [15, 57, 93] #P2 is a number divisible by 3
list_odd_div5 = [15, 55, 85] #P3 is a number divisible by 5
required_list = [15] #A number having P1, P2 and P3

Multiple if conditions with 'more than' and 'less than' values

How do we write these statements and their respective values below using the IF() conditions?
If 0 to equal or less than 8, $0.00
If 9 to equal or less than 18, $10.00
If 19 to equal or less than - 37, $20.00
If 38 to equal or less than - 51, $30.00
If equal to or more than 53, $60.00
I can't wrap my head around it after a couple of days of trials. Hope someone can clear this up for me.
#player0's answer is the answer I personally would use.
If you must use IF-conditions, then the following might be useful:
=IF(ISBETWEEN(A1;0;8);0;IF(ISBETWEEN(A1;9;18);10;IF(ISBETWEEN(A1;19;37);20;IF(ISBETWEEN(A1;38;52);30;IF(A1>=53;60;0)))))
use:
=VLOOKUP(A1, {0, 0; 9, 10; 19, 20; 38, 30; 53, 60}, 2, 1)
see: https://webapps.stackexchange.com/q/123729/186471

What is a regular expression for matching numbers divisible by 4?

I want to make a lexical analyzer that detects numbers divisible by 4.
Sample code -
%%
16(divisible by 4) {printf("divisible by 4 %s\n",yytext);}
%%
main()
{
yylex();
}
Divisibility by 4
The single-digit numbers which are divisible by 4 are 0, 4, and 8.
The two-digit numbers which are divisible by 4 can be divided into two groups:
12, 16, 32, 36, 52, 56, 72, 76, 92, 96
20, 24, 28, 40, 44, 48, 60, 64, 68, 80, 84, 88
Any number which is three or more digits and ends in any of these two-digit numbers is divisible by four.
Therefore, the regular expression should search for numbers of the form \d*[02468][048], or the form \d*[13579][26], or the single digit numbers 0, 4, and 8.
The Regex
This regular expression matches all numbers, positive or negative, which are divisible by 4:
-?(?:\d*[02468][048]|\d*[13579][26]|[048])
Note that this could match part of a number, such as 24 in 1245. If you want to make sure that you only match an entire number, you could add negative look-around expressions:
(?<!\d)-?(?:\d*[02468][048]|\d*[13579][26]|[048])(?!\d)
or you could use word boundaries:
\b-?(?:\d*[02468][048]|\d*[13579][26]|[048])\b
%%
[0-9]+ {int number = atoi(yytext); if((number % 4) == 0) printf("Div_4 %d\n", number);}
%%
main()
{
yylex();
}
As lex/flex support C, so you can save the string as integer and then check it in C.

Permuting on a schedule python

I'm trying to implement simplified DES for learning purposes in python, but I am having trouble figuring out how to do the permutations based on a "schedule." Essentially, I have a tuple with the appropriate permutations, and I need to bit shift to the correct location.
For example, using a key:
K = 00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001
Would move the 57st bit to the first bit spot, 49th bit to the second bit spot, etc...
K+ = 1111000 0110011 0010101 0101111 0101010 1011001 1001111 0001111
Current code:
def keyGen(key):
PC1table = (57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4)
keyBinary = bin(int(key, 16))[2:].zfill(64)
print keyBinary
permute(PC1table, keyBinary)
def permute(permutation, permuteInput):
elements = list(enumerate(permutation))
for bit in permuteInput:
***magic bitshifting goes here***
keyGen("133457799BBCDFF1")
The logic I thought would work was to enumerate the tuple of permutations, and for each bit of my old key, look in the enumeration to find the index corresponding the the bit, and bit shift the appropriate number of times, but I just can't figure out how to go about doing this. It may be that I am approaching the problem from the wrong angle, but any guidance would be greatly appreciated!
Ok, I ended up figuring a way to make this work, although this probably isn't the most efficient way...
prior to calling the function, turn the binary number into a list:
keyBinary = bin(int(key, 16))[2:].zfill(64)
keyBinary = [int(i) for i in keyBinary]
Kplus = permute(PC1table, keyBinary)
def permute(mapping, permuteInput):
permuteOutput = []
for i in range(len(mapping)):
permuteOutput.append(permuteInput[mapping[i % 56] - 1])
return permuteOutput
if anyone has a better way of tackling this, I'd love to see your solutions!