Thursday, January 29, 2015

Simple Implementation of Binary Search Tree in Ocaml


  
 
type 'a tree = 
 | Node of 'a * 'a tree * 'a tree
 | Leaf;;

let empty = Leaf ;;

let rec mem x = function
 | Leaf -> false
 | Node (key, left, right) ->
  key = x || (x < key && mem x left) || (x > key && mem x right) ;;


(* insert function will ignore the key which has already existed *)
let rec insert x = function
 | Leaf -> Node (x, Leaf, Leaf)
 | Node (k, left, right) as node-> 
    if x < k then
    Node (k, insert x left, right)
   else if x > k then
    Node (k, left, insert x right)
   else
    node ;;


let rec tree_of_list = function
 | [] -> empty
 | h::t -> insert h (tree_of_list t) ;;


let rec insert x = function
 | Leaf -> Node (x, Leaf, Leaf)
 | Node (k, left, right) as node-> 
    if x < k then
    Node (k, insert x left, right)
   else if x > k then
    Node (k, left, insert x right)
   else
    node ;;


let my_tree = tree_of_list [2;3;4;1;7;6;4;8] ;;

let rec in_order_walk = function
 | Leaf -> ()
 | Node (k,left,right) ->
  in_order_walk left;
  let () = print_int k in
    print_newline ();
  in_order_walk right;;

let rec pre_order_walk = function
 | Leaf -> ()
 | Node (k, left, right) ->
  let () = print_int k in
   print_newline ();
  pre_order_walk left;
  pre_order_walk right ;;

let rec post_order_walk = function
 | Leaf -> ()
 | Node (k, left, right) ->
  post_order_walk left;
  post_order_walk right;
  let () = print_int k in
   print_newline () ;;
  
let rec height = function
 | Leaf -> 0
 | Node (k, left, right) ->
   1 + max (height left) (height right) ;;





  

Sunday, January 18, 2015

Hackerrank: Permutation game

Permutation game
https://www.hackerrank.com/challenges/permutation-game

Problem Statement
Alice and Bob play the following game:
  1. They choose a permutation of the first N numbers to begin with.
  2. They play alternately and Alice plays first.
  3. In a turn, they can remove any one remaining number from the permutation.
  4. The game ends when the remaining numbers form an increasing sequence. The person who played the last turn (after which the sequence becomes increasing) wins the game.

Assuming both play optimally, who wins the game? 
Input: 
The first line contains the number of test cases T. T test cases follow. Each case contains an integer N on the first line, followed by a permutation of the integers 1..N on the second line.
Output: 
Output T lines, one for each test case, containing "Alice" if Alice wins the game and "Bob" otherwise.
Constraints: 
1 <= T <= 100 
2 <= N <= 15 
The permutation will not be an increasing sequence initially.
Sample Input:
2
3
1 3 2
5
5 3 2 1 4
Sample Output:
Alice
Bob
Explanation: 
For the first example, Alice can remove the 3 or the 2 to make the sequence increasing and wins the game. 

For the second example, if 4 is removed then the only way to have an increasing sequence is to only have 1 number left, which would take a total of 4 moves, thus allowing Bob to win. On the first move if Alice removes the 4, it will take 3 more moves to create an increasing sequence thus Bob wins. If Alice does not remove the 4, then Bob can remove it on his next turn since Alice can not win in one move.
Solution: To solve this problem, we will use recursion and memorization. Given a list we will determine if the player starts from that position can win the game. In my algorithm, I tested all the possibilities. For example, let say Alice starts from (5 3 2 1 4), the algorithm will test all available choices, therefore we will test if (3 2 1 4) (5 2 1 4) (5 3 2 4) (5 3 2 1) are winnable positions.
Notice that (5 2 1 4) is equivalent to (4 2 1 3) = (5-1 2 1 4-1) and it is here that the recursion comes in.
Code:

(defvar num-case)       ;; denotes the number of test case in the online judgement

(defvar tab)            ;; we will use a hash table to store all the results that have been calculated
                        ;; we expect that during the recursion we will meet the same configuration many times
                        ;; hence, use a hash table to memorize results can accelerate the algorithm


(setq tab (make-hash-table :test 'equal)) ;; we use 'equal test, because we want to compare the contents of two list



(defun test-lst (lst)
  "this function test if the lst reaches a terminal condition"
  (if (= 1 (length lst))      
    t                             ;; if the list has only one element, then this is a terminal condition 
    (let ((ref (first lst))       ;; otherwier, we will check if the list is in a increasing order
          (terminated t))
      (dolist (it (rest lst))
        (if (< it ref)
          (setq terminated nil))
        (setq ref it))
      terminated)))
        

 (defun is-win-position(lst) 
   (if (gethash lst tab)          
     (gethash lst tab)                       ;;; if we have already calculated the result
     (let ((test-res (test-lst lst)))        ;;; otherwise, test every possibility
       (if test-res
         (setf (gethash lst tab) nil)
      (let ((this-is-a-win-position nil))
       (dolist (element lst)
         (let ((new-lst ()))
           (dolist (x lst)                   ;;; here we will create a new list and it is here that 
             (cond                           ;;; the recursion involves
               ((< x element) (push x new-lst))
               ((> x element) (push (1- x) new-lst))
               (t ())))
                  (setf new-lst (reverse new-lst))
               (let ((tmp-result (is-win-position new-lst)))
                 (if (null tmp-result)
                   (progn
                     (setf this-is-a-win-position t)
                     (return))))))
        (setf (gethash lst tab) this-is-a-win-position))))))


 (setq tab (make-hash-table :test 'equal))         
          


;;; main part

(setq num-case (read))

(dotimes (i num-case)
  (let ((n (read))
        (my-lst ()))
    (dotimes (j n)
      (push (read) my-lst))
    (setq my-lst (reverse my-lst))
    (let ((res (is-win-position my-lst)))
      (if res
        (format t "Alice~%")
        (format t "Bob~%")))))

          
          

          
         
             




Hackerrank: Stone Piles



Problem Statement
Stone Piles

 https://www.hackerrank.com/challenges/stone-piles
 
There are N piles of stones where the ith pile has xi stones in it. Alice and Bob play the following game:
  1. Alice starts, and they alternate turns.
  2. In a turn, a player can choose any one of the piles of stones and divide the stones in it into any number of unequal piles such that no two of the newly created piles have the same number of stones. For example, if there 8 stones in a pile, it can be divided into one of these set of piles: (1,2,5), (1,3,4), (1,7), (2,6) or (3,5). 
  3. The player who cannot make a move (because all the remaining piles are indivisible) loses the game.
Given the starting set of piles, who wins the game assuming both players play optimally?

Input:
The first line contains the number of test cases T. T test cases follow. The first line for each test case contains N, the number of piles initially. The next line contains N space delimited numbers, the number of stones in each of the piles.

Output:
Output T lines, one corresponding to each test case containing "ALICE" if Alice wins the game and "BOB" otherwise.

Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 50
1 ≤ xi ≤ 50
Sample Input
4  
1  
4  
2  
1 2  
3  
1 3 4  
1  
8
Sample Output
BOB  
BOB  
ALICE  
BOB
 
Explanation
For the first case, the only possible move for Alice is (4) -> (1,3). Now Bob breaks up the pile with 3 stones into (1,2). At this point Alice cannot make any move and has lost.




Solution:
To solve this problem we need some basic knowledge in game theory. There is a well-written tutorial about impartial games online. (http://web.mit.edu/sp.268/www/nim.pdf)

Now back to our problem. The basic idea is to compute the Sprague-Grundy function. We can apply the same argument about the Nim game mentioned in the tutorial, meaning if we have SG function eaqual to zero in the current step, we will get a non-zero value in the next step and if we have a non-zero value at current step, we can always construct a strategy  that brings the value to zero again.

Given the initial array, we can compute the SG value, if it is zero then print "BOB", otherwise print "ALICE".

Code:


#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <vector>
#include <climits>
#include <list>
#include <unordered_map>
#include <algorithm>

using namespace std;


typedef vector< vector<bool> > myVector;


void compute_sg_fun(int prev, int start, int rest, int key, vector<int>& sg_fun, myVector& record) {

 for (int i = start; i <= rest / 2; i++) {
  if (rest-i > i) {
   int res = prev ^ sg_fun[i] ^ sg_fun[rest-i];
   record[key][res] = true;
   compute_sg_fun(prev ^ sg_fun[i], i+1, rest - i,key, sg_fun, record);
  }
 }

 int k = 0;

 while (record[key][k]) ++k;

 sg_fun[key] = k;
}






int main(void)


{

 myVector record(51, vector<bool>(51,false));
 vector<int> sg_fun(51,-1);
 sg_fun[0] = 0;
 sg_fun[1] = 0;
 sg_fun[2] = 0;
 sg_fun[3] = 1;


 for (int i = 4; i <= 50; i++) compute_sg_fun(0,1,i,i,sg_fun,record);
 
 int t; cin >> t;

 for (int i = 0; i < t; i++) {
  int n;
  cin >> n;

  int res = 0;

  for (int j = 0; j < n; j++) {
   int c; cin >> c;
   res = res ^ sg_fun[c];
  }

  printf("%s\n", res == 0 ? "BOB" : "ALICE");

 }

 return 0;

}









Tuesday, January 13, 2015

Common Lisp Books




Common Lisp Books

It is really fun to learn Common Lisp. Though it may take time to learn the nuance of different concepts in Common Lisp, it is actually not that hard to learn. Once we become familiar with the basic concepts of the language, we can start to write our own program very quickly.

It turns out that we can really get satisfaction when we write Common Lisp program. Part of the reason is the name of functions in Common Lisp. For instance, there is a really useful function called “describe”, when I enter the word describe I have the feeling that I am talking with the machine.

There are some well-written books, I would recommend the following three books. They are not hard to read and I think they cover most of the aspects in the language.



Practical Common Lisp, by Peter Seibel

http://www.gigamonkeys.com/book/


Common Lisp: A gentle introduction to Symbolic Computation, by David S. Touretzky
https://www.cs.cmu.edu/~dst/LispBook/book.pdf

Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp, by Peter Norvig

http://www.amazon.com/Paradigms-Artificial-Intelligence-Programming-Studies-ebook/dp/B003VWBY1I

Tuesday, January 6, 2015

Monday, January 5, 2015

Lisp的括号




之前一直觉得lisp的括号确实多的有点让人难以置信。想到以前看到的一个笑话,说是有人去偷别人写的代码但是只拿到了最后几页,回去一看只有括号。 原先觉得这个笑话不是那么的好笑,现在想想觉得还有有点意思。


写for loop 的时候心里也有些微词,觉得格式有些复杂,不够简洁。但是今天开始写C++的时候发现虽然C++的 for loop 看上去简洁,但是真正打起来还是有点费时间,主要是因为手要来回移动,消耗不少时间。虽然不知道为什么,但是现在隐约觉得似乎lisp的程序写起来要稍稍快一些。 不知道是不是一种错觉。

我觉得应该设计一种键盘,专门为编程优化才对。





Tuesday, December 23, 2014

今夜的灯光不属于我




果然选择了一条比较艰难的道路。我时常告诫自己,年轻的时候要去多经历一些,哪怕道路不是那么平坦也要坚定地走下去。可是事情往往是说起来容易,真正实践起来就变得无比困难。困难本身并没有什么变化,随着时间的推移,外部的环境可能会有细小的变化,但是终究还是和最初的状况相差无几。更多的是心理上的,很容易就会怀疑自己,否定自己。其实我可以想得明白,在某一个时刻做出某一个决定,那时往往不是是非对错的问题,往往也不存在是非对错的问题。就是那么决定了而已。

“现在”是一个非常奇妙的时间点,既无法纠结未来,过去的也无法纠结。前两天无意间看到一篇文章,大意上是说我们应该始终相信过去的决定是正确的。从某种程度上我是赞成这样的一种态度。 最近一段时间情绪有些低落,我也明白了一个道理,那就是一个人比自己想象的还要孤独很多。几乎没有人可以真正理解另一个人,最好的情况也不过是无条件的支持。这样的支持一般来自父母和身边最好的一两个朋友,剩下的就无关紧要了。如果说目前有什么压力,那也就是看着日渐苍老的父母,在看着自己的无所作为感到一种对于自己的无能的愤怒。

生活在这样一个时代,我们似乎已经没有办法知道自己以后会去做什么。但我仍然想知道自己以后想去做什么,想拥有怎样一种生活。我始终坚信需要把握住大的方向,不然就会迷失在细节和琐碎之中。 我并不知道挣扎会不会让人变得更加强壮。然而自强不息的呐喊已经深深根植在心中。没有理由退缩,没有理由放弃。
 
很快新的一年就要到来,希望自己能给自己一个交代。