Who's the boss--a puzzle like Joseph's ring

Source: Internet
Author: User
an intellectual question similar to the Joseph Ring

This is a question to be asked in the interview, in fact, it is very easy to think about it. But at that time only gave two minutes, failed to give a direct solution. Problem Description

There were 156 pirates on an island, they decided to choose a person to do the boss, because so many people, choose who when the boss has not been elected, so they come up with a way to put these 156 people from 1 to 156 numbers, and then press 1, 2, 1, 2, ... Count off, Report 1 of the exit election, the rest of the people continue to be numbered, and then the ' 1 ' people kicked out, the last remaining is the boss. So, excuse me, who is the boss? ideas for solving problems

This question is a bit like the classic Joseph Ring, but it's actually easier than the Joseph Ring. We can use x 2 = 0来 as a condition of judgment, because each time it is the person who reported ' 1 '. So the program can be written in the following way:
(python)

def calc_out_2 (num):
    nlist = range (1, num)
    cnt = 1 while
    len (nlist)!= 1:
        nlist = [x/2 to x in Nlist if X 2 = 0]
        cnt *= 2 return
    cnt

calc_out_2 (156)

Load B, use functional programming, you can write this:

def calc_out_3 (num):
    nlist = range (1, num)
    cnt = 1
    while Len (nlist)!= 1:
        nlist = map (lambda x:x/2, fi Lter (lambda x:x%2 = = 0, nlist)
        CNT *= 2 return
    cnt
calc_out_1 (156)

Again careful analysis, because every time is ' 1 ' out, so the definition of f (n) for n Pirates Select the boss of the function.

F (2) = 2
F (3) = 2
F (4) = 4
F (5) = 4
F (6) = 4
F (7) = 4
F (8) = 8
F (9) = 8
...

Let's see the rules:

F (n) = max (2^x) if 2^x < n

Rewrite the Python code as follows:

Import math as M
log = M.log

def calc_out_1 (num): Return
    POW (2, int (log (num)/log (2))

calc_out_1 (156)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.