2016年8月15日 星期一

用Java連接Redis(使用Jedis)

此篇主要介紹使用Jedis來用Java操作Redis資料庫,進行以下操作之前請先確定有安裝以及啟動Redis,可參考此篇

Jedis安裝

這邊主要介紹用Maven安裝Jedis到專案裡,您也可以直接到這裡下載最新版本的Jedis。
以安裝2.9.0版本的Jedis為例,將以下語法貼進pom.xml的dependencies tag裡面:
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
並且進行maven install即可將Jedis安裝至專案。

Jedis基本使用範例

以下範例使用Jedis來儲存以及讀取String,Java程式碼如下:
import redis.clients.jedis.Jedis;

public class JedisEx {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        String value;

        try {
            jedis.set("helloStr", "hello");
            value = jedis.get("helloStr");
            System.out.println(value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }
}
此範例連接到本機的Redis,並且儲存了一個key為helloStr以及value為hello的String。接著利用此key從Redis讀取出對應的value,並將value印出來,輸出結果為hello。最後將jedis的連線資源做關閉。

2016年8月9日 星期二

Redis安裝以及基本操作

What is Redis?

Redis是一個NoSQL資料庫,提供許多不同的資料結構供資料處理使用。Redis在memory上處理資料,所以讀取速度快,並且可將結果存進disk以供下次使用。

Redis建置與啟動

這邊主要介紹的是build from source code(unstable)的方法,您也可以去Redis官網下載或OS X使用者可以用homebrew安裝,指令如下:
brew install redis
首先到Redis的github(unstable branch)把專案用git clone下來之後,切到redis專案目錄底下build,指令如下:
make
build完之後就可以啟動Redis,先將目錄切到src底下,並輸入以下指令:
./redis-server
不過啟動後service就會開著,並且卡住terminal,所以建議可以搭配tmux來操作。

Redis基本操作範例

把目錄切到src底下,用以下指令即可打開與Redis互動的環境:
./redis-cli
進入互動環境後,可以開始下一些指令來做資料儲存和取得的工作,以下用儲存String型態的資料為範例:
set helloStr 'hello'
這個指令指定一個key叫做helloStr並且將值設為hello,所以如果要取得這個String的話可以用以下指令:
get helloStr
若要列出資料庫裡目前所有的key的話,可用以下指令:
keys *
以上只是簡單的操作範例,Redis還提供許多好用的資料結構如 Set, Sorted Set 和 Hash 等。
想要看更多操作指令,可以參考官方文件

2016年8月8日 星期一

107 - The Cat in the Hat

The Cat in the Hat 

Background

(An homage to Theodore Seuss Geisel)
The Cat in the Hat is a nasty creature,
But the striped hat he is wearing has a rather nifty feature.
With one flick of his wrist he pops his top off.
Do you know what's inside that Cat's hat?
A bunch of small cats, each with its own striped hat.
Each little cat does the same as line three,
All except the littlest ones, who just say ``Why me?''
Because the littlest cats have to clean all the grime,
And they're tired of doing it time after time!

The Problem

A clever cat walks into a messy room which he needs to clean. Instead of doing the work alone, it decides to have its helper cats do the work. It keeps its (smaller) helper cats inside its hat. Each helper cat also has helper cats in its own hat, and so on. Eventually, the cats reach a smallest size. These smallest cats have no additional cats in their hats. These unfortunate smallest cats have to do the cleaning.
The number of cats inside each (non-smallest) cat's hat is a constant, N. The height of these cats-in-a-hat is tex2html_wrap_inline35 times the height of the cat whose hat they are in.
The smallest cats are of height one;
these are the cats that get the work done.
All heights are positive integers. Given the height of the initial cat and the number of worker cats (of height one), find the number of cats that are not doing any work (cats of height greater than one) and also determine the sum of all the cats' heights (the height of a stack of all cats standing one on top of another).

The Input

The input consists of a sequence of cat-in-hat specifications. Each specification is a single line consisting of two positive integers, separated by white space. The first integer is the height of the initial cat, and the second integer is the number of worker cats.
A pair of 0's on a line indicates the end of input.

The Output

For each input line (cat-in-hat specification), print the number of cats that are not working, followed by a space, followed by the height of the stack of cats. There should be one output line for each input line other than the ``0 0'' that terminates input.

Sample Input

216 125
5764801 1679616
0 0

Sample Output

31 671
335923 30275911
 
出處: UVa Online Judge - The Cat in the Hat


問題敘述

現在有貓咪進去一個房間,房間非常髒亂所以需要打掃,但是這個貓咪不想自己掃地,所以牠戴了頂帽子把別的小貓咪裝進去,要別的小貓咪打掃(好奸詐)。不過在帽子裡面的小貓咪可以再戴帽子裝更小的貓咪,一直裝到小到沒有戴帽子的貓咪就要打掃了(真可憐)。裝貓咪的過程有個數學規律在裡面,就是假設此貓咪的身高為 h,帽子可以裝的貓咪數量為 n,則帽子裡面的貓咪身高為 h / (n + 1),最小的貓咪身高為1(即不能再戴帽子且要打掃的貓咪)。題目每組資料會輸入兩個整數,第一個整數為第一個貓咪的身高,第二個整數為最後要打掃的貓咪數量,要求您輸出兩個整數,第一個整數為沒有打掃的貓咪數量,第二個整數為所有貓咪的總身高為多少。

解題思路

此題很明顯是數學題,首先我們把算式列出來:

設 n 為帽子可以裝貓咪的數量、k 為某個非負整數、c 為最後要打掃的貓咪數量、h 為初始貓咪的身高,可以列出以下兩個式子

n ^ k = c
h * (1 / (n + 1)) ^ k = 1

先將兩個算式都取 log

k * log(n) = log(c)
k * log(n + 1) = log(h)

將上面的算式除以下面的算式可以得到以下

log(n) / log(n + 1) = log(c) / log(h)

接著我們只要找出 n 讓等式成立就可以知道帽子裡可以裝多少貓咪了。知道 n 之後剩下的工作就相當簡單了,可以依據以下算式求出沒在打掃的貓咪:

n ^ 0 + n ^ 1 + ... + n ^ (k - 2) + n ^ (k - 1)

至於總身高可以由以下算式求出:

h * (n ^ 0) + (h / (n + 1)) * (n ^ 1) + ... + (h / (n + 1) ^ (k - 1)) * n ^ (k - 1) + (h / (n + 1) ^ k) * n ^ k

c++ 程式碼

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    while (true) {
        int initHeight, workCat, n, k, height;
        double rightC;
        int notWorkCat = 0;
        int totalHeight = 0;

        cin >> initHeight >> workCat;
        if (!initHeight && !workCat)
            break;
        if (workCat == 1)
            n = 1;
        else {
            rightC = log(initHeight) / log(workCat);
            for (n=2;; n++) {
                double leftC = log(n + 1) / log(n);

                if (leftC - rightC <= 0.0000000001)
                    break;
            }
        }
        k = round(log(initHeight) / log(n + 1));
        height = initHeight;
        for (int i=0; i<k; i++) {
            int cats = pow(n, i);

            notWorkCat += cats;
            totalHeight += height * cats;
            height /= n + 1;
        }
        cout << notWorkCat << " " << totalHeight + workCat << endl;
    }

    return 0;
}

2014年4月19日 星期六

Sudoku Solver



What is this?

This is a program which can solve sudoku for those people who are tired of solving difficult sudoku problem.

How to use?

1. Input the sudoku problem into the board.
2. Click "Solve It!" to solve sudoku, and you will see the answer on the board.
3. If you want to input another sudoku problem, just click "Clear" to clean the board and input again.

118 - Mutant Flatworld Explorers

Background

Robotics, robot motion planning, and machine learning are areas that cross the boundaries of many of the subdisciplines that comprise Computer Science: artificial intelligence, algorithms and complexity, electrical and mechanical engineering to name a few. In addition, robots as ``turtles'' (inspired by work by Papert, Abelson, and diSessa) and as ``beeper-pickers'' (inspired by work by Pattis) have been studied and used by students as an introduction to programming for many years.
This problem involves determining the position of a robot exploring a pre-Columbian flat world.

The Problem

Given the dimensions of a rectangular grid and a sequence of robot positions and instructions, you are to write a program that determines for each sequence of robot positions and instructions the final position of the robot.
A robot position consists of a grid coordinate (a pair of integers: x-coordinate followed by y-coordinate) and an orientation (N,S,E,W for north, south, east, and west). A robot instruction is a string of the letters 'L', 'R', and 'F' which represent, respectively, the instructions:
  • Left: the robot turns left 90 degrees and remains on the current grid point.
  • Right: the robot turns right 90 degrees and remains on the current grid point.
  • Forward: the robot moves forward one grid point in the direction of the current orientation and mantains the same orientation.
The direction North corresponds to the direction from grid point (x,y) to grid point (x,y+1).
Since the grid is rectangular and bounded, a robot that moves ``off'' an edge of the grid is lost forever. However, lost robots leave a robot ``scent'' that prohibits future robots from dropping off the world at the same grid point. The scent is left at the last grid position the robot occupied before disappearing over the edge. An instruction to move ``off'' the world from a grid point from which a robot has been previously lost is simply ignored by the current robot.

The Input

The first line of input is the upper-right coordinates of the rectangular world, the lower-left coordinates are assumed to be 0,0.
The remaining input consists of a sequence of robot positions and instructions (two lines per robot). A position consists of two integers specifying the initial coordinates of the robot and an orientation (N,S,E,W), all separated by white space on one line. A robot instruction is a string of the letters 'L', 'R', and 'F' on one line.
Each robot is processed sequentially, i.e., finishes executing the robot instructions before the next robot begins execution.
Input is terminated by end-of-file.
You may assume that all initial robot positions are within the bounds of the specified grid. The maximum value for any coordinate is 50. All instruction strings will be less than 100 characters in length.

The Output

For each robot position/instruction in the input, the output should indicate the final grid position and orientation of the robot. If a robot falls off the edge of the grid the word ``LOST'' should be printed after the position and orientation.

Sample Input

5 3
1 1 E
RFRFRFRF
3 2 N
FRRFLLFFRRFLL
0 3 W
LLFFFLFLFL

Sample Output

1 1 E
3 3 N LOST
2 3 S
 
出處: UVa Online Judge - Mutant Flatworld Explorers


問題敘述

此問題會先輸入兩個整數,表示這個矩形右上角的座標,接著會輸入多組測試資料,每組測試資料兩行,一直到輸入結束為止。每組測試資料第一行輸入的是兩個整數及一個字元,兩個整數代表機器人所在的初始的座標,字元表示面對的方位(E=東, W=西, S=南, N=北),第二行輸入的則是一行字串代表著一連串的指令(L=左轉, R=右轉, F=往現在面對的方位走一格)。每組輸入會對應一組輸出,此問題要求您輸出經過一連串的指令後,機器人最後所在的座標以及面對的方位為何。若機器人在執行指令的過程中跑出了此矩形的範圍,就輸出它在跑出去前的座標和方位並且印出 LOST,若機器人下次執行指令時,再次在之前跑出去過的座標往矩形外面跑,則此指令視為無效,將會被忽略。

解題思路

這是一個模擬類型的題目,沒有什麼特別的思路,但是要善用資料結構。比如說要如何知道左轉或右轉會轉到哪個方位呢? 我的作法是用一個陣列存{'E', 'N', 'W', 'S'},然後用一個 index 表示現在所在的位置,index + 1 就是左轉,index - 1 就是右轉,但是注意 index 做加減的時候可能會超出陣列範圍,所以要做環狀處理(意即 index 等於陣列的長度的時候要讓 index = 0,index 小於 0 的時候要讓 index = 陣列的長度 - 1)。其他的就把程式碼交給讀者們參考了。

c++ 程式碼

#include <iostream>
#include <map>
#include <vector>
using namespace std;

bool checkIsLost(int x, int y, int maxX, int maxY) {
    return x < 0 || x > maxX || y < 0 || y > maxY;
}

int main() {
    int maxX, maxY, x, y;
    char ori;
    string ins;
    char oriArr[4] = {'E', 'N', 'W', 'S'};
    int oriArrLen = 4;
    map<char, int> oriIndexMap;

    oriIndexMap['E'] = 0;
    oriIndexMap['N'] = 1;
    oriIndexMap['W'] = 2;
    oriIndexMap['S'] = 3;
    cin >> maxX >> maxY;
    vector< vector<bool> > lostTable(maxX + 1, vector<bool>(maxY + 1, false));
    while (cin >> x >> y >> ori >> ins) {
        int oriIndex;
        bool lost = false;

        oriIndex = oriIndexMap[ori];
        for (int i=0; i<ins.length(); i++) {
            switch (ins[i]) {
                case 'L':
                    oriIndex = (oriIndex + 1) % oriArrLen;
                    break;
                case 'R':
                    if (oriIndex)
                        oriIndex--;
                    else
                        oriIndex = oriArrLen - 1;
                    break;
                case 'F':
                    switch (oriIndex) {
                        case 0:
                            lost = checkIsLost(x + 1, y, maxX, maxY);
                            if (!lost)
                                x++;
                            break;
                        case 1:
                            lost = checkIsLost(x, y + 1, maxX, maxY);
                            if (!lost)
                                y++;
                            break;
                        case 2:
                            lost = checkIsLost(x - 1, y, maxX, maxY);
                            if (!lost)
                                x--;
                            break;
                        case 3:
                            lost = checkIsLost(x, y - 1, maxX, maxY);
                            if (!lost)
                                y--;
                    }
            }
            if (lost && !lostTable[x][y]) {
                lostTable[x][y] = true;
                break;
            }
        }
        cout << x << " " << y << " " << oriArr[oriIndex];
        if (lost)
            cout << " " << "LOST\n";
        else
            cout << endl;
    }

    return 0;
}

2014年4月7日 星期一

102 - Ecological Bin Packing

Background

Bin packing, or the placement of objects of certain weights into different bins subject to certain constraints, is an historically interesting problem. Some bin packing problems are NP-complete but are amenable to dynamic programming solutions or to approximately optimal heuristic solutions.
In this problem you will be solving a bin packing problem that deals with recycling glass.

The Problem

Recycling glass requires that the glass be separated by color into one of three categories: brown glass, green glass, and clear glass. In this problem you will be given three recycling bins, each containing a specified number of brown, green and clear bottles. In order to be recycled, the bottles will need to be moved so that each bin contains bottles of only one color.
The problem is to minimize the number of bottles that are moved. You may assume that the only problem is to minimize the number of movements between boxes.
For the purposes of this problem, each bin has infinite capacity and the only constraint is moving the bottles so that each bin contains bottles of a single color. The total number of bottles will never exceed 2^31.

The Input

The input consists of a series of lines with each line containing 9 integers. The first three integers on a line represent the number of brown, green, and clear bottles (respectively) in bin number 1, the second three represent the number of brown, green and clear bottles (respectively) in bin number 2, and the last three integers represent the number of brown, green, and clear bottles (respectively) in bin number 3. For example, the line 10 15 20 30 12 8 15 8 31
indicates that there are 20 clear bottles in bin 1, 12 green bottles in bin 2, and 15 brown bottles in bin 3.
Integers on a line will be separated by one or more spaces. Your program should process all lines in the input file.

The Output

For each line of input there will be one line of output indicating what color bottles go in what bin to minimize the number of bottle movements. You should also print the minimum number of bottle movements.
The output should consist of a string of the three upper case characters 'G', 'B', 'C' (representing the colors green, brown, and clear) representing the color associated with each bin.
The first character of the string represents the color associated with the first bin, the second character of the string represents the color associated with the second bin, and the third character represents the color associated with the third bin.
The integer indicating the minimum number of bottle movements should follow the string.
If more than one order of brown, green, and clear bins yields the minimum number of movements then the alphabetically first string representing a minimal configuration should be printed.

Sample Input

1 2 3 4 5 6 7 8 9
5 10 5 20 10 5 10 20 10

Sample Output

BCG 30
CBG 50

出處: UVa Online Judge - Ecological Bin Packing


問題敘述

此問題會有很多行輸入,每一行都會有九個整數,前三個整數分別代表在第一個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量,中間三個整數分別代表在第二個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量,最後三個整數分別代表在第三個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量。此問題要求您用最少的次數移動瓶子,來讓每個桶子都只裝一種顏色,並且輸出每個桶子各擺哪些顏色以及最少移動的次數。若不只一種移動方法可以讓每個桶子都只裝一種顏色且移動次數最少,則字母排列順序比較優先的要被輸出。

解題思路

因為瓶子的顏色只有三種,總共也只有六種排列方式,故暴力法是最簡單直接的解法。照字母順序把六種擺放瓶子顏色的方式都算出移動次數,並照順序找出移動次數最小的排列方式就是解答。

c++ 程式碼

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    int start;

    while (cin >> start) {
        vector< vector<int> > binBottle(3, vector<int>(3, -1));
        vector<string> comb(6, "");
        map<string, int> getCount;
        string minComb;

        comb[0] = "BCG";
        comb[1] = "BGC";
        comb[2] = "CBG";
        comb[3] = "CGB";
        comb[4] = "GBC";
        comb[5] = "GCB";
        for (int i=0; i<binBottle.size(); i++) {
            for (int j=0; j<binBottle[i].size(); j++) {
                if (!i && !j)
                    binBottle[i][j] = start;
                else
                    cin >> binBottle[i][j];
            }
        }
        getCount[comb[0]] = binBottle[1][0] + binBottle[2][0] + binBottle[0][2] + binBottle[2][2] +
                            binBottle[0][1] + binBottle[1][1];
        getCount[comb[1]] = binBottle[1][0] + binBottle[2][0] + binBottle[0][1] + binBottle[2][1] +
                            binBottle[0][2] + binBottle[1][2];
        getCount[comb[2]] = binBottle[1][2] + binBottle[2][2] + binBottle[0][0] + binBottle[2][0] +
                            binBottle[0][1] + binBottle[1][1];
        getCount[comb[3]] = binBottle[1][2] + binBottle[2][2] + binBottle[0][1] + binBottle[2][1] +
                            binBottle[0][0] + binBottle[1][0];
        getCount[comb[4]] = binBottle[1][1] + binBottle[2][1] + binBottle[0][0] + binBottle[2][0] +
                            binBottle[0][2] + binBottle[1][2];
        getCount[comb[5]] = binBottle[1][1] + binBottle[2][1] + binBottle[0][2] + binBottle[2][2] +
                            binBottle[0][0] + binBottle[1][0];
        minComb = comb[0];
        for (int i=1; i<comb.size(); i++) {
            if (getCount[minComb] > getCount[comb[i]])
                minComb = comb[i];
        }
        cout << minComb << " " << getCount[minComb] << endl;
    }

    return 0;
}

2014年3月5日 星期三

Binary search

演算法類型

divide and conquer, 搜尋演算法

演算法目的

利用比對 key value 來對資料進行搜尋

演算法描述

使用 binary search 的前提是資料必須是已經排序好的,接著再藉由比對資料堆中間位置的 key value 來將資料堆做二分法搜尋。舉例說明,假設有一排序好的數列如下圖:



現在假設我們要搜尋的數字是 3,就我們目前所得知的資訊,3 有可能出現在此數列的任何位置,所以目前的搜尋範圍是整個數列,我們先找出在搜尋範圍內中間位置的數字,如下圖:


我們在中間位置找到 4,很明顯的 4 不是我們要的 3,不過因為數列是已經排序好的而且 3 < 4,故我們可以確定 3 只有可能落在 4 的左邊而不可能會落在 4 的右邊,如下圖:


如此我們就可以拋棄右邊,接著繼續向左邊搜尋,所以現在的搜尋範圍變成只剩 4 的左邊,同之前的方法,直接去比對搜尋範圍中間位置的數字,如下圖:


我們在搜尋範圍中間找到 2,很明顯 2 不是我們要的 3,不過因為數列是已經排序好的而且 3 > 2,故我們可以確定 3 只有可能落在 2 的右邊而不可能會落在 2 的左邊,如下圖:


同之前的方法,我們繼續在搜尋範圍內找中間的數字做比對,以目前的情況來看,我們只剩下一個數字,如下圖:


恭喜,我們很幸運的找到 3 了,binary search 圓滿結束。如果一直二分到沒有範圍可以搜尋,則代表此數字不在數列裡。

最壞情況效率分析

設總資料量為 n, 分析單位為比較次數
binary search 的最壞情況就是要搜尋的資料不在資料堆裡,依據最壞情況可以列出以下遞迴式:

T(n) = T(n / 2) + 1
T(1) = 1

根據 master theorem,可推出此演算法效率的最壞情況為 O(lgn)

程式實作


C
#include <stdio.h>

int binarySearch(int *, int, int);

int main() {
    int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    int arrLength = 8;
    int findNum = 3;
    int findIndex = binarySearch(arr, arrLength, findNum);

    if (findIndex == -1)
        printf("The number %d is not in the sequence\n", findNum);
    else
        printf("The number %d is at index %d\n", findNum, findIndex);

    return 0;
}

int binarySearch(int *arr, int arrLength, int findNum) {
    int low = 0;
    int high = arrLength - 1;

    while (low <= high) {
        int mid = (low + high) / 2;

        if (findNum > arr[mid])
            low = mid + 1;
        else if (findNum == arr[mid])
            return mid;
        else
            high = mid - 1;
    }
    return -1;
}

Java
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        int findNum = 3;
        int findIndex = binarySearch(arr, findNum);

        if (findIndex == -1)
            System.out.printf("The number %d is not in the sequence\n", findNum);
        else
            System.out.printf("The number %d is at index %d\n", findNum, findIndex);
    }

    private static int binarySearch(int[] arr, int findNum) {
        int low = 0;
        int high = arr.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;

            if (findNum > arr[mid])
                low = mid + 1;
            else if (findNum == arr[mid])
                return mid;
            else
                high = mid - 1;
        }
        return -1;
    }
}

Python
def binarySearch(arr, findNum):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) / 2
        if findNum > arr[mid]:
            low = mid + 1
        elif findNum == arr[mid]:
            return mid
        else:
            high = mid - 1
    return -1

arr = [1, 2, 3, 4, 5, 6, 7, 8]
findNum = 3
findIndex = binarySearch(arr, findNum)
if findIndex == -1:
    print "The number %d is not in the sequence" % (findNum)
else:
    print "The number %d is at index %d" % (findNum, findIndex)