you are given a string consisting of only 1's. eg: "11111111"
you have an iterator that changes direction when it hits the extremes of the string. starting in the direction left to right.
the iterator replaces the next immediate '1' in its path with a zero and then skips to the '1' following that. This goes on until there is only one '1' remaining in the string.
you have to print the location of that '1'.
here is a python 3 code with the naive solution (it also prints the steps for understanding the problem, although steps are not required for the expected answer):
n=int(input("enter the number of people in the row : "))
assert(n>=1)
input_string="1"*n
print(input_string)
direction=1
iterator=0
count=0
while(count!=1):
count=0
next_to_delete=-1
while(iterator<len(input_string) and iterator>=0):
if(input_string[iterator]=='1'):
if(next_to_delete==-1):
next_to_delete=iterator
else:
input_string=input_string[:iterator]+"0"+input_string[iterator+1:]
#i.e. input_string[iterator]='0'
next_to_delete=-1
count+=1
iterator+=direction
print(input_string)
direction=1 if direction==-1 else -1
iterator+=direction
print("answer is : ",end='')
print(next_to_delete+1)
example:
if n=4::::::::::
1111
1010
0010
answer is : 3
if n=5::::::::::
11111
10101
10001
10000
answer is : 1
Here is a log(n) solution:
def survivor_number(n):
if n % 2 == 0:
n -= 1
b = 2
t = 1
while b <= n:
t += b & n
b *= 4
return t
This is based on the algorithm in OEIS for sequence A090569
We are required to compute the bit wise AND amongst all natural numbers lying between A and B, both inclusive.I came across this problem on a website and here is the approach they used but i couldn't understand the method.Can anyone explain this more clearly with an example ?
In order to solve this problem, we just need to focus on the occurrences of each power 2, which turn out to be cyclic. Now for each 2^i(the length of the cycle will be 2^(i+1) having 2^i zeros followed by same number of ones) we just need to compute if 1 remains constant in the given interval, which is done by simple arithmetic. If so, that power of 2 will be present in the answer, otherwise it won't.
Let's count (unsigned) with 3 bits to visualize some numbers first:
000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7
If you look at the columns, you can see that the lowest bit is alternating with a cycle of 1, the next with a cycle of 2, then 4, and the nth lowest bit is alternating with a cycle of 2^(n-1).
As soon as a bit was 0 once it is always 0 (because 0 and whatever is 0).
You could also say the nth bit is only 1 if the nth bit of A and B is 1 and d < 2^(n-1). In other words a bit will only be 1 if it is 1 at the beginning and the end and didn't had time to change to 0 in between because its cycle is too large.
let's say I have the following implementation of a list:
list=^listelement
listelement=record
w:integer;
next:list;
end;
and a list represents a large number written decimally
(a list 1 -> 2 -> 3 represents the number 123).
What I want to do is to transform such a number into binary representation. So, the eastiest way to do this required dividing a number by 2
The problem is I'm having a hard time implementing the division by 2 algorithm. I understand the basic algorithms such as this one
https://www.mathsisfun.com/long_division.html, but I can't think of a way to translate that into code
I would appreciate some help
You will proceed from left to right, dividing the digits by two. Every time a digit is odd, you will propagate a carry (10) to the next digit.
Example: divide 123
1 divided by 2 is 0, carry = 10
2 + 10 divided by 2 is 6, no carry
3 divided by 2 is 1, carry = 10
The last carry can be ignored.
Result: 061.
carry= 0;
element= head;
WHILE element <> NIL DO
BEGIN
element^.w= element^.w + carry;
IF ODD(element^.w) THEN carry= 10 ELSE carry= 0;
element^.w= element^.w DIV 2;
element= element^.next
END.
Say i have this list of integers :
List A = 3 5 9 10 11 15
Say I have several other lists of integers :
List B1 = 1 2 3 4 5 6 7 8 20 25
List B2 = 4 7 8 13 17
List B3 = 10 11 12 13 14 15 16 17
NB :
in A, 4 is a gap (idem for 6, 7, 8, 12, 13, 14)
in B1, 1, 2, 20 and 25 are fat : superfluous because inferior to the min in A or superior to the max in A
Is there any algorithm that :
tells if a B list fills all the gaps in the A list - or not ;
(if some gaps are not filled) tells which B list fills gaps in the A list the best = highest number of gaps filled and lowest number of fat
I guess it is a classical need...
ps : i prefer .py code but pseudo-code is ok
Thanks a lot
I would use two iterators over the sorted arrays of A and B. The first iterates over A and the second over B. Whenever there is a gap in A the next number in B must fill it. Like this (example in C#):
var iterA = A.Sort().GetEnumerator();
var iterB = B.Sort().GetEnumerator();
iterA.MoveNext(); iterB.MoveNext();
var prevA = iterA.Current;
var curB = iterB.Current;
if (curB < prevA) return "B is fat";
while (iterA.MoveNext()) {
var curA = iterA.Current;
if (curA - prevA == 1) {
prevA = curA;
continue; // no gap
}
while (curA - prevA > 1) {
if (curB != prevA + 1) return "B does not fill gap";
if (iterB.MoveNext()) {
curB = iterB.Current;
prevA++;
} else return "B does not fill gap";
}
prevA = curA;
}
The runtime complexity would be linear O(N) with N being the numbers between min(A) and max(A). This is just an example to give you an idea on how to approach this problem. I do not guarantee correctness of this algorithm, I have not compiled or tested it. I don't know python, but I assume that it does provide something similar to C#'s iterators.
Following steps will do it
1) Store the gaps of A, in an array.
2) Then Map each element of A With different B(B1,B2,..)
3) And then display the result, based on the result in the above step
This is a brute force approach to solve this problem.
I'm looking for a hint to an algorithm or pseudo code which helps me calculate sequences.
It's kind of permutations, but not exactly as it's not fixed length.
The output sequence should look something like this:
A
B
C
D
AA
BA
CA
DA
AB
BB
CB
DB
AC
BC
CC
DC
AD
BD
CD
DD
AAA
BAA
CAA
DAA
...
Every character above represents actually an integer, which gets incremented from a minimum to a maximum.
I do not know the depth when I start, so just using multiple nested for loops won't work.
It's late here in Germany and I just can't wrap my head around this. Pretty sure that it can be done with for loops and recursion, but I have currently no clue on how to get started.
Any ideas?
EDIT: B-typo corrected.
It looks like you're taking all combinations of four distinct digits of length 1, 2, 3, etc., allowing repeats.
So start with length 1: { A, B, C, D }
To get length 2, prepend A, B, C, D in turn to every member of length 1. (16 elements)
To get length 3, prepend A, B, C, D in turn to every member of length 2. (64 elements)
To get length 4, prepend A, B, C, D in turn to every member of length 3. (256 elements)
And so on.
If you have more or fewer digits, the same method will work. It gets a little trickier if you allow, say, A to equal B, but that doesn't look like what you're doing now.
Based on the comments from the OP, here's a way to do the sequence without storing the list.
Use an odometer analogy. This only requires keeping track of indices. Each time the first member of the sequence cycles around, increment the one to the right. If this is the first time that that member of the sequence has cycled around, then add a member to the sequence.
The increments will need to be cascaded. This is the equivalent of going from 99,999 to 100,000 miles (the comma is the thousands marker).
If you have a thousand integers that you need to cycle through, then pretend you're looking at an odometer in base 1000 rather than base 10 as above.
Your sequence looks more like (An-1 X AT) where A is a matrices and AT is its transpose.
A= [A,B,C,D]
AT X An-1 ∀ (n=0)
sequence= A,B,C,D
AT X An-1 ∀ (n=2)
sequence= AA,BA,CA,DA,AB,BB,CB,DB,AC,BC,CC,DC,AD,BD,CD,DD
You can go for any matrix multiplication code like this and implement what you wish.
You have 4 elements, you are simply looping the numbers in a reversed base 4 notation. Say A=0,B=1,C=2,D=3 :
first loop from 0 to 3 on 1 digit
second loop from 00 to 33 on 2 digits
and so on
i reversed i output using A,B,C,D digits
loop on 1 digit
0 0 A
1 1 B
2 2 C
3 3 D
loop on 2 digits
00 00 AA
01 10 BA
02 20 CA
03 30 DA
10 01 AB
11 11 BB
12 21 CB
13 31 DB
20 02 AC
21 12 BC
22 22 CC
...
The algorithm is pretty obvious. You could take a look at algorithm L (lexicographic t-combination generation) in fascicle 3a TAOCP D. Knuth.
How about:
Private Sub DoIt(minVal As Integer, maxVal As Integer, maxDepth As Integer)
If maxVal < minVal OrElse maxDepth <= 0 Then
Debug.WriteLine("no results!")
Return
End If
Debug.WriteLine("results:")
Dim resultList As New List(Of Integer)(maxDepth)
' initialize with the 1st result: this makes processing the remainder easy to write.
resultList.Add(minVal)
Dim depthIndex As Integer = 0
Debug.WriteLine(CStr(minVal))
Do
' find the term to be increased
Dim indexOfTermToIncrease As Integer = 0
While resultList(indexOfTermToIncrease) = maxVal
resultList(indexOfTermToIncrease) = minVal
indexOfTermToIncrease += 1
If indexOfTermToIncrease > depthIndex Then
depthIndex += 1
If depthIndex = maxDepth Then
Return
End If
resultList.Add(minVal - 1)
Exit While
End If
End While
' increase the term that was identified
resultList(indexOfTermToIncrease) += 1
' output
For d As Integer = 0 To depthIndex
Debug.Write(CStr(resultList(d)) + " ")
Next
Debug.WriteLine("")
Loop
End Sub
Would that be adequate? it doesn't take much memory and is relatively fast (apart from the writing to output...).