com.hpe.caf.worker.testing.ContentComparer.java Source code

Java tutorial

Introduction

Here is the source code for com.hpe.caf.worker.testing.ContentComparer.java

Source

/*
 * (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hpe.caf.worker.testing;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by ploch on 25/11/2015.
 */
public class ContentComparer {

    private ContentComparer() {
    }

    public static double calculateSimilarity(String s1, String s2) {
        String longer = s1, shorter = s2;
        if (s1.length() < s2.length()) { // longer should always have greater length
            longer = s2;
            shorter = s1;
        }
        int longerLength = longer.length();
        if (longerLength == 0) {
            return 1.0;
            /* both strings are zero length */ }
        return (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double) longerLength;
    }

    public static double calculateSimilarityPercentage(String s1, String s2) {
        return calculateSimilarity(s1, s2) * 100;
    }
}