001 // Copyright 2012, 2013 Brad Block, Pawjaw, LLC. (an Ohio Limited Liability Company) 002 // 003 // This file is part of JFPPR. 004 // 005 // JFPPR is free software: you can redistribute it and/or modify 006 // it under the terms of the GNU General Public License as published by 007 // the Free Software Foundation, either version 3 of the License, or 008 // (at your option) any later version. 009 // 010 // JFPPR is distributed in the hope that it will be useful, 011 // but WITHOUT ANY WARRANTY; without even the implied warranty of 012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 // GNU General Public License for more details. 014 // 015 // You should have received a copy of the GNU General Public License 016 // along with JFPPR. If not, see <http://www.gnu.org/licenses/>. 017 018 package com.pawjaw.graph.fppr.demo; 019 020 public class Utils { 021 public static int editDistance(String a, String b) { 022 int i, j, I = a.length(), J = b.length(); 023 int[][] d = new int[I + 1][J + 1]; 024 for(i = 0;i <= I;i++) 025 d[i][0] = i; 026 for(j = 0;j <= J;j++) 027 d[0][j] = j; 028 for(j = 1;j <= J;j++) 029 for(i = 1;i <= I;i++) 030 if(a.charAt(i - 1) == b.charAt(j - 1)) 031 d[i][j] = d[i - 1][j - 1]; 032 else 033 d[i][j] = Math.min( 034 d[i - 1][j] + 1, Math.min( 035 d[i][j - 1] + 1, 036 d[i - 1][j - 1] + 1)); 037 return d[I][J]; 038 } 039 040 public static float scaledEditSimilarity(String a, String b) { 041 if(a.isEmpty() || b.isEmpty()) 042 return 0; 043 return 1.0f - (float)editDistance(a, b) / (float)Math.max(a.length(), b.length()); 044 } 045 046 public static float scaledEditSimilarity(String a, String b, int max_edit_distance) { 047 int edit_distance; 048 if(a.isEmpty() || b.isEmpty() || (edit_distance = editDistance(a, b)) > max_edit_distance) 049 return 0; 050 return 1.0f - (float)edit_distance / (float)Math.max(a.length(), b.length()); 051 } 052 }