Statically compile and link mod_spatialite

  1. Install vcpkg
    1. git clone https://github.com/Microsoft/vcpkg.git
    1. cd vcpkg
    1. ./bootstrap-vcpkg.sh OR .\bootstrap-vcpkg.bat
    1. vcpkg install libspatialite[freexl,gcp,geocallbacks,rttopo]:x64-windows-static
    1. OR
    1. ./vcpkg install libspatialite[freexl,gcp,geocallbacks,rttopo]:x64-linux

WINDOWS

  • Delete folder buildtrees
  • Open and modify ‘ports/libspatialite/portfile.cmake’
  • Moify line set(CL_FLAGS “”) to have “/MD /DLOADABLE_EXTENSION”
  • Execute vcpkg remove libspatialite:x64-windows-static
  • Then run again vcpk install libspatialite[freexl… (as above)
  • When dll is created it will be in buildtrees\libspatialite\x64-windows-static-rel\spatialite.dll -> RENAME THIS FILE TO mod_spatialite.dll and use as such.

LINUX

  • Same as in windows, just without modifications in portfile.cmake and using “x64-linux”
  • After “vcpkg install”, mod_spatialite.a will be created in “installed/x64-linux/lib”
  • Go there and execute command “gcc -shared -o mod_spatialite.so -Wl,–whole-archive mod_spatialite.a librttopo.a libgeos.a libgeos_c.a libfreexl.a libminizip.a libproj.a libtiff.a libjpeg.a libcurl.a libssl.a libcrypto.a  -Wl,–no-whole-archive“

ps:

On linux, install “sudo apt-get install build-essential pkg-config autoconf libtool”

If package says restored from cache, delete cache folder.

Word embeddings with Skipgram

import numpy as np

def softmax(x):
  return np.divide(np.exp(x), np.sum(np.exp(x), axis=0, keepdims=True))

def softmax_deriv(x):
  return x

#cross entropy loss
def compute_cost(y,o):
  return - np.sum(np.sum(y * np.log(o), axis=0, keepdims=True), axis=1)

#init all biases to 0 and all weights to 1
def initialize_model():
  #<START> I make model <END>
  #windows size 1
  # (<START>, I)
  # (I, make)
  embeddings = np.array([ #embedding size = 7, vocabulary size = 5
    [.1, .2, .3, .4, .5, .6, .7], #<START>
    [.6, .7, .8, .9, .10, .11, .12], #I
    [.11, .12, .13, .14, .15, .16, .17], #make
    [.21, .22, .23, .24, .25, .26, .27], #model
    [.26, .27, .28, .29, .30, .31, .32] #<END>
  ], dtype=np.float64)

  #no bias since it has same performance with it
  W1 = np.array([ #dimensions are vocab_size X embedding_size
    [1,2,3,4,5,6,7], #w1, w2, ..., w7
    [1,1,4,5,6,1,1],
    [1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1]
  ], dtype=np.float64)

  return embeddings, W1

def forward_prop(x, W1):
  o = W1.dot(x)
  o = softmax(o)
  return o

def back_prop(x,y,o,W1):
  dZ = softmax_deriv(o)-y
  grad_x = W1.T.dot(dZ)
  grad_W1 = dZ.dot(x.T)
  return grad_x, grad_W1

#for inner words we repeat batches 2 times, since for some inputs
#e.g. "make", we can have as output "I" and "model" - those are
#words that show up around word "make" for window size 1
def get_batch(embeddings):
  #<START> I make model <END>
  x = np.array([
    embeddings[0], #[<START>] I
    embeddings[1], #<START> [I]
    embeddings[1], #[I] make
    embeddings[2], #I [make]
    embeddings[2], #[make] model
    embeddings[3], #make [model]
    embeddings[3], #[model] <END>
    embeddings[4]  #model [<END>]
  ], dtype=np.float64)

  labels = np.array([
    [0,1,0,0,0], #[<START>] I
    [1,0,0,0,0], # for word I, before is "<START>"
    [0,0,1,0,0], # for word I, after is "make"
    [0,1,0,0,0], # for word make, before is I
    [0,0,0,1,0], #...
    [0,0,1,0,0],
    [0,0,0,0,1], #
    [0,0,0,1,0], #model [<END>]
  ], dtype=np.float64)
  return x.T, labels.T

def gradient_descent(alpha=0.01):
  emb, W1 = initialize_model()
  for _ in range(0, 1000): #1000 epochs
      x,y = get_batch(emb) #batch is always the same - all input samples
      o = forward_prop(x,W1)
      cost = compute_cost(y,o)
      print(f"cost is {cost}")
      grad_emb, grad_W1 = back_prop(x,y,o,W1)
      grad_embT = grad_emb.T
      #since batch input has same word many times (eg make->I, make->model)
      #we need to sum errors for same word input, but different outputs
      grad_embT = np.array([
        grad_embT[0],
        grad_embT[1]+grad_embT[2],
        grad_embT[3]+grad_embT[4], # make->I, make->model
        grad_embT[5]+grad_embT[6],
        grad_embT[7],
      ], dtype=np.float64)
      emb = emb - alpha*grad_embT
      W1 = W1 - alpha*grad_W1
  return emb,W1

emb,W1 = gradient_descent()

embT,_ = get_batch(emb)
sad = np.array([
  embT.T[1], # I
  embT.T[3] # make
], dtype=np.float64).T

rezz = forward_prop(sad, W1)

print(rezz.T)

#here we get
# [[4.99451986e-01 4.95151586e-04 4.94055631e-01 1.66231881e-04
#   5.83099999e-03]
#  [1.68018351e-06 4.99527827e-01 8.52740862e-04 4.97696671e-01
#  1.92108123e-03]]
# so for "I", 0.5 probs that it is "<START>" and 0.5 prob that it is "make"

FNN with 2 hidden layers

import numpy as np

#sigmoid function
def sigmoid(x):
  return 1/(1+np.exp(-x))

#derivative of sigmoid function
def sigmoid_deriv(x):
  return x * (1 - x)

#MSE function
def compute_cost(y,o):
  return np.average(np.power(y - o, 2))

#prepend ones for multiplication with biases b1 b2 b3
def prepend_ones(X):
  return np.hstack([np.ones((X.shape[0],1)), X])

#init all biases to 0 and all weights to 1
def initialize_model():
  W1 = np.array([
    [0,0], # b1 b2
    [1,1], # w1 w3
    [1,1]  # w2 w4
  ], dtype=np.float64).T

  W2 = np.array([
    [0,0], # b1 b2
    [1,1], # w1 w3
    [1,1]  # w2 w4
  ], dtype=np.float64).T

  W3 = np.array([
    [0], # b3
    [1], # w5
    [1]  # w6
  ], dtype=np.float64).T
  return W1.T,W2.T,W3.T

def forward_prop(x, W1, W2, W3):
  h1 = prepend_ones(x).dot(W1)
  h1 = sigmoid(h1)
  h2 = prepend_ones(h1).dot(W2)
  h2 = sigmoid(h2)
  o = prepend_ones(h2).dot(W3)
  o = sigmoid(o)
  return o, h1, h2

def back_prop(x,y,o,h1,h2,W1,W2,W3):
  E = y - o
  dZ = -2*E*sigmoid_deriv(o)
  Wz = W3[1:].T #remove bias terms from matrix
  Wh2 = W2[1:].T #remove bias terms from matrix
  dH2 = dZ.dot(Wz) * sigmoid_deriv(h2)
  dH1 = dH2.dot(Wh2) * sigmoid_deriv(h1)
  grad_W1 = prepend_ones(x).T.dot(dH1)
  grad_W2 = prepend_ones(h1).T.dot(dH2)
  grad_W3 = prepend_ones(h2).T.dot(dZ)
  return grad_W1, grad_W2, grad_W3

def get_batch():
  data = np.array([
    [-2, -1],
    [25, 6],
    [17, 4],
    [-15, -6],
  ])
  labels = np.array([
    [1],
    [0],
    [0],
    [1],
  ])
  return data, labels

def gradient_descent(alpha=0.1):
  W1, W2, W3 = initialize_model()
  for _ in range(0, 1000): #1000 epochs
      x,y = get_batch() #batch is always the same - all input samples
      o,h1,h2 = forward_prop(x,W1,W2,W3)
      cost = compute_cost(y,o)
      print(f"cost is {cost}")
      grad_W1, grad_W2, grad_W3 = back_prop(x,y,o,h1,h2,W1,W2,W3)
      W1 = W1 - alpha*grad_W1
      W2 = W2 - alpha*grad_W2
      W3 = W3 - alpha*grad_W3
  return W1, W2, W3

W1,W2,W3 = gradient_descent()

sad = np.array([
  [-7, -3],
  [20, 2]
])

rezz = forward_prop(sad, W1,W2,W3)

print("Emily: %.3f" % rezz[0][0]) # 0.951 - F
print("Frank: %.3f" % rezz[0][1]) # 0.039 - M

Leetcode – Coin Change 2

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

Example 1:

Input: amount = 5, coins = [1, 2, 5]

Output: 4

Explanation: there are four ways to make up the amount:

5=5

5=2+2+1

5=2+1+1+1

5=1+1+1+1+1

Solution:

This is unbounded knapsack 0/1 problem.

We can try brute-force solution first.

If coins array is not sorted, we need to sort it first in ascending order. In this example it is sorted, so we can proceed. We start with total amount = 5, and then try each possible coin. As we try each coin, we decrease the amount for that coin value (e.g. if we try coin 1, remaining amount is 5-1=4). We do this, until we reach amount of 0 – and at this point we can count this coin combination as one that can make up amount. These are the algorithm steps:

  1. Coins = []; Amount = 5
  2. Coins = [1]; Amount = 4
  3. Coins = [1,1]; Amount = 3
  4. Coins = [1,1,1]; Amount = 2
  5. Coins = [1,1,1,1]; Amount = 1
  6. Coins = [1,1,1,1,1]; Amount = 0 -> First option
  7. Coins = [1,1,1,1,2]; Amount = -1 -> We do not need to test 5 in the next step here ([1,1,1,1,5]; Amount = -4), since it is larger than 2 and amount will be definitely negative. Also, we do not need to test any coin value that comes after 5 (if there is any), since it will also amount to negative value.
  8. Coins = [1,1,1,2]; Amount = 0 -> Second option
  9. Coins = [1,1,1,5]; Amount = -3
  10. Coins = [1,1,2,2]; Amount = -1 -> Notice that we do not test [1,1,2,1], since we would count this combination multiple times – [1,1,1,2] == [1,1,2,1] == [1,2,1,1] == [2,1,1,1]
  11. Coins = [1,1,5]; Amount = -2;
  12. Coins = [1,2,2]; Amount = 0; -> Third option
  13. Coins = [1,2,2,2]; Amount = -2;
  14. Coins = [1,2,5]; Amount = -3;
  15. Coins = [1,5]; Amount = -1;
  16. Coins = [2,2,2]; Amount = -1;
  17. Coins = [2,5]; Amount = -2;
  18. Coins = [5]; Amount = 0; -> Fourth option
  19. Coins = [5,5]; Amount = -5.

Here is the Java code for this solution:

public int change(int amount, int[] coins) {
    Arrays.sort(coins);
    return change(amount, coins, 0);
}

public int change(int amount, int[] coins, int pointer){
    int total = 0;
    for(int i=pointer; i<coins.length; i++) {
        int remaining = amount – coins[i];
        if (remaining < 0) {
            //since everything after this index i is larger than
            //coins[i], we do not need to test further
           
return total;
        } else if(remaining == 0){
            //we found one combination that can make up amount
            //there is no need to test with larger i values, since
            //every coins[i] will have negative “remaining” value
           
return 1 + total;
        } else {
            //there is still some amount remaining, so we need to
            //try using next coin. we can try only same or larger
            //coin than this one, since we do not want to count
            //same combinations multiple times
            //e.g. [1,1,1,2] == [1,1,2,1]
           
total += change(remaining, coins, i);
        }
    }
    return total;
}

Now, we can introduce memorization (we can use dynamic programming), since we do not want to calculate many times the same thing. This way, we can reuse values and algorithm speed will be much better.

We will store in Map calculated results in the following format:

[“remaining” is remaining Amount at this point] -> [“coins[i]” is current coin value] -> [“result” is number of combinations that make up amount at this point]

Here is an example:

  1. Coins = []; Amount = 5
  2. Coins = [1]; Amount = 4
  3. Coins = [1,1]; Amount = 3
  4. Coins = [1,1,1]; Amount = 2
  5. Coins = [1,1,1,1]; Amount = 1
  6. Coins = [1,1,1,1,1]; Amount = 0
    1. After return from this calculation ([1,1,1,1]), “remaining” == 1; “coins[i]” == 1 and “result” == 1. This means that if in future we get to remaining amount with value of 1 and our current coin value at that time is equal to 1 we do not need to compute again, but we can use existing value of “result” – at this point it is == 1; So we save [1] -> [1] -> [1].
  7. Coins = [1,1,1,1,2]; Amount = -1 -> We do not need to test 5 in the next step here ([1,1,1,1,5]; Amount = -4), since it is larger than 2 and amount will be definitely negative. Also, we do not need to test any coin value that comes after 5 (if there is any), since it will also amount to negative value.
  8. Coins = [1,1,1,2]; Amount = 0
    1. After return from this calculation ([1,1,1]), “remaining” == 2; “coins[i]” == 1 and “result” == 2. This means that if in future we get to remaining amount with value of 2 and our current coin value at that time is equal to 2 we do not need to compute again, but we can use existing value of “result” – at this point it is == 2; So we save [2] -> [1] -> [2].
  9. Coins = [1,1,1,5]; Amount = -3
  10. Coins = [1,1,2,2]; Amount = -1
    1. After return from this calculation ([1,1,2]), “remaining” == 1; “coins[i]” == 2 and “result” == 0. This means that if in future we get to remaining amount with value of 1 and our current coin value at that time is equal to 2 we do not need to compute again, but we can use existing value of “result” – at this point it is == 0; So we save [1] -> [2] -> [0].
  11. Coins = [1,1,5]; Amount = -2
    1. We save [3] -> [1] -> [2].
  12. Coins = [1,2,2]; Amount = 0
  13. Coins = [1,2,2,2]; Amount = -2
  14. Coins = [1,2,5]; Amount = -3
    1. We save [2] -> [2] -> [1].
  15. Coins = [1,5]; Amount = -1
    1. We save [4] -> [1] -> [3].
  16. Coins = [2,2,?]; Amount = 1
    1. HERE – we do not need to repeat calculation, but we can use existing result from the map that we saved in step 10. That is [1] -> [2] -> [0]. Remaining value is 1 (this is correct since 5-(2+2)==1) and current coin values == 2. So instead of calculating, we can use pre-calculate value 0.
  17. Coins = [2,5]; Amount = -2
    1. We save [3] -> [2] -> [0].
  18. Coins = [5]; Amount = 0
  19. Coins = [5,5]; Amount = -5.

If we would use only [“remaining”] -> [“result”] we could have the following problems:

After returning from [1,1,1,1,1] ([1,1,1,1]) there is one combination where we would save [1] -> [1].

After returning from [1,1,1,2] ([1,1,1]) there would be two combinations and we would save [2] -> [2] (combinations are [1,1,1, 1,1] and [1,1,1, 2]).

Then, when we reach [1,2] -> we would have “remaining”==2, and we could try using value from map [2] -> [2]. But this way we would have a problem counting same combination two times – namely: [1,2, 1,1] and [1,2, 2] à but we already counted [1,1,1,2] above, so we should not count [1,2,1,1] again!

Here is the Java code for this solution:

public int change(int amount, int[] coins) {
    Arrays.sort(coins);
    //this is map where we store pre-calculated values
   
Map<Integer, Map<Integer, Integer>> dp = new HashMap<>();
    return change(amount, coins, 0, dp);
}

public int change(int amount, int[] coins, int pointer, Map<Integer, Map<Integer, Integer>> dp){
    int total = 0;
    for(int i=pointer; i<coins.length; i++) {
        int remaining = amount – coins[i];
        if (remaining < 0) {
            return total;
        } else if(remaining == 0){
            return 1 + total;
        } else {
            if(dp.containsKey(remaining) && dp.get(remaining).containsKey(coins[i])){
                total += dp.get(remaining).get(coins[i]);
            }
            else {
                int result = change(remaining, coins, i, dp);
                dp.computeIfAbsent(remaining, k -> new HashMap<>()).put(coins[i], result);
                total += result;
            }
        }
    }
    return total;
}

Now we want to convert this dynamic programming solution that use recursion to iterative version that uses 2D matrix for storing the intermediate results.

public int changedp(int amount, int[] coins) {
    Arrays.sort(coins);
    int[][] dp = new int[amount][coins.length];
    for(int i=0; i<dp.length; i++){
        for(int j=0; j<dp[i].length && coins[j]<=i+1; j++){
            if(i+1 == coins[j]){
                dp[i][j] = 1;
            }
            else{
                dp[i][j] = Arrays.stream(dp[i-coins[j]]).skip(j).sum();
           
}
        }
    }
    return Arrays.stream(dp[amount-1]).sum();
}  

Which can be further optimized to

public int[] maxAndDiff(int coins[]){
    int min = 0;
    int max = 0;
    for (int coin : coins) {
        min = Math.min(min, coin);
        max = Math.max(max, coin);
    }
    return new int[]{max,max-min};
}

public int change(int amount, int[] coins) {
    if(amount==0)
        return 1;   //shouldnt this be 0 also?
   
if(coins.length==0)
        return 0;
    Arrays.sort(coins);
    int[] maxDiff = maxAndDiff(coins);
    int height = amount+ maxDiff[1];
    int max = maxDiff[0];
    int[][] dp = new int[max][coins.length];
    for(int i=max-1; i<height; i++){
        int dif2 = coins.length – 1;
        int j = i;
        int k = dif2;
        while (j>=0 && k>=0){
            if(coins[k]<=j+1) {
                if (j + 1 == coins[k]) {
                    dp[j][k] = 1;
                } else {
                    dp[j%max][k] = (k+1==coins.length ? 0 : dp[(j+(coins[k+1]-coins[k]))%max][k+1]) + dp[(j-coins[k])%max][k];
                }
            }
            j-= k>0 ? coins[k]-coins[k-1] : -1;
            k–;
        }
    }
    return dp[(amount+(coins[0]-1))%max][0];
} 



Levenštajnovo rastojanje (Levenshtein Distance)

Kod ovog problema pokušavamo da nađemo ukupan potreban broj brisanja, umetanja ili prepisivanja slova na jednom nizu slova kako bi taj niz slova pretvorili u drugi niz. Na primjer, ako za ulaz imamo nizove „MARKO“ I „JANKO“, levenštajnovo rastojanje iznosi  2 – potrebno je izvšiti dva prepisivanja slova i to „M“ sa „J“ i „R“ sa „N“. Ostala slova se poklapaju i nije ih potrebno mijenjati.

MARKO
JANKO

Ako za ulaz imamo nizove „MILOŠ“ i „LOMIŠ“, levenštajnovo rastojanje iznosi 4 – potrebno je izbrisati slova „M“ i „I“, a potom ubaciti slova „M“ i „I“ (nakon slova „L“ i „O“).

MILO**Š
**LOMIŠ

Kada poklapamo riječi „HORSE“ i „ROS“ levenštajnovo rastojanje iznosi 3 – slovo „H“ prepisujemo sa „R“, zatim brišemo jedno „R“ i brišemo „E“ :

HORSE
RO*S*

Algoritam:

Rekurzivna varijanta:

Poredimo prvo slovo u oba niza. Ako se slova poklapaju (ista su), znači da smo pronašli jedno poklapanje i cijena ovog poklapanja je najmanja – 0. Zatim pokušavamo da poklopimo ostatak nizova (prvi i drugi niz bez prvih slova – koja smo već poklopili). Ako se slova ne poklapaju, onda moramo da nađemo minimalnu cijenu poklapanje od prestala tri slučaja (u svakom od preostalih slučajeva cijena je 1 – imamo ili umetanje ili brisanje ili prepisivanje):

  1. Poklapanje između prvog niza i drugog niza bez prvog slova – ovo se računa kao umetanje.
  2. Poklapanje između drugog niza i prvog niza bez prvog slova – ovo se računa kao brisanje.
  3. Poklapanje između prvog i drugog niza, ali nakon poklapanja slova iako se razlikuju – ovo se računa kao prepisivanje.
 
public int minDistance(String word1, String word2) {
    if(word1.isEmpty() || word2.isEmpty()){
        return Math.max(word1.length(), word2.length());
    }
    if(word1.charAt(0)==word2.charAt(0)){
        return minDistance(word1.substring(1), word2.substring(1));
    }
    else{
        return 1 + Math.min(Math.min(minDistance(word1, word2.substring(1)), minDistance(word1.substring(1), word2)), minDistance(word1.substring(1), word2.substring(1))); 
    }
}

Zaustavni slučaj u algoritmu jeste kada smo došli do toga da je bilo koji od stringova prazan, tj da mu je dužina jednaka 0. U ovom slučaju, cijena je jednaka dužini preostalih karaktera u većem od dva niza – ovi karakteri se računaju ili kao karakteri za brisanje ili umetanje.

Na sledećoj slici se vidi princip preklapanja stringova „MARK“ i „MRAK“ čije je rastojanje jednako 2.

  1. Poklopili smo M i M i zatim možemo da poklopimo ostatak stringova „ARK“ i „RAK“.
  2. A se ne poklapa sa R, i zbog toga imamo tri opcije od kojih ćemo da uzmemo onu sa minimalnom cijenom, tj. Sa minimalnim brojem potrebnih operacija:
    1. Poklapamo „ARK“ i „AK“; tj. Izbacili smo početno slovo u drugom nizu slova. Ovdje probamo varijantu umetanja slova „R“ (pošto je umetanje inverzno brisanju, „R“ se pojavljuje u prethodnom preklapanju „ARK:RAK“ a ne u sledećem „ARK:AK“) – tretiraćemo ovo kao operaciju umetanja i cijena će biti 1…
    2. Poklapamo „RK“ i „RAK“; tj. Izbacili smo početno slovo u prvom nizu slova. Ovdje probamo varijantu brisanja slova „A“ – tretiraćemo ovo kao operaciju brisanja i cijena će biti 1…
    3. Poklapamo „RK“ i „AK“ ; tj. Ovdje probamo varijantu kada poklopimo slova „A“ i „R“ iako su različita – ali tretiraćemo ovo kao operaciju prepisavanja i cijena će biti 1…

Varijanta sa upotrebom dinamičkog programiranja:

Pošto se rekurzivni algoritam može napisati još i kao:

 
//initially i=0 and j=0
public int LD(char[] word1, char[] word2, int i, int j) {
    if(i==word1.length || j==word2.length){
        return Math.max(word1.length-i, word2.length-j);
    }
    if(word1[i]==word2[j]){
        return LD(word1, word2, i+1, j+1);
    }
    else{
        return 1 + Math.min(Math.min(LD(word1, word2, i, j+1), LD(word1, word2, i+1, j)), LD(word1, word2, i+1, j+1));
    }
}

iz njega možemo konstruisati varijantu koja koristi dinamičko programirannje.

Pošto je zaustavni uslov da smo došli do kraja bilo kojeg od dva stringa (poslednjeg indeksa) i u tom slučaju uvijek vraćamo dužinu karaktera iz drugog niza koji potencijalno još uvijek nije prazan, inicijalizujemo prvi redi i prvu kolonu sa brojem karaktera u tom drugom stringu (koji može biti prazan a ne mora).

Prvo inicijalizujemo matricu velicine duzina(word1)*duzina(word2) a zatim punimo prvi red i prvu kolonu.

public int minDistance(String word1, String word2){
    int[][] dp = new int[word1.length()+1][];
    for(int i=0; i<dp.length; i++){
        dp[i] = new int[word2.length()+1];
    }
    for(int i=0; i<dp.length; i++){
        dp[i][0] = i;
    }
    for(int i=0; i<dp[0].length; i++){
        dp[0][i] = i;
    }
    for(int i=1; i<dp.length; i++){
        for(int j=1; j<dp[i].length; j++){
            if(word1.charAt(word1.length()-i) == word2.charAt(word2.length()-j)){
                dp[i][j] = dp[i-1][j-1];
            }
            else{
                dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
            }
        }
    }
    return dp[dp.length-1][dp[dp.length-1].length-1];
}

Na ovoj tabeli ispod, vidimo prvu kolonu i red koji su inicijalizovani na vrijednost koja predstavlja broj karaktera u nizu koji nije prazan (osim ako su oba prazna onda je 0). Crvenom je dat slučaj u kome se dva karaktera poklapaju i u tom slučaju uzimamo dijagonalno vrijednost i prepisujemo je – jer u tom slučaju cijena je jednaka 0.

Najduži zajednički podniz (LCS – longest common subsequence)

Kod ovog problema pokušavamo da nađemo najduži zajednički podniz između dva niza. Na primjer, ako za ulaz imamo nizove „MARKO“ I „JANKO“, najduži zajednički podniz između ova dva niza slova je „AKO“ – dužine 3.

MARKO
JANKO

Ako za ulaz imamo nizove „MILOŠ“ i „LOMIŠ“, najduži zajednički podniz je „MIŠ“ ili „LOŠ“ – dužine 3. To znači da možemo imati više od jednog podniza maksimalne dužine.

MILOŠ
LOMIŠ

Algoritam:

Rekurzivna varijanta:

Poredimo prvo slovo u oba niza. Ako se slova poklapaju (ista su), znači da smo pronašli jedno poklapanje (podniz dužine 1) i zatim pokušavamo da poklopimo ostatak nizova (prvi i drugi niz bez prvih slova – koja smo već poklopili). Ako se slova ne poklapaju, onda moramo da nađemo maksimalno poklapanje od prestala dva slučaja:

  1. Poklapanje između prvog niza i drugog niza bez prvog slova.
  2. Poklapanje između drugog niza i prvog niza bez slova.

U oba slučaja izbacujemo po jedno slovo – i ovim kažemo da se to slovo neće računati dalje u poklapanjima koje dalje rekurzivno pozivamo.

 
public int LCS(String text1, String text2) {
    if(text1.isEmpty() || text2.isEmpty()){
        return 0;
    }
    if(text1.charAt(0)==text2.charAt(0)){
        return 1 + LCS(text1.substring(1), text2.substring(1)); 
    else{
        return Math.max(LCS(text1, text2.substring(1)), LCS(text1.substring(1), text2)); 
    }
}

Na sledećoj slici se vidi princip preklapanja stringova „MARK“ i „MRAK“ čiji je maksimalni zajednički podniz dužine 3.

  1. Poklopili smo M i M i zatim možemo da poklopimo ostatak stringova „ARK“ i „RAK“.
  2. A se ne poklapa sa R, i zbog toga imamo dvije opcije od kojih ćemo da uzmemo maksimalnu:
    1. Poklapamo „ARK“ i „AK“; tj. Izbacili smo početno slovo u drugom nizu slova. Ovdje se poklapaju slova A i A, pa nastavljamo sa poklapanjem ostatka – „RK“ i „K“. Pošto se R i K ne poklapaju, opet imamo dva slučaja:
      1. Poklapamo „RK“ i „“
      1. Poklapamo „K“ i „K“
    1. Poklapamo „RK“ i „RAK“; tj. Izbacili smo početno slovo u prvom nizu slova…

Varijanta sa upotrebom dinamičkog programiranja:

Pošto se rekurzivni algoritam može napisati još i kao:

 
public int LCS(char[] text1, char[] text2, int i, int j) {
    if(i==text1.length || j==text1.length){
        return 0;
    }
    if(text1[i]==text2[j]){
        return 1 + LCS(text1, text2, i+1, j+1);
    }
    else{
        return Math.max(LCS(text1, text2, i, j+1), LCS(text1, text2, i+1, j));
    }
}

iz njega možemo konstruisati varijantu koja koristi dinamičko programirannje.

Pošto je zaustavni uslov da smo došli do kraja bilo kojeg od dva stringa (poslednjeg indeksa) i u tom slučaju uvijek vraćamo 0, inicijalizujemo prvi redi i prvu kolonu sa nulama.

public int LCS(String text1, String text2) {
    int[][] dp = new int[text1.length()+1][];
    for(int i=0; i<dp.length; i++){
        dp[i] = new int[text2.length()+1];
    }
    for(int i=1; i<dp.length; i++){
        for(int j=1; j<dp[i].length; j++){
            if(text1.charAt(text1.length()-i) == text2.charAt(text2.length()-j)){
                dp[i][j] = 1 + dp[i-1][j-1];
            }
            else{
                dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }
    return dp[dp.length-1][dp[dp.length-1].length-1];
}

Na ovoj tabeli ispod, vidimo prvu kolonu i red koji su inicijalizovani na 0 – vrijednost koju vraćamo kada je bilo koji od dva niza prazan (bilo koji od dva stringa prazan). Crvenom je dat slučaj u kome se dva karaktera poklapaju i u tom slučaju uzimamo dijagonalno vrijednost i uvećavamo je za 1.

Generating Nth combination in Java

In case you need to calculate directly N-th combination in Java (without enumerating all possible combinations) here is a way to do it.

In main method we use loop just to print combinations, but if it is needed to list all the combinations for (n k) – this is not a way to do it. This is only to be used if you need directly only N-th combination.

<pre class="wp-block-preformatted">[code language="java"]
public static void main(String[] args) {
        //generate last (1820-1700) 4-combinations of 16 elements
        for(int i=1700; i&lt;1820; i++){
            System.out.println(Arrays.toString(new Circular().combination(16,4,i)));
        }
    }

    long choose(int n, int k){
        if (k < 0 || k > n)
            return 0;
        if (k == 0 || k == n)
            return 1;
        k = Math.min(k, n - k);  // Take advantage of symmetry
        long c = 1;
        for(int i=0; i<k; i++){
            c = c * (n - i) / (i + 1);
        }
        return c;
    }

    /**
     * Generates N-th combination for (n k) binomial
     */
    int[] combination(int n, int k, int N){
        int[] result = new int[k];
        int a = n;
        int b = k;
        long x = (choose(n, k) - 1) - N;
        for(int i=0; i<k; i++){
            a = a-1;
            while(choose(a,b)>x){
                a=a-1;
            }
            result[i] = n-1-a;
            x=x-choose(a,b);
            b=b-1;
        }
        return result;
    }
[/code]</pre>