## Next Permutation

Posted on Fri 24 March 2017 in Puzzles

Aim: Find a larger permutation

We must move a larger number forward. So we should go from the tail to find any new number is smaller than a number behind it. If no next permutation, reverse list.

In [ ]:
def next_permutation(l):
'''Give out the next permutation of list l
>>> next_permutation …

## 24 Game Solver

Posted on Wed 01 March 2017 in Puzzles

24 game is an arithmetic game with a simple rule: Given 4 numbers and use + - * / to get 24.

• A simple example is 1, 2, 3, 4, and you find 1*2*3*4=24
• A more difficult one is 5, 5, 5, 1, the answer is 5*(5-(1/5 …

## 最大子序列和系列问题

Posted on Tue 01 November 2016 in Puzzles

In [2]:
def maxsum(l):
'''最大子序列和问题'''
m=s=0
for i in l:
s=max(s, 0)
s+=i
m=max(m, s)
return m

In [3]:
def maxprod(l):
'''最大子序列积问题'''
m=pos=0
neg=0
for i in l:
pos=max(1, pos)*i
neg=neg*i
if i …

## 拼图游戏之打乱拼图

Posted on Sat 07 March 2015 in Puzzles

## 线性时间计算排列的奇偶性¶

### 计算交换次数（鸠占鹊巢）¶

• 鸠现在占着鹊(Magpie)巢
• 鸠的巢(nest)被麻雀(sparrow)占领
• 鸠和麻雀换巢：鸠回到自己的巢，麻雀挪到鹊的巢
In [1]:
def rev_index(l):
'''Construct nest<->bird reversed index'''
rev=empty_like(l)
for i, j in enumerate(l):
rev[j]=i
return rev
def count_swap(nest2bird, bird2nest):
'''Count swaps needed …

## 拼图游戏之可解性条件

Posted on Fri 06 March 2015 in Puzzles

## 充分性¶

### 三元轮换与聚合¶

A  B     C  A     B  C
-->      -->
C  O     B  O     A  O