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;
}