2011-07-18 10 views
4

如何用基於數組的語言K(或Q)表達這個命令函數?如何用一個基於數組的語言(如K(或Q))來表示這個命令函數?

在馬虎C++:

vector<int> x(10), y(10); // Assume these are initialized with some values. 

// BTW, 4 is just a const -- it's part of the algorithm and is arbitrarily chosen. 

vector<int> result1(x.size() - 4 + 1); // A place to hold a resulting array. 
vector<int> result2(x.size() - 4 + 1); // A place to hold another resulting array. 

// Here's the code I want to express functionally. 
for (int i = 0; i <= x.size() - 4; i++) { 
    int best = x[i + 0] - y[i + 0]; 
    int bad = best; 
    int worst = best; 
    for(int j = 0; j < 4; j++) { 
     int tmp = x[i + j] - y[i + 0]; 
     bad = min(bad, tmp); 
     if(tmp > best) { 
      best = tmp; 
      worst = bad; 
     } 
    } 
    result1[i] = best 
    result2[i] = worst 
} 

我最想看到這個kdb和Q,但其他功能的語言是受歡迎的。

+2

這段代碼試圖做什麼? –

+0

它試圖計算兩件事:首先,在x中的每個點上,我們希望在接下來的4個元素上有最大值(讓我們稱之爲Nx = max(x),在位置Px處,其中Px = 0..3。Second ,在x的每個點上,我們都希望下一個Px點的最小值。 – Badmanchild

回答

5

Kona(一個開電源K,方言):

首先,設置一些示例值(使用相同的Clojure溶液):

a:1+!8;b:8#0  /a is 1..8, b is eight 0s 

然後:

{(|/x;&/x)}@+{4#y _ x}[a+b;]'!#a 

一個b是您的上面的x和y變量。 (K使得爲變量x,y和z的特殊情況。)

爲了打破了位更多:

maxmin:{(|/x;&/x)}/(max;min) pairs of x 
get4:{4#y _ x} /next 4 from x, starting at y 
        /with <4 remaining, will repeat; doesn't matter for min or max 
/maxmin applied to flipped results of get4(a-b) at each index 0..(length a)-1 
[email protected]+get4[a-b;]'!#a 

/result 
(4 5 6 7 8 8 8 8 
1 2 3 4 5 6 7 8) 
2

Clojure(的Lisp方言):

(defn minmax [x y](map #(vector (- (apply max %1) %2) (- (apply min %1) %2)))(partition-all 4 1 x) y) 

(minmax [1 2 3 4 5 6 7 8] [0 0 0 0 0 0 0 0]) 

會給

[(4 1] [5 2] [6 3] [7 4] [8 5] [8 6] [8 7] [8 8])`(結果1,結果2)作爲輸出..

然後

(map #(first %1) result) is result1 
(map #(last %1) result) is result2 
4

移植@ silentbicycle爲其k直接至q產量

q)a:1+til 8 
q)b:8#0 
q){(max x;min x)}flip{4#y _ x}[a+b;]each til count a 
4 5 6 7 8 8 8 8 
1 2 3 4 5 6 7 8 

另一種方法,稍微更加矢量化(imao):

q){(max;min)@\:flip 4#'(til count x)_\:x+y}[a;b] 
4 5 6 7 8 8 8 8 
1 2 3 4 5 6 7 8 
相關問題