Have a question about backtracking for parsing string - depth-first-search

Given a string of numbers, you need to parse this string and then use + or - between numbers. If the result of calculation is equal to 100, add this combo to result.
Example input:
"991"
Example output:
["9+91", "99+1"]
Please let me know if you have thought on this. Python is preferred. Thanks

Let's say you have n digits, then a brute-force solution would be to try and put one of three possible cases between each two digits, the possibilities are ('+','-',''(nothing)), the time complexity of this solution is 3^(d-1), where d is the number of digits in the input string.

Related

Algorithm for assigning numerics to a string?

I'd like to design a dictionary which stores a value for a string, such that when two strings are compared, the two corresponding values can be used to determine which string comes first in a dictionary.
For example, the value for "a" should be less than the value for "ab". The value for "z" should be greater than the value for "az". And so on.
I tried googling for this but I wasn't able to find it :( Is there a good way to implement this? I see it is very similar to a decimal system but in base 26. (For example aaa would be like 111, and aaz would be like 11(26).) But that wouldn't work for the case that "z" > "az", since that would be saying (26) > 1(26).
One solution I came up with was to take the length of the largest word (let's say m), and then assign a value by doing 26^m + 26^(m-1) and so on for each letter. However this requires knowing the length of the largest word. Are there any such algorithms that do not require this?
This is not possible with only natural numbers/integers because between any two strings there are an infinite number of others (ex. "asdf" < "asdfa" < "asdfaa" < ... < "asdg"), but between any two integers there is only a finite number of integers.
However, as suggested in the comments, if you can use real numbers, you can map a string to char1 + char2/27 + char3/27^2+.... However, for long strings, this will hit the max floating point precision and stop working correctly.

Check if string includes part of Fibonacci Sequence

Which way should I follow to create an algorithm to find out whether fibonacci sequence exists in a given string ?
The string includes only digits with no whitespaces and there may be more than one sequence, I need to find all of them.
If as your comment says the first number must have less than 6 digits, you can simply search for all positions there one of the 25 fibonacci numbers (there are only 25 with less than 6 digits) and than try to expand this 1 number sequence in both directions.
After your update:
You can even speed things up when you are only looking for sequences of at least 3 numbers.
Prebuild all 25 3-number-Strings that start with one of the 25 first fibonnaci-numbers this should give much less matches than the search for the single fibonacci-numbers I suggested above.
Than search for them (like described above and try to expand the found 3-number-sequences).
here's how I would approach this.
The main algorithm could search for triplets then try to extend them to as long a sequence as possible.
This leaves us with the subproblem of finding triplets. So if you are scanning through a string to look for fibonacci numbers, one thing you can take advantage of is that the next number must have the same number of digits or one more digit.
e.g. if you have the string "987159725844" and are considering "[987]159725844" then the next thing you need to look at is "987[159]725844" and "987[1597]25844". Then the next part you would find is "[2584]4" or "[25844]".
Once you have the 3 numbers you can check if they form an arithmetic progression with C - B == B - A. If they do you can now check if they are from the fibonacci sequence by seeing if the ratio is roughly 1.6 and then running the fibonacci iteration backwards down to the initial conditions 1,1.
The overall algorithm would then work by scanning through looking for all triples starting with width 1, then width 2, width 3 up to 6.
I'd say you should first find all interesting Fibonacci items (which, having 6 or less digits, are no more than 30) and store them into an array.
Then, loop every position in your input string, and try to find upon there the longest possible Fibonacci number (that is, you must browse the array backwards).
If some Fib number is found, then you must bifurcate to a secondary algorithm, consisting of merely going through the array from current position to the end, trying to match every item in the following substring. When the matching ends, you must get back to the main algorithm to keep searching in the input string from the current position.
None of these two algorithms is recursive, nor too expensive.
update
Ok. If no tables are allowed, you could still use this approach replacing in the first loop the way to get the bext Fibo number: Instead of indexing, apply your formula.

Find number of substrings in binary string having equal 1's and 0's

I came across the following question,
Find the total number of substrings in a string which contain equal number of 1's and 0's. Also the substring should have consecutive 0's followed by consecutive 1's or vice versa.
For example,
1010 - 10,01,10
1100110- 1100,10,0011,01,10.
My initial idea was to use a n^2 loop to find all substrings and then check if the condition is satisfied. Obviously there must be a better solution to this as I could not pass all cases.
Please suggest ideas to improve on this. Thanks.
I’d suggest the following - iterating over you sequence for each consecutive sequence of 0’s or 1’s of length L(k) (except for the first one) add to the counter min(L(k), L(k-1)). The final value of the counter will be the number you’re looking for.
For your example 1100110
L = (2, 2, 2, 1)
And the sum is 2+2+1=5

Convert string to perfect number

Given a string, we need to find the largest square which can be obtained by replace its characters by digits (leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits. If no solution, return -1.
Consider the string "ab" If we replace character a with 8 and b with 1, we get 81, which is a square.
How to find it for given string ? It is given that string length can be at max 11.
Please help me find a suitable and efficient way
Sorry can't comment, not enough reputation for it so I'll answer here.
#mat7 about what you said in your question comments, no you don't have to do it for every letter from a to z. You only have to do it for the letters present in your string (so at max 12 letters, not 26).
The first thing I would even check is how much different letter you have, if it's 11 or 12 different letters you can directly return -1 since you can't have different letters having the same number.
Now, supposing the input string being "fdsadrtas", you take a new array with only each different letter => "fdsadrt"
And with this array you try all possibilities (exclude the obvious mismatching options, if you set 'f' to 4 and 'd' to 5, 's' can only be 12367890 (and f can never be 0)), this way you will exclude lots of possibilities, having as worst case 10! instead of 12^10. (actually 9*9! with the test of the first one never beeing 0 but it's close enough)
EDIT 2 : +1 samgak nice idea !
The last digit can only be 0,1,4,5,6,9 so the worst number of tests drop even to 9*6*8!
10! is by far small enough to be brute tested, keep the higher square value you found and you are done.
EDIT :
Actually It would work (in a finite reasonable amount of time) but it is the wrong approach now that I have thought about it.
You will use less time in looking all the squares numbers that could be a solution for your string, using the exemple I gave above it's a string of length 9, and checking each square who is length 9 if he could be successfully mapped into the string.
For a string of length 12 (the worst case) you will have to check the square values of 316'228 to 999'999, who is way less than the >2 millions check of the previous proposition. The other proposition might become faster if you start accepting long strings but with only 12 you are faster this way.

Sorting a list of variable length integers delimited by decimal points

I'm in need of some help.
I have a list of delimited integer values that I need to sort. An example:
Typical (alpha?) sort:
1.1.32.22
11.2.4
2.1.3.4
2.11.23.1.2
2.3.7
3.12.3.5
Correct (numerical) sort:
1.1.32.22
2.1.3.4
2.3.7
2.11.23.1.2
3.12.3.5
11.2.4
I'm having trouble figuring out how to setup the algorithm to do such a sort with n number of decimal delimiters and m number of integer fields.
Any ideas? This has to have been done before. Let me know if you need more information.
Thanks a bunch!
-Daniel
All you really need to do is to write "compare()" and then you can plug that into any sort algorithm.
To write compare, compare each field from left to right, and if any field is higher, return that that argument is higher. If one argument is shorter, assume that remaining fields are 0.
Check out radix sort.
versionsort does exactly what you're looking for.
The comparison algorithm is strverscmp, here's a description of it from the man page:
What this function does is the
following. If both strings are equal,
return 0. Otherwise find the position
between two bytes with the property
that before it both strings are equal,
while directly after it there is a
difference. Find the largest
consecutive digit strings containing
(or starting at, or ending at) this
position. If one or both of these is
empty, then return what strcmp() would
have returned (numerical ordering of
byte values). Otherwise, compare both
digit strings numerically, where digit
strings with one or more leading
zeroes are interpreted as if they have
a decimal point in front (so that in
particular digit strings with more
leading zeroes come before digit
strings with fewer leading zeroes).
Thus, the ordering is 000, 00, 01,
010, 09, 0, 1, 9, 10.
It is called natural sort. See Natural Sorting algorithm.
For example, Darius Bacon's answer in Python:
def sorted_nicely(strings):
"Sort strings the way humans are said to expect."
return sorted(strings, key=natural_sort_key)
def natural_sort_key(key):
import re
return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]
General solution is to convert this string into array of bytes, then use qsort and specify comparison function.

Resources